@arnilo/prism-hosts 0.0.0-stage → 0.13.1
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/CHANGELOG.md +394 -0
- package/LICENSE +21 -0
- package/README.md +34 -2
- package/acp/README.md +87 -0
- package/acp/src/capabilities.ts +184 -0
- package/acp/src/errors.ts +24 -0
- package/acp/src/host.ts +36 -0
- package/acp/src/index.ts +25 -0
- package/acp/src/limits.ts +49 -0
- package/acp/src/mapper.ts +419 -0
- package/acp/src/permission.ts +37 -0
- package/acp/src/projection.ts +39 -0
- package/acp/src/prompt.ts +170 -0
- package/acp/src/serve.ts +345 -0
- package/acp/src/session-map.ts +49 -0
- package/ag-ui/README.md +56 -0
- package/ag-ui/src/a2ui.ts +570 -0
- package/ag-ui/src/ag-ui-mapper.ts +507 -0
- package/ag-ui/src/encrypted-value.ts +40 -0
- package/ag-ui/src/errors.ts +29 -0
- package/ag-ui/src/handler.ts +642 -0
- package/ag-ui/src/index.ts +177 -0
- package/ag-ui/src/input.ts +190 -0
- package/ag-ui/src/limits.ts +279 -0
- package/ag-ui/src/mcp-apps.ts +256 -0
- package/ag-ui/src/mcp.ts +94 -0
- package/ag-ui/src/projection.ts +201 -0
- package/ag-ui/src/projectors.ts +272 -0
- package/ag-ui/src/renderer/bind.ts +152 -0
- package/ag-ui/src/renderer/core.ts +270 -0
- package/ag-ui/src/renderer/index.ts +165 -0
- package/ag-ui/src/replay.ts +189 -0
- package/ag-ui/src/types.ts +66 -0
- package/channels/README.md +139 -0
- package/channels/src/admission.ts +8 -0
- package/channels/src/approvals.ts +262 -0
- package/channels/src/checkpoint-contract.ts +97 -0
- package/channels/src/delivery.ts +116 -0
- package/channels/src/host-ui.ts +356 -0
- package/channels/src/identity.ts +46 -0
- package/channels/src/index.ts +82 -0
- package/channels/src/limits.ts +49 -0
- package/channels/src/memory-stores.ts +112 -0
- package/channels/src/pairing.ts +178 -0
- package/channels/src/runtime-admit.ts +389 -0
- package/channels/src/runtime-core.ts +621 -0
- package/channels/src/runtime-reconcile.ts +299 -0
- package/channels/src/runtime-turn.ts +664 -0
- package/channels/src/runtime-types.ts +95 -0
- package/channels/src/runtime.ts +86 -0
- package/channels/src/secret-ref.ts +42 -0
- package/channels/src/signal.ts +790 -0
- package/channels/src/state.ts +355 -0
- package/channels/src/telegram.ts +1317 -0
- package/channels/src/types.ts +442 -0
- package/devtools/README.md +92 -0
- package/devtools/bin/prism-devtools.ts +63 -0
- package/devtools/src/args.ts +71 -0
- package/devtools/src/bun.d.ts +27 -0
- package/devtools/src/compare.ts +190 -0
- package/devtools/src/errors.ts +15 -0
- package/devtools/src/index.ts +25 -0
- package/devtools/src/replay.ts +36 -0
- package/devtools/src/security.ts +80 -0
- package/devtools/src/serve.ts +259 -0
- package/devtools/src/ui/assets.ts +108 -0
- package/devtools/src/ui/inspector.ts +182 -0
- package/driver-process/README.md +197 -0
- package/driver-process/src/abort.ts +74 -0
- package/driver-process/src/adapter.ts +211 -0
- package/driver-process/src/driver.ts +303 -0
- package/driver-process/src/errors.ts +17 -0
- package/driver-process/src/extend.ts +72 -0
- package/driver-process/src/index.ts +5 -0
- package/driver-process/src/inspect.ts +33 -0
- package/driver-process/src/session.ts +72 -0
- package/driver-process/src/testing.ts +394 -0
- package/driver-process/src/transports/json-rpc.ts +147 -0
- package/driver-process/src/transports/jsonl-stream.ts +12 -0
- package/driver-process/src/transports/types.ts +11 -0
- package/driver-process/src/turn.ts +106 -0
- package/evals/README.md +843 -0
- package/evals/src/calibration.ts +179 -0
- package/evals/src/citation-integrity.ts +98 -0
- package/evals/src/citations.ts +45 -0
- package/evals/src/compare-experiments.ts +153 -0
- package/evals/src/comparison.ts +230 -0
- package/evals/src/curate.ts +257 -0
- package/evals/src/dataset.ts +81 -0
- package/evals/src/erp-invariants.ts +163 -0
- package/evals/src/errors.ts +23 -0
- package/evals/src/experiment.ts +537 -0
- package/evals/src/failure-injection.ts +77 -0
- package/evals/src/feedback.ts +53 -0
- package/evals/src/index.ts +198 -0
- package/evals/src/injection.ts +247 -0
- package/evals/src/judge-panel.ts +109 -0
- package/evals/src/judge.ts +89 -0
- package/evals/src/limits.ts +50 -0
- package/evals/src/report-record.ts +47 -0
- package/evals/src/rubric-judge.ts +334 -0
- package/evals/src/scenario-runner.ts +317 -0
- package/evals/src/scenarios.ts +81 -0
- package/evals/src/score.ts +328 -0
- package/evals/src/scorer.ts +21 -0
- package/evals/src/state-match.ts +130 -0
- package/evals/src/stats.ts +635 -0
- package/evals/src/threshold.ts +117 -0
- package/evals/src/timeline.ts +38 -0
- package/evals/src/toolless-session.ts +33 -0
- package/evals/src/trace.ts +80 -0
- package/evals/src/trajectory.ts +623 -0
- package/evals/src/types.ts +672 -0
- package/evals/src/user-simulator.ts +101 -0
- package/evals/src/util.ts +207 -0
- package/headless/README.md +172 -0
- package/headless/src/answers.ts +91 -0
- package/headless/src/authority.ts +32 -0
- package/headless/src/errors.ts +36 -0
- package/headless/src/index.ts +17 -0
- package/headless/src/limits.ts +11 -0
- package/headless/src/pending.ts +16 -0
- package/headless/src/policy.ts +36 -0
- package/headless/src/resume.ts +103 -0
- package/headless/src/route.ts +153 -0
- package/headless/src/scheduler/clock.ts +22 -0
- package/headless/src/scheduler/cron.ts +19 -0
- package/headless/src/scheduler/firing.ts +58 -0
- package/headless/src/scheduler/index.ts +399 -0
- package/headless/src/scheduler/lease.ts +38 -0
- package/headless/src/scheduler/missed.ts +12 -0
- package/headless/src/scheduler/state.ts +132 -0
- package/host-builder/README.md +251 -0
- package/host-builder/bin/prism-host-builder.ts +169 -0
- package/host-builder/data/api.json +6197 -0
- package/host-builder/data/errors.json +558 -0
- package/host-builder/data/examples/acp.ts +63 -0
- package/host-builder/data/examples/adapters/conformance.ts +34 -0
- package/host-builder/data/examples/adapters/fixtures/rpc-server.json +26 -0
- package/host-builder/data/examples/adapters/fixtures/stream-cli.json +27 -0
- package/host-builder/data/examples/adapters/fixtures/workspace-config.json +28 -0
- package/host-builder/data/examples/adapters/rpc-server.dialect.ts +218 -0
- package/host-builder/data/examples/adapters/rpc-server.ts +309 -0
- package/host-builder/data/examples/adapters/stream-cli.dialect.ts +165 -0
- package/host-builder/data/examples/adapters/stream-cli.ts +256 -0
- package/host-builder/data/examples/adapters/workspace-config.dialect.ts +172 -0
- package/host-builder/data/examples/adapters/workspace-config.ts +251 -0
- package/host-builder/data/examples/advisor.ts +94 -0
- package/host-builder/data/examples/ag-ui-a2ui.ts +80 -0
- package/host-builder/data/examples/ag-ui-mcp-apps.ts +44 -0
- package/host-builder/data/examples/ag-ui-server.ts +118 -0
- package/host-builder/data/examples/agent-durable-approval.ts +43 -0
- package/host-builder/data/examples/api-key-auth.ts +23 -0
- package/host-builder/data/examples/approval.ts +92 -0
- package/host-builder/data/examples/attention-compiler.ts +81 -0
- package/host-builder/data/examples/autonomous-coding-loop.ts +343 -0
- package/host-builder/data/examples/behavior-evaluation.ts +303 -0
- package/host-builder/data/examples/build-workflow.ts +334 -0
- package/host-builder/data/examples/cache-aware-prompt-assembly.ts +139 -0
- package/host-builder/data/examples/caveman-ponytail.ts +197 -0
- package/host-builder/data/examples/cli.ts +31 -0
- package/host-builder/data/examples/coding-approval.ts +115 -0
- package/host-builder/data/examples/coding-browser-evaluation.ts +208 -0
- package/host-builder/data/examples/coding-compaction.ts +30 -0
- package/host-builder/data/examples/coding-goal-verify.ts +121 -0
- package/host-builder/data/examples/coding-tools-capability-gaps.ts +75 -0
- package/host-builder/data/examples/compaction.ts +36 -0
- package/host-builder/data/examples/connected-slack-mcp.ts +67 -0
- package/host-builder/data/examples/context.ts +29 -0
- package/host-builder/data/examples/custom-adapter.ts +256 -0
- package/host-builder/data/examples/custom-builders.ts +66 -0
- package/host-builder/data/examples/custom-loop.ts +89 -0
- package/host-builder/data/examples/custom-provider.ts +70 -0
- package/host-builder/data/examples/custom-session-store.ts +72 -0
- package/host-builder/data/examples/custom-tools-skills-context.ts +97 -0
- package/host-builder/data/examples/decision-models.ts +98 -0
- package/host-builder/data/examples/define-package.ts +188 -0
- package/host-builder/data/examples/delegate.ts +200 -0
- package/host-builder/data/examples/discover-skills.ts +65 -0
- package/host-builder/data/examples/drive-rag-sync.ts +44 -0
- package/host-builder/data/examples/durable-approval.ts +139 -0
- package/host-builder/data/examples/durable-investigation.ts +93 -0
- package/host-builder/data/examples/durable-loops-and-approvals.ts +94 -0
- package/host-builder/data/examples/enterprise-identity.ts +21 -0
- package/host-builder/data/examples/enterprise-policy-audit.ts +50 -0
- package/host-builder/data/examples/enterprise-work-connectors.ts +103 -0
- package/host-builder/data/examples/eval-injection.ts +73 -0
- package/host-builder/data/examples/eval-judges.ts +145 -0
- package/host-builder/data/examples/evals.ts +86 -0
- package/host-builder/data/examples/evaluation-gate.ts +40 -0
- package/host-builder/data/examples/execution-timeline.ts +173 -0
- package/host-builder/data/examples/external-agent.ts +541 -0
- package/host-builder/data/examples/external-app-db-backed.ts +344 -0
- package/host-builder/data/examples/governance-deny.ts +122 -0
- package/host-builder/data/examples/guardrail-packs.ts +240 -0
- package/host-builder/data/examples/headless-host.ts +245 -0
- package/host-builder/data/examples/hooks-audit-command.mjs +31 -0
- package/host-builder/data/examples/hooks-json.ts +87 -0
- package/host-builder/data/examples/host-builder-agent.ts +150 -0
- package/host-builder/data/examples/host-hooks.ts +71 -0
- package/host-builder/data/examples/host-step-loop-timeline.ts +212 -0
- package/host-builder/data/examples/hosted-sandbox.ts +48 -0
- package/host-builder/data/examples/instruction-injection.ts +127 -0
- package/host-builder/data/examples/jsonl-stores-branching.ts +49 -0
- package/host-builder/data/examples/long-term-memory.ts +158 -0
- package/host-builder/data/examples/manifest.ts +112 -0
- package/host-builder/data/examples/mcp-server.ts +48 -0
- package/host-builder/data/examples/mcp-trust.ts +173 -0
- package/host-builder/data/examples/memory-and-wiki.ts +315 -0
- package/host-builder/data/examples/memory-lifecycle.ts +302 -0
- package/host-builder/data/examples/memory-system.ts +255 -0
- package/host-builder/data/examples/messaging-agent.ts +70 -0
- package/host-builder/data/examples/minimal-host-app.ts +41 -0
- package/host-builder/data/examples/model-router-aggregate-budgets.ts +364 -0
- package/host-builder/data/examples/model-router.ts +106 -0
- package/host-builder/data/examples/obscura.ts +48 -0
- package/host-builder/data/examples/observability.ts +116 -0
- package/host-builder/data/examples/open-connector-sidecar.ts +105 -0
- package/host-builder/data/examples/openai-compatible.ts +70 -0
- package/host-builder/data/examples/package-skills.ts +85 -0
- package/host-builder/data/examples/phase9-coding-intelligence.ts +221 -0
- package/host-builder/data/examples/provider-registration.ts +29 -0
- package/host-builder/data/examples/provider-resolver.ts +39 -0
- package/host-builder/data/examples/rag.ts +40 -0
- package/host-builder/data/examples/remote-agent-server.ts +45 -0
- package/host-builder/data/examples/remote-agent.ts +124 -0
- package/host-builder/data/examples/research-ledger.ts +79 -0
- package/host-builder/data/examples/revocation-propagation.ts +287 -0
- package/host-builder/data/examples/run-feedback.ts +93 -0
- package/host-builder/data/examples/scanned-document-rag.ts +48 -0
- package/host-builder/data/examples/sdk-basics.ts +21 -0
- package/host-builder/data/examples/secure-agent.ts +55 -0
- package/host-builder/data/examples/semantic-memory.ts +52 -0
- package/host-builder/data/examples/serve-tools.ts +495 -0
- package/host-builder/data/examples/session-memory.ts +318 -0
- package/host-builder/data/examples/session-search.ts +131 -0
- package/host-builder/data/examples/session.ts +52 -0
- package/host-builder/data/examples/side-call.ts +68 -0
- package/host-builder/data/examples/signal-agent.ts +9 -0
- package/host-builder/data/examples/skills-progressive-disclosure.ts +88 -0
- package/host-builder/data/examples/skills.ts +19 -0
- package/host-builder/data/examples/sqlite-resume.ts +147 -0
- package/host-builder/data/examples/system-project-prompts.ts +74 -0
- package/host-builder/data/examples/system-prompts.ts +19 -0
- package/host-builder/data/examples/telegram-agent.ts +30 -0
- package/host-builder/data/examples/tool-narrowing-planes.ts +99 -0
- package/host-builder/data/examples/tools.ts +29 -0
- package/host-builder/data/examples/validator.ts +67 -0
- package/host-builder/data/examples/web-no-key.ts +85 -0
- package/host-builder/data/examples/web-research.ts +35 -0
- package/host-builder/data/examples/workflow-event-sink.ts +114 -0
- package/host-builder/data/examples/workflow-loop.ts +93 -0
- package/host-builder/data/examples/workflow-multimodal-document.ts +94 -0
- package/host-builder/data/examples/workflow-parallel-research.ts +111 -0
- package/host-builder/data/examples/workflow-postgres-resume.ts +75 -0
- package/host-builder/data/examples/workflow-research-and-review.ts +98 -0
- package/host-builder/data/examples/workflow-sqlite-resume.ts +163 -0
- package/host-builder/data/examples.json +130 -0
- package/host-builder/skills/prism-host-builder/SKILL.md +85 -0
- package/host-builder/skills/prism-host-builder/references/choosing.md +101 -0
- package/host-builder/skills/prism-host-builder/references/layout.md +52 -0
- package/host-builder/skills/prism-host-builder/references/pitfalls.md +50 -0
- package/host-builder/skills/prism-host-builder/references/recipes.md +129 -0
- package/host-builder/skills/prism-host-builder/references/security.md +52 -0
- package/host-builder/skills/prism-host-builder/references/upgrading.md +67 -0
- package/host-builder/skills/prism-host-builder/references/verification.md +108 -0
- package/host-builder/src/check/child.ts +108 -0
- package/host-builder/src/check/conformance.ts +13 -0
- package/host-builder/src/check/inspect.ts +20 -0
- package/host-builder/src/check/manifest.ts +23 -0
- package/host-builder/src/check/runner.ts +181 -0
- package/host-builder/src/check/targets.ts +65 -0
- package/host-builder/src/errors.ts +35 -0
- package/host-builder/src/index.ts +25 -0
- package/host-builder/src/indexes.ts +145 -0
- package/host-builder/src/install/install.ts +400 -0
- package/host-builder/src/install/targets.ts +50 -0
- package/host-builder/src/lookup/api.ts +127 -0
- package/host-builder/src/lookup/bound.ts +38 -0
- package/host-builder/src/lookup/docs.ts +238 -0
- package/host-builder/src/lookup/errors.ts +92 -0
- package/host-builder/src/lookup/examples.ts +117 -0
- package/host-builder/src/lookup/text.ts +60 -0
- package/host-builder/src/server.ts +300 -0
- package/host-builder/src/version.ts +38 -0
- package/mcp-server/README.md +219 -0
- package/mcp-server/src/bounds.ts +23 -0
- package/mcp-server/src/host.ts +31 -0
- package/mcp-server/src/index.ts +27 -0
- package/mcp-server/src/serve-tools.ts +408 -0
- package/mcp-server/src/serve.ts +329 -0
- package/mcp-server/src/server.ts +331 -0
- package/mcp-server/src/session-map.ts +47 -0
- package/mcp-server/src/skill-resources.ts +85 -0
- package/mcp-server/src/types.ts +215 -0
- package/package.json +130 -4
- package/remote/README.md +244 -0
- package/remote/src/attribution.ts +22 -0
- package/remote/src/auth.ts +30 -0
- package/remote/src/bun-module.d.ts +34 -0
- package/remote/src/channel.ts +86 -0
- package/remote/src/connect.ts +212 -0
- package/remote/src/dispatcher.ts +282 -0
- package/remote/src/errors.ts +59 -0
- package/remote/src/host-ui.ts +152 -0
- package/remote/src/http-gate.ts +43 -0
- package/remote/src/index.ts +53 -0
- package/remote/src/jsonl.ts +69 -0
- package/remote/src/limits.ts +43 -0
- package/remote/src/mirror.ts +90 -0
- package/remote/src/pending.ts +22 -0
- package/remote/src/protocol.ts +107 -0
- package/remote/src/serve.ts +560 -0
- package/remote/src/session-proxy.ts +219 -0
- package/remote/src/sse.ts +38 -0
- package/remote/src/stdio-client.ts +41 -0
- package/remote/src/testing-fixtures/serve-stdio.ts +32 -0
- package/remote/src/testing.ts +230 -0
- package/remote/src/transport.ts +139 -0
- package/remote/src/transports/client.ts +126 -0
- package/remote/src/transports/network.ts +268 -0
- package/remote/src/wire.ts +244 -0
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `prism-host-builder install`: copies the `prism-host-builder` skill into a coding agent's project skill
|
|
3
|
+
* directory and, on request, adds the MCP server to the agent's project configuration.
|
|
4
|
+
*
|
|
5
|
+
* Project scope only: every path is resolved through its symlinks and must stay inside `--root`; the user-global
|
|
6
|
+
* agent directories are never touched. The skill copy is stamped with its version and content hash, so a later
|
|
7
|
+
* install replaces it only while the files still match that stamp. The installer never runs a package manager and
|
|
8
|
+
* never writes a secret (the MCP entry holds `command` and `args` only).
|
|
9
|
+
*/
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import {
|
|
12
|
+
existsSync,
|
|
13
|
+
lstatSync,
|
|
14
|
+
mkdirSync,
|
|
15
|
+
readdirSync,
|
|
16
|
+
readFileSync,
|
|
17
|
+
realpathSync,
|
|
18
|
+
renameSync,
|
|
19
|
+
rmSync,
|
|
20
|
+
statSync,
|
|
21
|
+
writeFileSync,
|
|
22
|
+
} from "node:fs";
|
|
23
|
+
import { dirname, isAbsolute, join, relative, sep } from "node:path";
|
|
24
|
+
import { isDeepStrictEqual } from "node:util";
|
|
25
|
+
import { HostBuilderError } from "../errors.js";
|
|
26
|
+
import { INSTALL_TARGETS, type InstallTarget, type InstallTargetName, SERVER_ENTRY, SERVER_NAME, SKILL_NAME } from "./targets.js";
|
|
27
|
+
|
|
28
|
+
const PACKAGE_DIR = join(import.meta.dirname, "..", "..");
|
|
29
|
+
const SKILL_SOURCE = join(PACKAGE_DIR, "skills", SKILL_NAME);
|
|
30
|
+
const STAMP_FILE = ".prism-host-builder.json";
|
|
31
|
+
const PACKAGE_NAME = "@arnilo/prism-hosts/host-builder";
|
|
32
|
+
|
|
33
|
+
export interface InstallOptions {
|
|
34
|
+
readonly target: InstallTargetName;
|
|
35
|
+
/** The project root (an existing directory). Nothing outside it is written. */
|
|
36
|
+
readonly root: string;
|
|
37
|
+
/** Also add the MCP server to the target's project configuration (JSON), or print the snippet (TOML). */
|
|
38
|
+
readonly mcp?: boolean;
|
|
39
|
+
/** Overwrite a modified skill copy or a different `prism` server entry. */
|
|
40
|
+
readonly force?: boolean;
|
|
41
|
+
/** Compute and report the plan; write nothing. */
|
|
42
|
+
readonly dryRun?: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type SkillStatus = "installed" | "upgraded" | "unchanged" | "overwritten";
|
|
46
|
+
export type McpStatus = "added" | "unchanged" | "replaced" | "snippet";
|
|
47
|
+
|
|
48
|
+
export interface InstallResult {
|
|
49
|
+
readonly target: InstallTargetName;
|
|
50
|
+
readonly dryRun: boolean;
|
|
51
|
+
readonly skill: {
|
|
52
|
+
readonly status: SkillStatus;
|
|
53
|
+
/** Project-relative directory of the copy. */
|
|
54
|
+
readonly dir: string;
|
|
55
|
+
readonly version: string;
|
|
56
|
+
readonly files: number;
|
|
57
|
+
};
|
|
58
|
+
readonly mcp?: {
|
|
59
|
+
readonly status: McpStatus;
|
|
60
|
+
readonly file: string;
|
|
61
|
+
/** The exact text to add by hand, for a configuration the installer does not write. */
|
|
62
|
+
readonly snippet?: string;
|
|
63
|
+
};
|
|
64
|
+
/** Extra lines for the person: a printed config, a duplicate warning, a skipped step. */
|
|
65
|
+
readonly notes: readonly string[];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface Stamp {
|
|
69
|
+
readonly package: string;
|
|
70
|
+
readonly version: string;
|
|
71
|
+
readonly contentHash: string;
|
|
72
|
+
readonly files: readonly string[];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface SkillFile {
|
|
76
|
+
readonly path: string;
|
|
77
|
+
readonly bytes: Buffer;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const fail = (code: HostBuilderError["code"], message: string): never => {
|
|
81
|
+
throw new HostBuilderError(code, message);
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
function isInside(root: string, path: string): boolean {
|
|
85
|
+
const rel = relative(root, path);
|
|
86
|
+
return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The absolute path of `rel` under `rootReal` with every existing component resolved through symlinks. Each
|
|
91
|
+
* resolved component must stay inside the root; a dangling link is refused, since a write would follow it.
|
|
92
|
+
*/
|
|
93
|
+
function containedPath(rootReal: string, rel: string): string {
|
|
94
|
+
let current = rootReal;
|
|
95
|
+
const parts = rel.split("/").filter(Boolean);
|
|
96
|
+
for (let index = 0; index < parts.length; index++) {
|
|
97
|
+
let next = join(current, parts[index] as string);
|
|
98
|
+
let stat: ReturnType<typeof lstatSync>;
|
|
99
|
+
try {
|
|
100
|
+
stat = lstatSync(next);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
103
|
+
return join(next, ...parts.slice(index + 1));
|
|
104
|
+
}
|
|
105
|
+
if (stat.isSymbolicLink()) {
|
|
106
|
+
try {
|
|
107
|
+
next = realpathSync(next);
|
|
108
|
+
} catch {
|
|
109
|
+
return fail("ERR_PRISM_HOST_BUILDER_INSTALL_ROOT", `${rel} passes through a symbolic link that does not resolve`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (!isInside(rootReal, next))
|
|
113
|
+
return fail("ERR_PRISM_HOST_BUILDER_INSTALL_ROOT", `${rel} resolves outside the project root ${rootReal}`);
|
|
114
|
+
current = next;
|
|
115
|
+
}
|
|
116
|
+
return current;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Regular files under `dir`, sorted, as project-relative POSIX paths; symbolic links and other entries are skipped. */
|
|
120
|
+
function listFiles(dir: string, prefix = ""): string[] {
|
|
121
|
+
const out: string[] = [];
|
|
122
|
+
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
123
|
+
const rel = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
|
|
124
|
+
if (entry.isDirectory()) out.push(...listFiles(join(dir, entry.name), rel));
|
|
125
|
+
else if (entry.isFile()) out.push(rel);
|
|
126
|
+
}
|
|
127
|
+
return out;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function hashFiles(files: readonly SkillFile[]): string {
|
|
131
|
+
const hash = createHash("sha256");
|
|
132
|
+
for (const file of files) {
|
|
133
|
+
hash.update(file.path);
|
|
134
|
+
hash.update("\0");
|
|
135
|
+
hash.update(String(file.bytes.length));
|
|
136
|
+
hash.update("\0");
|
|
137
|
+
hash.update(file.bytes);
|
|
138
|
+
hash.update("\0");
|
|
139
|
+
}
|
|
140
|
+
return hash.digest("hex");
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function readSkillSource(): SkillFile[] {
|
|
144
|
+
return listFiles(SKILL_SOURCE)
|
|
145
|
+
.filter((path) => path !== STAMP_FILE)
|
|
146
|
+
.map((path) => ({ path, bytes: readFileSync(join(SKILL_SOURCE, path)) }));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function packageVersion(): string {
|
|
150
|
+
const parsed = JSON.parse(readFileSync(join(PACKAGE_DIR, "..", "package.json"), "utf8")) as { version?: unknown };
|
|
151
|
+
return typeof parsed.version === "string" ? parsed.version : "0.0.0";
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function readStamp(dir: string): Stamp | undefined {
|
|
155
|
+
try {
|
|
156
|
+
const parsed = JSON.parse(readFileSync(join(dir, STAMP_FILE), "utf8")) as Partial<Stamp>;
|
|
157
|
+
if (
|
|
158
|
+
parsed.package === PACKAGE_NAME &&
|
|
159
|
+
typeof parsed.version === "string" &&
|
|
160
|
+
typeof parsed.contentHash === "string" &&
|
|
161
|
+
Array.isArray(parsed.files) &&
|
|
162
|
+
parsed.files.every((file) => typeof file === "string" && file !== "" && !file.startsWith("/") && !file.split("/").includes(".."))
|
|
163
|
+
)
|
|
164
|
+
return parsed as Stamp;
|
|
165
|
+
} catch {
|
|
166
|
+
// No stamp, or one that is not ours: the copy is treated as foreign.
|
|
167
|
+
}
|
|
168
|
+
return undefined;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** The hash of the files a stamp lists, as they are on disk now. A missing or unreadable file never matches. */
|
|
172
|
+
function diskHash(dir: string, stamp: Stamp): string | undefined {
|
|
173
|
+
const files: SkillFile[] = [];
|
|
174
|
+
for (const path of stamp.files) {
|
|
175
|
+
try {
|
|
176
|
+
const file = join(dir, path);
|
|
177
|
+
if (!lstatSync(file).isFile()) return undefined;
|
|
178
|
+
files.push({ path, bytes: readFileSync(file) });
|
|
179
|
+
} catch {
|
|
180
|
+
return undefined;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return hashFiles(files);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
interface SkillPlan {
|
|
187
|
+
readonly status: SkillStatus;
|
|
188
|
+
readonly dir: string;
|
|
189
|
+
readonly write: boolean;
|
|
190
|
+
readonly stale: readonly string[];
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function planSkill(dir: string, shown: string, files: readonly SkillFile[], hash: string, version: string, force: boolean): SkillPlan {
|
|
194
|
+
const conflict = (why: string): never =>
|
|
195
|
+
fail("ERR_PRISM_HOST_BUILDER_INSTALL_CONFLICT", `${shown} ${why}. Re-run with --force to overwrite it.`);
|
|
196
|
+
if (!existsSync(dir)) return { status: "installed", dir, write: true, stale: [] };
|
|
197
|
+
if (!statSync(dir).isDirectory()) return fail("ERR_PRISM_HOST_BUILDER_INSTALL_CONFLICT", `${shown} exists and is not a directory`);
|
|
198
|
+
const stamp = readStamp(dir);
|
|
199
|
+
if (stamp === undefined) {
|
|
200
|
+
if (readdirSync(dir).length === 0) return { status: "installed", dir, write: true, stale: [] };
|
|
201
|
+
if (!force) conflict("holds a skill this installer did not write");
|
|
202
|
+
return { status: "overwritten", dir, write: true, stale: [] };
|
|
203
|
+
}
|
|
204
|
+
const modified = diskHash(dir, stamp) !== stamp.contentHash;
|
|
205
|
+
const stale = stamp.files.filter((path) => !files.some((file) => file.path === path));
|
|
206
|
+
if (stamp.version === version && stamp.contentHash === hash) {
|
|
207
|
+
return modified && force ? { status: "overwritten", dir, write: true, stale } : { status: "unchanged", dir, write: false, stale: [] };
|
|
208
|
+
}
|
|
209
|
+
if (modified && !force) conflict(`was edited since version ${stamp.version} was installed`);
|
|
210
|
+
return { status: modified ? "overwritten" : "upgraded", dir, write: true, stale };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function writeAtomic(file: string, text: string | Buffer): void {
|
|
214
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
215
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
216
|
+
writeFileSync(temp, text);
|
|
217
|
+
renameSync(temp, file);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function applySkill(plan: SkillPlan, files: readonly SkillFile[], stamp: Stamp): void {
|
|
221
|
+
for (const path of plan.stale) rmSync(join(plan.dir, path), { force: true });
|
|
222
|
+
for (const file of files) writeAtomic(join(plan.dir, file.path), file.bytes);
|
|
223
|
+
writeAtomic(join(plan.dir, STAMP_FILE), `${JSON.stringify(stamp, null, 2)}\n`);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
type Json = Record<string, unknown>;
|
|
227
|
+
|
|
228
|
+
function isObject(value: unknown): value is Json {
|
|
229
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
interface ConfigPlan {
|
|
233
|
+
readonly status: McpStatus;
|
|
234
|
+
readonly file: string;
|
|
235
|
+
readonly text?: string;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Re-serialises with the file's own indent, line ending and trailing newline. Comments are not JSON and are refused earlier. */
|
|
239
|
+
function render(value: Json, original: string | undefined): string {
|
|
240
|
+
const indent = /^([ \t]+)"/m.exec(original ?? "")?.[1] ?? " ";
|
|
241
|
+
const eol = original?.includes("\r\n") ? "\r\n" : "\n";
|
|
242
|
+
const body = JSON.stringify(value, null, indent).replaceAll("\n", eol);
|
|
243
|
+
return original === undefined || /\r?\n$/.test(original) ? `${body}${eol}` : body;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function planJsonConfig(file: string, shown: string, key: string, force: boolean): ConfigPlan {
|
|
247
|
+
const refuse = (why: string): never => fail("ERR_PRISM_HOST_BUILDER_INSTALL_CONFIG", `${shown} ${why}; it was not changed`);
|
|
248
|
+
let original: string | undefined;
|
|
249
|
+
let root: Json = {};
|
|
250
|
+
if (existsSync(file)) {
|
|
251
|
+
original = readFileSync(file, "utf8");
|
|
252
|
+
let parsed: unknown;
|
|
253
|
+
try {
|
|
254
|
+
parsed = JSON.parse(original.replace(/^/, ""));
|
|
255
|
+
} catch (error) {
|
|
256
|
+
return refuse(`is not valid JSON (${error instanceof Error ? error.message : String(error)})`);
|
|
257
|
+
}
|
|
258
|
+
if (!isObject(parsed)) return refuse("does not hold a JSON object");
|
|
259
|
+
root = parsed;
|
|
260
|
+
}
|
|
261
|
+
const servers = root[key];
|
|
262
|
+
if (servers !== undefined && !isObject(servers)) return refuse(`has a "${key}" value that is not an object`);
|
|
263
|
+
const existing = servers?.[SERVER_NAME];
|
|
264
|
+
if (existing !== undefined && isDeepStrictEqual(existing, SERVER_ENTRY)) return { status: "unchanged", file };
|
|
265
|
+
if (existing !== undefined && !force)
|
|
266
|
+
return fail(
|
|
267
|
+
"ERR_PRISM_HOST_BUILDER_INSTALL_CONFLICT",
|
|
268
|
+
`${shown} already has a different "${SERVER_NAME}" server under "${key}". Re-run with --force to replace it.`,
|
|
269
|
+
);
|
|
270
|
+
const next: Json = { ...root, [key]: { ...(servers ?? {}), [SERVER_NAME]: { ...SERVER_ENTRY, args: [...SERVER_ENTRY.args] } } };
|
|
271
|
+
const text = render(next, original);
|
|
272
|
+
// Parse check after: the written text must read back as the original with only our entry changed.
|
|
273
|
+
const back = JSON.parse(text.replace(/^/, "")) as Json;
|
|
274
|
+
const expected = structuredClone(root);
|
|
275
|
+
expected[key] = { ...((expected[key] as Json | undefined) ?? {}), [SERVER_NAME]: { ...SERVER_ENTRY, args: [...SERVER_ENTRY.args] } };
|
|
276
|
+
if (!isDeepStrictEqual(back, expected)) return refuse("could not be merged without changing other entries");
|
|
277
|
+
return { status: existing === undefined ? "added" : "replaced", file, text };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** The exact text for a TOML configuration the installer does not write. */
|
|
281
|
+
function tomlSnippet(target: InstallTarget): string {
|
|
282
|
+
const config = target.config as NonNullable<InstallTarget["config"]>;
|
|
283
|
+
return [
|
|
284
|
+
`[${config.key}.${SERVER_NAME}]`,
|
|
285
|
+
`command = "${SERVER_ENTRY.command}"`,
|
|
286
|
+
`args = [${SERVER_ENTRY.args.map((arg) => `"${arg}"`).join(", ")}]`,
|
|
287
|
+
].join("\n");
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** What a Prism builder agent lists in code: the skill is found by `contextFiles`, the MCP server by `@arnilo/prism-extensions/mcp`. */
|
|
291
|
+
function prismSnippet(): string {
|
|
292
|
+
return [
|
|
293
|
+
'import contextFiles from "@arnilo/prism-extensions/context-files";',
|
|
294
|
+
'import mcp from "@arnilo/prism-extensions/mcp";',
|
|
295
|
+
"",
|
|
296
|
+
"packages: [",
|
|
297
|
+
" contextFiles({ root: process.cwd() }), // discovers .agents/skills (and .claude/skills) by default",
|
|
298
|
+
" mcp({",
|
|
299
|
+
" servers: [",
|
|
300
|
+
` { id: "prism-host-builder", transport: "stdio", command: "${SERVER_ENTRY.command}", args: [${SERVER_ENTRY.args.map((arg) => `"${arg}"`).join(", ")}], allow: "stdio:${SERVER_ENTRY.command}" },`,
|
|
301
|
+
" ],",
|
|
302
|
+
" }),",
|
|
303
|
+
"],",
|
|
304
|
+
].join("\n");
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** A sibling skill directory of another target that already holds a copy under a different real path. */
|
|
308
|
+
function duplicateNote(rootReal: string, own: string, target: InstallTarget): string | undefined {
|
|
309
|
+
for (const other of Object.values(INSTALL_TARGETS)) {
|
|
310
|
+
if (other.skillDir === target.skillDir) continue;
|
|
311
|
+
try {
|
|
312
|
+
const dir = containedPath(rootReal, `${other.skillDir}/${SKILL_NAME}`);
|
|
313
|
+
if (dir !== own && readStamp(dir) !== undefined)
|
|
314
|
+
return `${other.skillDir}/${SKILL_NAME} also holds a copy; an agent that reads both directories (Cursor) will list the skill twice. Keep one.`;
|
|
315
|
+
} catch {
|
|
316
|
+
// A sibling that does not resolve inside the root is not our business here.
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return undefined;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Installs the skill (and, with `mcp`, the MCP server entry) for one target. Every conflict is detected before the
|
|
324
|
+
* first write, so a refused install changes nothing. `dryRun` returns the same result without writing.
|
|
325
|
+
*/
|
|
326
|
+
export function installHostBuilder(options: InstallOptions): InstallResult {
|
|
327
|
+
const target = INSTALL_TARGETS[options.target];
|
|
328
|
+
if (target === undefined || !Object.hasOwn(INSTALL_TARGETS, options.target))
|
|
329
|
+
throw new RangeError(`unknown install target "${String(options.target)}"`);
|
|
330
|
+
const force = options.force === true;
|
|
331
|
+
const dryRun = options.dryRun === true;
|
|
332
|
+
let rootReal: string;
|
|
333
|
+
try {
|
|
334
|
+
rootReal = realpathSync(options.root);
|
|
335
|
+
if (!statSync(rootReal).isDirectory()) throw new Error("not a directory");
|
|
336
|
+
} catch {
|
|
337
|
+
return fail("ERR_PRISM_HOST_BUILDER_INSTALL_ROOT", `${options.root} is not a directory`);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const files = readSkillSource();
|
|
341
|
+
const hash = hashFiles(files);
|
|
342
|
+
const version = packageVersion();
|
|
343
|
+
const skillRel = `${target.skillDir}/${SKILL_NAME}`;
|
|
344
|
+
const skill = planSkill(containedPath(rootReal, skillRel), skillRel, files, hash, version, force);
|
|
345
|
+
const notes: string[] = [];
|
|
346
|
+
|
|
347
|
+
let config: ConfigPlan | undefined;
|
|
348
|
+
let snippet: string | undefined;
|
|
349
|
+
if (options.target === "prism") {
|
|
350
|
+
snippet = prismSnippet();
|
|
351
|
+
notes.push("Add to the Prism builder agent's packages:", snippet);
|
|
352
|
+
} else if (options.mcp === true) {
|
|
353
|
+
if (target.config === undefined) {
|
|
354
|
+
notes.push(`target "${options.target}" has no MCP configuration to write; use --target claude, cursor or codex for --mcp.`);
|
|
355
|
+
} else if (target.config.format === "toml") {
|
|
356
|
+
snippet = tomlSnippet(target);
|
|
357
|
+
config = { status: "snippet", file: target.config.file };
|
|
358
|
+
notes.push(
|
|
359
|
+
`Add to ${target.config.file} (Codex reads project configuration only for a trusted project; the installer writes no TOML):`,
|
|
360
|
+
snippet,
|
|
361
|
+
);
|
|
362
|
+
} else {
|
|
363
|
+
config = planJsonConfig(containedPath(rootReal, target.config.file), target.config.file, target.config.key, force);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
const duplicate = duplicateNote(rootReal, skill.dir, target);
|
|
367
|
+
if (duplicate !== undefined) notes.push(duplicate);
|
|
368
|
+
|
|
369
|
+
if (!dryRun) {
|
|
370
|
+
if (skill.write) applySkill(skill, files, { package: PACKAGE_NAME, version, contentHash: hash, files: files.map((file) => file.path) });
|
|
371
|
+
if (config?.text !== undefined) writeAtomic(config.file, config.text);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
return {
|
|
375
|
+
target: options.target,
|
|
376
|
+
dryRun,
|
|
377
|
+
skill: { status: skill.status, dir: skillRel, version, files: files.length },
|
|
378
|
+
...(config === undefined
|
|
379
|
+
? {}
|
|
380
|
+
: {
|
|
381
|
+
mcp: {
|
|
382
|
+
status: config.status,
|
|
383
|
+
file: (target.config as NonNullable<InstallTarget["config"]>).file,
|
|
384
|
+
...(config.status === "snippet" && snippet !== undefined ? { snippet } : {}),
|
|
385
|
+
},
|
|
386
|
+
}),
|
|
387
|
+
notes,
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** The lines the CLI prints for a result. */
|
|
392
|
+
export function describeInstall(result: InstallResult): string[] {
|
|
393
|
+
const lines: string[] = [];
|
|
394
|
+
if (result.dryRun) lines.push("dry run: nothing was written");
|
|
395
|
+
lines.push(`skill ${result.skill.status}: ${result.skill.dir} (version ${result.skill.version}, ${result.skill.files} files)`);
|
|
396
|
+
if (result.mcp !== undefined && result.mcp.status !== "snippet")
|
|
397
|
+
lines.push(`mcp ${result.mcp.status}: "${SERVER_NAME}" in ${result.mcp.file}`);
|
|
398
|
+
lines.push(...result.notes);
|
|
399
|
+
return lines;
|
|
400
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The installer's targets. One row per coding agent; adding a target is adding a row.
|
|
3
|
+
*
|
|
4
|
+
* Conventions (plan 215 Task 13 (d), checked against the agents' docs on 2026-11-07):
|
|
5
|
+
* - Claude Code reads `.claude/skills` and the project `.mcp.json` (`mcpServers`).
|
|
6
|
+
* - Codex CLI reads `.agents/skills` and `.codex/config.toml` (`[mcp_servers.<name>]`, TOML).
|
|
7
|
+
* - Cursor reads `.agents/skills` (and `.claude/skills`) and `.cursor/mcp.json` (`mcpServers`).
|
|
8
|
+
* - Prism's `contextFiles` discovers `.agents/skills` first, then `.claude/skills`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export type InstallTargetName = "claude" | "codex" | "cursor" | "agents" | "prism";
|
|
12
|
+
|
|
13
|
+
/** Where a target keeps its project MCP configuration. */
|
|
14
|
+
export interface ConfigTarget {
|
|
15
|
+
/** Project-relative file. */
|
|
16
|
+
readonly file: string;
|
|
17
|
+
/** `json`: merged in place. `toml`: only printed (the package takes no TOML dependency). */
|
|
18
|
+
readonly format: "json" | "toml";
|
|
19
|
+
/** The JSON key (or TOML table prefix) that holds the servers. */
|
|
20
|
+
readonly key: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface InstallTarget {
|
|
24
|
+
/** Project-relative directory the skill is copied into, as `<skillDir>/prism-host-builder`. */
|
|
25
|
+
readonly skillDir: string;
|
|
26
|
+
readonly config?: ConfigTarget;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const INSTALL_TARGETS: Readonly<Record<InstallTargetName, InstallTarget>> = {
|
|
30
|
+
claude: { skillDir: ".claude/skills", config: { file: ".mcp.json", format: "json", key: "mcpServers" } },
|
|
31
|
+
codex: { skillDir: ".agents/skills", config: { file: ".codex/config.toml", format: "toml", key: "mcp_servers" } },
|
|
32
|
+
cursor: { skillDir: ".agents/skills", config: { file: ".cursor/mcp.json", format: "json", key: "mcpServers" } },
|
|
33
|
+
agents: { skillDir: ".agents/skills" },
|
|
34
|
+
prism: { skillDir: ".agents/skills" },
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export const INSTALL_TARGET_NAMES = Object.keys(INSTALL_TARGETS) as readonly InstallTargetName[];
|
|
38
|
+
|
|
39
|
+
/** The skill directory name under a target's `skillDir`. */
|
|
40
|
+
export const SKILL_NAME = "prism-host-builder";
|
|
41
|
+
|
|
42
|
+
/** The server name the installer writes. Another entry under this name that differs is a conflict. */
|
|
43
|
+
export const SERVER_NAME = "prism";
|
|
44
|
+
|
|
45
|
+
/** The entry written under the server key. `command` and `args` only: no env, no token. */
|
|
46
|
+
export const SERVER_ENTRY = { command: "bunx", args: ["--package", "@arnilo/prism-hosts", "prism-host-builder", "mcp"] } as const;
|
|
47
|
+
|
|
48
|
+
export function isInstallTargetName(value: string): value is InstallTargetName {
|
|
49
|
+
return Object.hasOwn(INSTALL_TARGETS, value);
|
|
50
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import type { ApiExport, ApiIndex } from "../indexes.js";
|
|
2
|
+
import { nearest, tokens } from "./text.js";
|
|
3
|
+
|
|
4
|
+
export interface ApiQuery {
|
|
5
|
+
/** An exact export name. */
|
|
6
|
+
readonly symbol?: string;
|
|
7
|
+
/** Words matched against names, signatures and summaries. */
|
|
8
|
+
readonly query?: string;
|
|
9
|
+
/** A package name (`@arnilo/prism-extensions/approval`) that limits the search. */
|
|
10
|
+
readonly package?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface ApiMatch {
|
|
14
|
+
readonly package: string;
|
|
15
|
+
readonly subpath: string;
|
|
16
|
+
/** The import specifier, for example `@arnilo/prism/testing`. */
|
|
17
|
+
readonly specifier: string;
|
|
18
|
+
readonly name: string;
|
|
19
|
+
readonly kind: ApiExport["kind"];
|
|
20
|
+
readonly signature: string;
|
|
21
|
+
/** Interface and class members, so a field name is read here and never guessed. */
|
|
22
|
+
readonly members?: readonly string[];
|
|
23
|
+
readonly summary?: string;
|
|
24
|
+
readonly docs: readonly string[];
|
|
25
|
+
readonly examples: readonly string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ApiResult {
|
|
29
|
+
readonly found: boolean;
|
|
30
|
+
readonly matches: readonly ApiMatch[];
|
|
31
|
+
/** The nearest names when nothing matched. */
|
|
32
|
+
readonly nearest: readonly string[];
|
|
33
|
+
readonly note?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const MAX_MATCHES = 10;
|
|
37
|
+
const MAX_SIGNATURE = 4000;
|
|
38
|
+
|
|
39
|
+
function flatten(index: ApiIndex, packageName: string | undefined): ApiMatch[] {
|
|
40
|
+
const matches: ApiMatch[] = [];
|
|
41
|
+
for (const pkg of index.packages) {
|
|
42
|
+
for (const entry of pkg.entries) {
|
|
43
|
+
if (packageName !== undefined && pkg.name !== packageName && entry.specifier !== packageName) continue;
|
|
44
|
+
for (const item of entry.exports) {
|
|
45
|
+
matches.push({
|
|
46
|
+
package: pkg.name,
|
|
47
|
+
subpath: entry.subpath,
|
|
48
|
+
specifier: entry.specifier,
|
|
49
|
+
name: item.name,
|
|
50
|
+
kind: item.kind,
|
|
51
|
+
signature: item.signature.length > MAX_SIGNATURE ? `${item.signature.slice(0, MAX_SIGNATURE)} …` : item.signature,
|
|
52
|
+
...(item.members !== undefined ? { members: item.members } : {}),
|
|
53
|
+
...(item.summary !== undefined ? { summary: item.summary } : {}),
|
|
54
|
+
docs: item.docs ?? [],
|
|
55
|
+
examples: item.examples ?? [],
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return matches;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Looks up a public name. `symbol` is an exact, case-sensitive match across every package and subpath;
|
|
65
|
+
* `query` is a lexical search over names, signatures and summaries (a name hit outranks a signature hit).
|
|
66
|
+
* With neither, or no hit, the result is `found: false` with the nearest names, never an exception.
|
|
67
|
+
*/
|
|
68
|
+
export function lookupApi(index: ApiIndex, input: ApiQuery): ApiResult {
|
|
69
|
+
const all = flatten(index, input.package);
|
|
70
|
+
if (input.package !== undefined && all.length === 0) {
|
|
71
|
+
return {
|
|
72
|
+
found: false,
|
|
73
|
+
matches: [],
|
|
74
|
+
nearest: nearest(
|
|
75
|
+
index.packages.flatMap((pkg) => [pkg.name, ...pkg.entries.map((entry) => entry.specifier)]),
|
|
76
|
+
input.package,
|
|
77
|
+
),
|
|
78
|
+
note: `no package named "${input.package}"`,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
if (input.symbol !== undefined && input.symbol.trim() !== "") {
|
|
82
|
+
const symbol = input.symbol.trim();
|
|
83
|
+
const exact = all.filter((match) => match.name === symbol);
|
|
84
|
+
if (exact.length > 0) return { found: true, matches: exact.slice(0, MAX_MATCHES), nearest: [] };
|
|
85
|
+
return {
|
|
86
|
+
found: false,
|
|
87
|
+
matches: [],
|
|
88
|
+
nearest: nearest(
|
|
89
|
+
all.map((match) => match.name),
|
|
90
|
+
symbol,
|
|
91
|
+
),
|
|
92
|
+
note: `no export named "${symbol}"`,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const words = tokens(input.query ?? "");
|
|
96
|
+
if (words.length === 0) return { found: false, matches: [], nearest: [], note: "pass a symbol or a query" };
|
|
97
|
+
const scored: Array<{ match: ApiMatch; score: number }> = [];
|
|
98
|
+
for (const match of all) {
|
|
99
|
+
const nameTokens = new Set(tokens(match.name));
|
|
100
|
+
const lowerName = match.name.toLowerCase();
|
|
101
|
+
const signature = match.signature.toLowerCase();
|
|
102
|
+
const summary = (match.summary ?? "").toLowerCase();
|
|
103
|
+
let score = 0;
|
|
104
|
+
for (const word of words) {
|
|
105
|
+
if (lowerName === word) score += 12;
|
|
106
|
+
else if (nameTokens.has(word)) score += 6;
|
|
107
|
+
else if (lowerName.includes(word)) score += 3;
|
|
108
|
+
if (signature.includes(word)) score += 1;
|
|
109
|
+
if (summary.includes(word)) score += 2;
|
|
110
|
+
}
|
|
111
|
+
if (score > 0) scored.push({ match, score });
|
|
112
|
+
}
|
|
113
|
+
// Equal scores: the shorter name is the closer match.
|
|
114
|
+
scored.sort((a, b) => b.score - a.score || a.match.name.length - b.match.name.length);
|
|
115
|
+
if (scored.length === 0) {
|
|
116
|
+
return {
|
|
117
|
+
found: false,
|
|
118
|
+
matches: [],
|
|
119
|
+
nearest: nearest(
|
|
120
|
+
all.map((match) => match.name),
|
|
121
|
+
(input.query ?? "").trim(),
|
|
122
|
+
),
|
|
123
|
+
note: "no export matched the query",
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
return { found: true, matches: scored.slice(0, MAX_MATCHES).map((entry) => entry.match), nearest: [] };
|
|
127
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** The most bytes of text one tool result or resource read returns. */
|
|
2
|
+
export const MAX_RESULT_BYTES = 64 * 1024;
|
|
3
|
+
|
|
4
|
+
const encoder = new TextEncoder();
|
|
5
|
+
const decoder = new TextDecoder("utf-8", { fatal: false });
|
|
6
|
+
|
|
7
|
+
/** UTF-8 length of `text`. */
|
|
8
|
+
export function byteLength(text: string): number {
|
|
9
|
+
return encoder.encode(text).byteLength;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** `text` cut to at most `maxBytes` of UTF-8 on a character boundary, with `truncated` saying whether it was cut. */
|
|
13
|
+
export function truncateBytes(text: string, maxBytes: number): { readonly text: string; readonly truncated: boolean } {
|
|
14
|
+
const bytes = encoder.encode(text);
|
|
15
|
+
if (bytes.byteLength <= maxBytes) return { text, truncated: false };
|
|
16
|
+
// A cut inside a multi-byte character decodes to U+FFFD at the end; drop it.
|
|
17
|
+
const cut = decoder.decode(bytes.subarray(0, maxBytes)).replace(/�+$/, "");
|
|
18
|
+
return { text: cut, truncated: true };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The marker appended to text that was cut. */
|
|
22
|
+
export function truncationMarker(omittedBytes: number): string {
|
|
23
|
+
return `\n[truncated: ${omittedBytes} bytes omitted]`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Serializes a result for the wire. A result over {@linkcode MAX_RESULT_BYTES} is cut and marked, so the text
|
|
28
|
+
* a client reads always says when it is incomplete. Lookup functions already bound their own lists; this is the
|
|
29
|
+
* last guard.
|
|
30
|
+
*/
|
|
31
|
+
export function boundedJson(value: unknown, maxBytes: number = MAX_RESULT_BYTES): string {
|
|
32
|
+
const text = JSON.stringify(value, null, 2);
|
|
33
|
+
const total = byteLength(text);
|
|
34
|
+
if (total <= maxBytes) return text;
|
|
35
|
+
const marker = truncationMarker(total - maxBytes);
|
|
36
|
+
const cut = truncateBytes(text, maxBytes - byteLength(marker));
|
|
37
|
+
return `${cut.text}${truncationMarker(total - byteLength(cut.text))}`;
|
|
38
|
+
}
|