@staix/agent-hosts 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -1
- package/package.json +1 -1
- package/src/fs-safe.ts +6 -1
- package/src/hosts.ts +47 -0
- package/src/index.ts +3 -0
- package/src/paths.ts +54 -1
- package/src/refusal.ts +6 -0
- package/src/skills.ts +404 -0
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
Install an exact version after it is published.
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
|
-
bun add --exact @staix/agent-hosts@0.
|
|
8
|
+
bun add --exact @staix/agent-hosts@0.3.0
|
|
9
9
|
```
|
|
10
10
|
|
|
11
11
|
## Supported hosts
|
|
@@ -88,6 +88,29 @@ The JSON codec accepts strict JSON and keeps unrelated bytes. The TOML codecs us
|
|
|
88
88
|
| `RefusalCode`, `UndoNoopCode` | Machine-readable identifiers from `REFUSAL_CODES` and `UNDO_NOOP_CODES`. |
|
|
89
89
|
| `ConfigImage`, `JsonMcpCodecOptions` | Base64 `bytes` or `null` for an absent file, plus numeric `mode`, and the JSON codec's key and entry options. |
|
|
90
90
|
|
|
91
|
+
## Skill roots and links
|
|
92
|
+
|
|
93
|
+
`SKILL_HOSTS` lists verified user installation roots for Claude, Codex, Pi, Qwen, OpenCode, and Gemini. Each definition lists its verified host versions. `resolveSkillRoots({ home, env, hosts?, scopes?, workspaceRoot?, redirectManagedProfiles? })` returns roots, redirects and refusals. Use the injected home and environment. The resolver applies the same override validation and optional managed-profile redirects as MCP. For OpenCode, it selects `OPENCODE_CONFIG_DIR/skills` ahead of `XDG_CONFIG_HOME/opencode/skills`. Project scope has no supported skill roots in this release. See the [versioned skill root verification](docs/verification/2026-11-29-skill-roots.md).
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
import { applySkillEntry, planSkillEntry, resolveSkillRoots, undoSkillEntry } from "@staix/agent-hosts";
|
|
97
|
+
|
|
98
|
+
const { roots } = resolveSkillRoots({ home, env, hosts: ["codex"] });
|
|
99
|
+
const root = roots.codex?.[0];
|
|
100
|
+
if (!root) throw new Error("No Codex skill root resolved");
|
|
101
|
+
|
|
102
|
+
const target = { host: "codex" as const, root, name: "example", receiptDir };
|
|
103
|
+
const preview = planSkillEntry({ ...target, sourcePath });
|
|
104
|
+
if (preview.change === "refused") throw new Error(preview.reason);
|
|
105
|
+
applySkillEntry(preview);
|
|
106
|
+
// Later, with the same target and receipt directory:
|
|
107
|
+
undoSkillEntry(target);
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Pass absolute physical paths for `root`, `receiptDir` and `sourcePath`. The source is an existing directory whose contents the caller manages. Preview writes nothing. Apply installs a relative symlink and records versioned ownership in the receipt directory. `classifySkillTarget({ targetPath, host?, receiptDir? })` recognizes an owned link when its recorded identity matches. Existing foreign links, unmanaged files or directories, sibling-tool ownership markers and the reserved `.system` name are refused.
|
|
111
|
+
|
|
112
|
+
Use the same `receiptDir` for each operation on a host and skill name. A changed profile root requires `retarget: true` in a new preview. Apply then publishes at the new root and removes the unchanged old link. Undo removes only the unchanged recorded link. If the link has already been deleted, undo retires the receipt and reports `entry-already-absent`. To resume an interrupted apply, preview and apply the same root and source again.
|
|
113
|
+
|
|
91
114
|
## Consumer migration
|
|
92
115
|
|
|
93
116
|
For each migration, use one PR per consumer and pin `@staix/agent-hosts` to the exact release. Keep the existing entry name and pass the consumer's existing setup directory as `receiptDir` so undo can find earlier receipts. Replay the [copy fixtures](fixtures/copies/) and [legacy receipts](fixtures/receipts/), and list behavior changes in the consumer PR. [Fixture divergences](fixtures/DIVERGENCES.md)
|
package/package.json
CHANGED
package/src/fs-safe.ts
CHANGED
|
@@ -43,13 +43,18 @@ function checkPath(file: string, directory = false): Stats | undefined {
|
|
|
43
43
|
return stat;
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
/** Inspect a directory chain without following a link at any point. */
|
|
47
|
+
export function checkPhysicalDirectory(directory: string): Stats | undefined {
|
|
48
|
+
return checkPath(directory, true);
|
|
49
|
+
}
|
|
50
|
+
|
|
46
51
|
function assertPhysical(file: string, existing: string): void {
|
|
47
52
|
if (realPath(existing) !== existing) {
|
|
48
53
|
throw new EntryRefusal("unsafe-path", `${file}: redirected path; use the exact physical path spelling`, { file: file });
|
|
49
54
|
}
|
|
50
55
|
}
|
|
51
56
|
|
|
52
|
-
function ensureDirectory(directory: string): void {
|
|
57
|
+
export function ensureDirectory(directory: string): void {
|
|
53
58
|
checkPath(directory, true);
|
|
54
59
|
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
55
60
|
checkPath(directory, true);
|
package/src/hosts.ts
CHANGED
|
@@ -119,3 +119,50 @@ export const HOSTS = {
|
|
|
119
119
|
} as const satisfies Record<string, HostDefinition>;
|
|
120
120
|
|
|
121
121
|
export type HostId = keyof typeof HOSTS;
|
|
122
|
+
|
|
123
|
+
export interface HostSkillDefinition {
|
|
124
|
+
readonly path: string;
|
|
125
|
+
readonly override: HomeOverride;
|
|
126
|
+
readonly preferredOverride?: HomeOverride;
|
|
127
|
+
readonly managedProfile?: "claude" | "codex";
|
|
128
|
+
readonly verified: readonly [string, ...string[]];
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Verified user installation roots. Hosts may discover skills from additional locations. */
|
|
132
|
+
export const SKILL_HOSTS = {
|
|
133
|
+
claude: {
|
|
134
|
+
path: "skills",
|
|
135
|
+
override: { key: "CLAUDE_CONFIG_DIR", rule: "trim-presence", directory: ".claude" },
|
|
136
|
+
managedProfile: "claude",
|
|
137
|
+
verified: ["2.1.332"],
|
|
138
|
+
},
|
|
139
|
+
codex: {
|
|
140
|
+
path: "skills",
|
|
141
|
+
override: HOSTS.codex.files[0].override,
|
|
142
|
+
managedProfile: "codex",
|
|
143
|
+
verified: ["0.172.0"],
|
|
144
|
+
},
|
|
145
|
+
pi: {
|
|
146
|
+
path: "skills",
|
|
147
|
+
override: HOSTS.pi.files[0].override,
|
|
148
|
+
verified: ["1.6.1"],
|
|
149
|
+
},
|
|
150
|
+
qwen: {
|
|
151
|
+
path: "skills",
|
|
152
|
+
override: HOSTS.qwen.files[0].override,
|
|
153
|
+
verified: ["0.26.9", "0.27.1"],
|
|
154
|
+
},
|
|
155
|
+
opencode: {
|
|
156
|
+
path: "opencode/skills",
|
|
157
|
+
override: HOSTS.opencode.files[0].override,
|
|
158
|
+
preferredOverride: { key: "OPENCODE_CONFIG_DIR", rule: "absolute-only", directory: "" },
|
|
159
|
+
verified: ["1.19.5"],
|
|
160
|
+
},
|
|
161
|
+
gemini: {
|
|
162
|
+
path: ".gemini/skills",
|
|
163
|
+
override: HOSTS.gemini.files[0].override,
|
|
164
|
+
verified: ["0.67.0"],
|
|
165
|
+
},
|
|
166
|
+
} as const satisfies Partial<Record<HostId, HostSkillDefinition>>;
|
|
167
|
+
|
|
168
|
+
export type SkillHostId = keyof typeof SKILL_HOSTS;
|
package/src/index.ts
CHANGED
|
@@ -5,3 +5,6 @@ export { HOSTS, type HostConfig, type HostDefinition, type HostFormat, type Host
|
|
|
5
5
|
export { resolveHostPaths, type HostPaths, type HostRedirect, type HostRefusal, type ResolveHostPathsOptions } from "./paths.ts";
|
|
6
6
|
export { applyEntry, planEntry, readEntryReceipt, undoEntry, UNDO_NOOP_CODES, type ApplyEntryOptions, type EntryPlan, type EntryReceipt, type EntryResult, type EntryTarget, type PlanEntryOptions, type UndoNoopCode } from "./entry.ts";
|
|
7
7
|
export { EntryRefusal, REFUSAL_CODES, type RefusalCode } from "./refusal.ts";
|
|
8
|
+
export { SKILL_HOSTS, type HostSkillDefinition, type SkillHostId } from "./hosts.ts";
|
|
9
|
+
export { resolveSkillRoots, type ResolveSkillRootsOptions, type SkillRoots } from "./paths.ts";
|
|
10
|
+
export { applySkillEntry, classifySkillTarget, planSkillEntry, undoSkillEntry, type PlanSkillEntryOptions, type SkillEntryPlan, type SkillEntryResult, type SkillEntryTarget, type SkillTargetClassification } from "./skills.ts";
|
package/src/paths.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
2
|
-
import { HOSTS, type HostDefinition, type HostId, type HostScope, type HomeOverride } from "./hosts.ts";
|
|
2
|
+
import { HOSTS, SKILL_HOSTS, type HostSkillDefinition, type SkillHostId, type HostDefinition, type HostId, type HostScope, type HomeOverride } from "./hosts.ts";
|
|
3
3
|
import { realPath } from "./platform.ts";
|
|
4
4
|
import type { RefusalCode } from "./refusal.ts";
|
|
5
5
|
|
|
@@ -142,3 +142,56 @@ export function resolveHostPaths(options: ResolveHostPathsOptions): HostPaths {
|
|
|
142
142
|
}
|
|
143
143
|
return { home, paths, legacyPaths, redirects, refusals, roots };
|
|
144
144
|
}
|
|
145
|
+
|
|
146
|
+
export interface ResolveSkillRootsOptions extends Omit<ResolveHostPathsOptions, "hosts"> {
|
|
147
|
+
hosts?: readonly HostId[];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface SkillRoots {
|
|
151
|
+
roots: Partial<Record<SkillHostId, string[]>>;
|
|
152
|
+
redirects: HostRedirect[];
|
|
153
|
+
refusals: HostRefusal[];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Select one verified installation root per host without writing to disk. */
|
|
157
|
+
export function resolveSkillRoots(options: ResolveSkillRootsOptions): SkillRoots {
|
|
158
|
+
const { env, scopes = ["user"], redirectManagedProfiles = true } = options;
|
|
159
|
+
const home = canonical(options.home);
|
|
160
|
+
const result: SkillRoots = { roots: {}, redirects: [], refusals: [] };
|
|
161
|
+
for (const id of new Set(options.hosts ?? (Object.keys(SKILL_HOSTS) as SkillHostId[]))) {
|
|
162
|
+
if (!Object.hasOwn(SKILL_HOSTS, id)) continue;
|
|
163
|
+
const host = id as SkillHostId;
|
|
164
|
+
const definition: HostSkillDefinition = SKILL_HOSTS[host];
|
|
165
|
+
if (!scopes.includes("user")) {
|
|
166
|
+
result.roots[host] = [];
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
const preferred = definition.preferredOverride;
|
|
170
|
+
const override = preferred && env[preferred.key] ? preferred : definition.override;
|
|
171
|
+
if (env[override.key]?.includes(String.fromCharCode(0))) {
|
|
172
|
+
result.refusals.push({
|
|
173
|
+
host, variable: override.key, code: "invalid-skill-override",
|
|
174
|
+
reason: `${override.key} contains a NUL character; supply an absolute directory or unset the override`,
|
|
175
|
+
});
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
const root = configRoot(override, env, home);
|
|
179
|
+
if (typeof root !== "string") {
|
|
180
|
+
result.refusals.push({ host, ...root });
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
const from = join(root, override === preferred ? "skills" : definition.path);
|
|
184
|
+
const personal = join(home, definition.override.directory, definition.path);
|
|
185
|
+
const orcaRoot = env.ORCA_USER_DATA_PATH?.trim() || join(home, "Library", "Application Support", "orca");
|
|
186
|
+
if (redirectManagedProfiles && definition.managedProfile && from !== personal
|
|
187
|
+
&& orcaHome(root, definition.managedProfile, orcaRoot)) {
|
|
188
|
+
result.roots[host] = [personal];
|
|
189
|
+
result.redirects.push({
|
|
190
|
+
target: host, from, to: personal, reason: "The managed profile uses the personal skill root",
|
|
191
|
+
});
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
result.roots[host] = [from];
|
|
195
|
+
}
|
|
196
|
+
return result;
|
|
197
|
+
}
|
package/src/refusal.ts
CHANGED
|
@@ -19,6 +19,12 @@ export const REFUSAL_CODES = [
|
|
|
19
19
|
"managed-entry-changed",
|
|
20
20
|
"pending-operation",
|
|
21
21
|
"io-error",
|
|
22
|
+
"invalid-skill-override",
|
|
23
|
+
"foreign-skill-link",
|
|
24
|
+
"skill-tool-marker",
|
|
25
|
+
"system-reserved-skill",
|
|
26
|
+
"unmanaged-skill-target",
|
|
27
|
+
"profile-root-changed",
|
|
22
28
|
] as const;
|
|
23
29
|
|
|
24
30
|
export type RefusalCode = typeof REFUSAL_CODES[number];
|
package/src/skills.ts
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { lstatSync, readlinkSync, renameSync, symlinkSync, unlinkSync, type Stats } from "node:fs";
|
|
3
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { checkPhysicalDirectory, ensureDirectory, publishImage, readImage, withConfigLock } from "./fs-safe.ts";
|
|
5
|
+
import { SKILL_HOSTS, type SkillHostId } from "./hosts.ts";
|
|
6
|
+
import type { ConfigImage } from "./json.ts";
|
|
7
|
+
import { asEntryRefusal, EntryRefusal, type RefusalCode } from "./refusal.ts";
|
|
8
|
+
|
|
9
|
+
const markers = [".ahub-skill.json", ".vmem-skill.json", ".amem-skill.json", ".arev-skill.json"] as const;
|
|
10
|
+
const receiptLimit = 64 * 1024;
|
|
11
|
+
const absentImage: ConfigImage = { bytes: null, mode: 0o600 };
|
|
12
|
+
const reserved = new Set([".system"]);
|
|
13
|
+
|
|
14
|
+
interface LinkIdentity {
|
|
15
|
+
targetPath: string;
|
|
16
|
+
link: string;
|
|
17
|
+
device: string;
|
|
18
|
+
inode: string;
|
|
19
|
+
birth: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface SkillReceipt {
|
|
23
|
+
version: 1;
|
|
24
|
+
host: SkillHostId;
|
|
25
|
+
name: string;
|
|
26
|
+
installed: LinkIdentity;
|
|
27
|
+
pending?: { temporary: LinkIdentity; previous: LinkIdentity | null };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface SkillEntryTarget {
|
|
31
|
+
host: SkillHostId;
|
|
32
|
+
root: string;
|
|
33
|
+
name: string;
|
|
34
|
+
receiptDir: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface PlanSkillEntryOptions extends SkillEntryTarget {
|
|
38
|
+
sourcePath: string;
|
|
39
|
+
retarget?: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export type SkillTargetClassification =
|
|
43
|
+
| { kind: "absent" | "system-reserved" | "unmanaged-directory" | "unmanaged-file" }
|
|
44
|
+
| { kind: "owned-symlink" | "foreign-symlink"; link: string }
|
|
45
|
+
| { kind: "tool-marker"; marker: typeof markers[number] };
|
|
46
|
+
|
|
47
|
+
type SkillChange = "add" | "replace" | "retarget" | "unchanged";
|
|
48
|
+
type SkillPreview = {
|
|
49
|
+
change: SkillChange;
|
|
50
|
+
targetPath: string;
|
|
51
|
+
options: PlanSkillEntryOptions;
|
|
52
|
+
intent: string;
|
|
53
|
+
};
|
|
54
|
+
export type SkillEntryPlan = SkillPreview
|
|
55
|
+
| { change: "refused"; code: RefusalCode; reason: string; file?: string };
|
|
56
|
+
|
|
57
|
+
export interface SkillEntryResult {
|
|
58
|
+
change: SkillChange | "removed";
|
|
59
|
+
targetPath: string;
|
|
60
|
+
receipt: string;
|
|
61
|
+
code?: "no-receipt" | "entry-already-absent";
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function fail(code: RefusalCode, file: string, reason: string): never {
|
|
65
|
+
throw new EntryRefusal(code, `${file}: ${reason}`, { file });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function stat(path: string): Stats | undefined {
|
|
69
|
+
try {
|
|
70
|
+
return lstatSync(path);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function plainAbsolute(path: unknown): path is string {
|
|
78
|
+
return typeof path === "string" && path.length <= 4096 && !path.includes(String.fromCharCode(0))
|
|
79
|
+
&& isAbsolute(path) && resolve(path) === path;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function sameLink(a: LinkIdentity | undefined | null, b: LinkIdentity | undefined | null): boolean {
|
|
83
|
+
return !!a && !!b && a.targetPath === b.targetPath && a.link === b.link
|
|
84
|
+
&& a.device === b.device && a.inode === b.inode && a.birth === b.birth;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function identify(targetPath: string, named: Stats): LinkIdentity {
|
|
88
|
+
const link = readlinkSync(targetPath);
|
|
89
|
+
const current = stat(targetPath);
|
|
90
|
+
if (!current?.isSymbolicLink() || named.ino !== current.ino || named.dev !== current.dev
|
|
91
|
+
|| named.ctimeMs !== current.ctimeMs) {
|
|
92
|
+
fail("file-changed", targetPath, "link changed during inspection; inspect it and retry");
|
|
93
|
+
}
|
|
94
|
+
return { targetPath, link, device: String(named.dev), inode: String(named.ino), birth: String(named.birthtimeMs) };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function inspect(targetPath: string, owned?: LinkIdentity): {
|
|
98
|
+
classification: SkillTargetClassification; identity?: LinkIdentity;
|
|
99
|
+
} {
|
|
100
|
+
if (!plainAbsolute(targetPath)) fail("unsafe-path", targetPath, "use an absolute physical skill path");
|
|
101
|
+
if (reserved.has(basename(targetPath))) return { classification: { kind: "system-reserved" } };
|
|
102
|
+
checkPhysicalDirectory(dirname(targetPath));
|
|
103
|
+
const named = stat(targetPath);
|
|
104
|
+
if (!named) return { classification: { kind: "absent" } };
|
|
105
|
+
if (named.isSymbolicLink()) {
|
|
106
|
+
const identity = identify(targetPath, named);
|
|
107
|
+
return {
|
|
108
|
+
identity,
|
|
109
|
+
classification: { kind: sameLink(identity, owned) ? "owned-symlink" : "foreign-symlink", link: identity.link },
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
if (!named.isDirectory()) return { classification: { kind: "unmanaged-file" } };
|
|
113
|
+
checkPhysicalDirectory(targetPath);
|
|
114
|
+
for (const marker of markers) {
|
|
115
|
+
if (stat(join(targetPath, marker))) return { classification: { kind: "tool-marker", marker } };
|
|
116
|
+
}
|
|
117
|
+
return { classification: { kind: "unmanaged-directory" } };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Classify ownership only when a validated receipt is supplied by host, name and directory. */
|
|
121
|
+
export function classifySkillTarget(options: {
|
|
122
|
+
targetPath: string; host?: SkillHostId; receiptDir?: string;
|
|
123
|
+
}): SkillTargetClassification {
|
|
124
|
+
const { targetPath, host, receiptDir } = options;
|
|
125
|
+
const owned = host !== undefined && receiptDir !== undefined
|
|
126
|
+
? readSkillReceipt({ host, name: basename(targetPath), root: dirname(targetPath), receiptDir }).receipt?.installed
|
|
127
|
+
: undefined;
|
|
128
|
+
return inspect(targetPath, owned).classification;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function targetFor(options: SkillEntryTarget): { targetPath: string; receiptPath: string } {
|
|
132
|
+
const { host, root, name, receiptDir } = options;
|
|
133
|
+
if (!Object.hasOwn(SKILL_HOSTS, host) || !/^(?:[A-Za-z0-9][A-Za-z0-9._-]{0,127}|\.system)$/.test(name)) {
|
|
134
|
+
fail("invalid-target", root, "supply a verified skill host and a single skill name");
|
|
135
|
+
}
|
|
136
|
+
if (!plainAbsolute(root) || !plainAbsolute(receiptDir)) {
|
|
137
|
+
fail("unsafe-path", root, "use absolute physical skill and receipt directories");
|
|
138
|
+
}
|
|
139
|
+
const key = createHash("sha256").update(JSON.stringify([host, name])).digest("hex");
|
|
140
|
+
return { targetPath: join(root, name), receiptPath: join(receiptDir, `skill-${key}.json`) };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function validLink(value: unknown): value is LinkIdentity {
|
|
144
|
+
if (typeof value !== "object" || value === null) return false;
|
|
145
|
+
const link = value as Partial<LinkIdentity>;
|
|
146
|
+
return plainAbsolute(link.targetPath) && typeof link.link === "string" && link.link.length > 0
|
|
147
|
+
&& link.link.length <= 4096 && !isAbsolute(link.link) && !link.link.includes(String.fromCharCode(0))
|
|
148
|
+
&& /^\d+$/.test(link.device ?? "") && /^\d+$/.test(link.inode ?? "")
|
|
149
|
+
&& /^\d+(\.\d+)?$/.test(link.birth ?? "");
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function readSkillReceipt(options: SkillEntryTarget): {
|
|
153
|
+
path: string; image: ConfigImage; receipt?: SkillReceipt;
|
|
154
|
+
} {
|
|
155
|
+
const { receiptPath: path } = targetFor(options);
|
|
156
|
+
const image = readImage(path, receiptLimit);
|
|
157
|
+
if (image.bytes === null) return { path, image };
|
|
158
|
+
let value: SkillReceipt;
|
|
159
|
+
try {
|
|
160
|
+
value = JSON.parse(Buffer.from(image.bytes, "base64").toString("utf8"));
|
|
161
|
+
} catch {
|
|
162
|
+
fail("invalid-receipt", path, "receipt is malformed; inspect it before retrying");
|
|
163
|
+
}
|
|
164
|
+
if (!value || value.version !== 1 || value.host !== options.host || value.name !== options.name
|
|
165
|
+
|| !validLink(value.installed) || basename(value.installed.targetPath) !== value.name
|
|
166
|
+
|| (value.pending !== undefined && (!value.pending || !validLink(value.pending.temporary)
|
|
167
|
+
|| dirname(value.pending.temporary.targetPath) !== dirname(value.installed.targetPath)
|
|
168
|
+
|| !/^\.agent-hosts-skill-[a-f0-9-]{36}\.tmp$/.test(basename(value.pending.temporary.targetPath))
|
|
169
|
+
|| !sameLink({ ...value.pending.temporary, targetPath: value.installed.targetPath }, value.installed)
|
|
170
|
+
|| (value.pending.previous !== null && (!validLink(value.pending.previous)
|
|
171
|
+
|| basename(value.pending.previous.targetPath) !== value.name))))) {
|
|
172
|
+
fail("invalid-receipt", path, "receipt does not match this skill; inspect it before retrying");
|
|
173
|
+
}
|
|
174
|
+
return { path, image, receipt: value };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function receiptImage(receipt: SkillReceipt): ConfigImage {
|
|
178
|
+
return { bytes: Buffer.from(JSON.stringify(receipt) + "\n").toString("base64"), mode: 0o600 };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function checkAvailable(targetPath: string, owned?: LinkIdentity): boolean {
|
|
182
|
+
const { classification } = inspect(targetPath, owned);
|
|
183
|
+
switch (classification.kind) {
|
|
184
|
+
case "absent": return false;
|
|
185
|
+
case "owned-symlink": return true;
|
|
186
|
+
case "foreign-symlink":
|
|
187
|
+
return fail(owned ? "managed-entry-changed" : "foreign-skill-link", targetPath,
|
|
188
|
+
"link is outside this receipt's ownership; move it aside or restore the recorded link, then retry");
|
|
189
|
+
case "tool-marker":
|
|
190
|
+
return fail("skill-tool-marker", targetPath, `owned by ${classification.marker}; manage it with its owning tool`);
|
|
191
|
+
case "system-reserved":
|
|
192
|
+
return fail("system-reserved-skill", targetPath, "name is reserved for host skills; choose another name");
|
|
193
|
+
default:
|
|
194
|
+
return fail("unmanaged-skill-target", targetPath, "entry already exists; move it aside or choose another name");
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function sourceLink(options: PlanSkillEntryOptions, targetPath: string): string {
|
|
199
|
+
if (!plainAbsolute(options.sourcePath) || !checkPhysicalDirectory(options.sourcePath)) {
|
|
200
|
+
fail("invalid-entry", String(options.sourcePath), "supply an existing physical source directory");
|
|
201
|
+
}
|
|
202
|
+
const outside = (path: string): boolean => path === ".." || path.startsWith(".." + sep);
|
|
203
|
+
if (!outside(relative(targetPath, options.sourcePath)) || !outside(relative(options.sourcePath, targetPath))) {
|
|
204
|
+
fail("invalid-entry", targetPath, "source and destination overlap and may create a recursive skill link; choose a source in a separate directory");
|
|
205
|
+
}
|
|
206
|
+
return relative(dirname(targetPath), options.sourcePath);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function plan(options: PlanSkillEntryOptions): SkillPreview {
|
|
210
|
+
const { targetPath } = targetFor(options);
|
|
211
|
+
const { receipt, image } = readSkillReceipt(options);
|
|
212
|
+
const link = sourceLink(options, targetPath);
|
|
213
|
+
const prior = receipt?.pending ? receipt.pending.previous ?? undefined : receipt?.installed;
|
|
214
|
+
const moved = !!prior && prior.targetPath !== targetPath;
|
|
215
|
+
if (receipt?.pending && (receipt.installed.targetPath !== targetPath || receipt.installed.link !== link)) {
|
|
216
|
+
fail("pending-operation", targetPath,
|
|
217
|
+
`preview and apply the interrupted publication for ${receipt.installed.targetPath} from ${resolve(dirname(receipt.installed.targetPath), receipt.installed.link)} first`);
|
|
218
|
+
}
|
|
219
|
+
if (moved && !options.retarget) {
|
|
220
|
+
fail("profile-root-changed", targetPath, `recorded skill root is ${dirname(prior.targetPath)}; pass retarget: true to move it`);
|
|
221
|
+
}
|
|
222
|
+
if (receipt?.pending) {
|
|
223
|
+
const change = moved ? "retarget" : prior ? "replace" : "add";
|
|
224
|
+
return { change, targetPath, options: { ...options }, intent: pendingIntent(image) };
|
|
225
|
+
}
|
|
226
|
+
const present = checkAvailable(targetPath, moved ? undefined : prior);
|
|
227
|
+
const oldPresent = moved && atRecordedRoot(prior, () => checkAvailable(prior.targetPath, prior));
|
|
228
|
+
const change = moved ? "retarget" : !present ? "add" : prior?.link === link ? "unchanged" : "replace";
|
|
229
|
+
const intent = createHash("sha256").update(JSON.stringify([targetPath, link, image.bytes, image.mode, present, oldPresent])).digest("hex");
|
|
230
|
+
return { change, targetPath, options: { ...options }, intent };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export function planSkillEntry(options: PlanSkillEntryOptions): SkillEntryPlan {
|
|
234
|
+
try {
|
|
235
|
+
return plan(options);
|
|
236
|
+
} catch (error) {
|
|
237
|
+
const refusal = asEntryRefusal(error, "Plan skill entry");
|
|
238
|
+
return { change: "refused", code: refusal.code, reason: refusal.reason, file: refusal.file };
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function removeOwned(link: LinkIdentity): boolean {
|
|
243
|
+
if (!checkAvailable(link.targetPath, link)) return false;
|
|
244
|
+
unlinkSync(link.targetPath);
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function atRecordedRoot<T>(link: LinkIdentity, action: () => T): T {
|
|
249
|
+
try {
|
|
250
|
+
return action();
|
|
251
|
+
} catch (error) {
|
|
252
|
+
if (!(error instanceof EntryRefusal) || error.code !== "unsafe-path") throw error;
|
|
253
|
+
fail("unsafe-path", link.targetPath,
|
|
254
|
+
`recorded skill root is redirected or unsafe; restore ${dirname(link.targetPath)} as a physical directory for undo, or move the receipt aside to stop tracking this link without following it`);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function pendingIntent(image: ConfigImage): string {
|
|
259
|
+
return createHash("sha256").update(JSON.stringify(["pending", image.bytes, image.mode])).digest("hex");
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function rollback(path: string, image: ConfigImage, temporary: LinkIdentity, restoration: ConfigImage): void {
|
|
263
|
+
try {
|
|
264
|
+
const current = inspect(temporary.targetPath).identity;
|
|
265
|
+
if (sameLink(current, temporary)) unlinkSync(temporary.targetPath);
|
|
266
|
+
} finally {
|
|
267
|
+
// A redirected directory may make the staged link unreachable. Never follow it.
|
|
268
|
+
publishImage(path, receiptLimit, image, restoration);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Finish a publication that reached rename, or roll back one that did not. */
|
|
273
|
+
function recover(options: SkillEntryTarget): boolean {
|
|
274
|
+
const { path, image, receipt } = readSkillReceipt(options);
|
|
275
|
+
if (!receipt?.pending) return false;
|
|
276
|
+
const { installed, pending: { previous, temporary } } = receipt;
|
|
277
|
+
const current = atRecordedRoot(installed, () => inspect(installed.targetPath).identity);
|
|
278
|
+
if (sameLink(current, installed)) {
|
|
279
|
+
if (previous && previous.targetPath !== installed.targetPath) {
|
|
280
|
+
atRecordedRoot(previous, () => removeOwned(previous));
|
|
281
|
+
}
|
|
282
|
+
const { pending: _pending, ...committed } = receipt;
|
|
283
|
+
publishImage(path, receiptLimit, image, receiptImage(committed));
|
|
284
|
+
return true;
|
|
285
|
+
}
|
|
286
|
+
const restoration = previous ? receiptImage({ version: 1, host: receipt.host, name: receipt.name, installed: previous }) : absentImage;
|
|
287
|
+
rollback(path, image, temporary, restoration);
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export function applySkillEntry(preview: SkillEntryPlan): SkillEntryResult {
|
|
292
|
+
if (preview.change === "refused") throw new EntryRefusal(preview.code, preview.reason, { file: preview.file });
|
|
293
|
+
const options = preview.options;
|
|
294
|
+
const { targetPath, receiptPath } = targetFor(options);
|
|
295
|
+
try {
|
|
296
|
+
return withConfigLock(receiptPath, () => {
|
|
297
|
+
if (targetPath !== preview.targetPath) {
|
|
298
|
+
fail("changed-since-preview", targetPath, "skill target changed; preview it again before applying");
|
|
299
|
+
}
|
|
300
|
+
const staged = readSkillReceipt(options);
|
|
301
|
+
const freshPendingPreview = staged.receipt?.pending !== undefined && preview.intent === pendingIntent(staged.image);
|
|
302
|
+
const resumed = staged.receipt?.pending ? plan(options) : undefined;
|
|
303
|
+
if (recover(options) && resumed) {
|
|
304
|
+
return { change: resumed.change, targetPath, receipt: receiptPath };
|
|
305
|
+
}
|
|
306
|
+
const current = plan(options);
|
|
307
|
+
if (!freshPendingPreview
|
|
308
|
+
&& (current.intent !== preview.intent || current.change !== preview.change)) {
|
|
309
|
+
fail("changed-since-preview", targetPath, "skill state changed; preview it again before applying");
|
|
310
|
+
}
|
|
311
|
+
const result = { change: current.change, targetPath, receipt: receiptPath };
|
|
312
|
+
if (current.change === "unchanged") return result;
|
|
313
|
+
|
|
314
|
+
const { receipt, image } = readSkillReceipt(options);
|
|
315
|
+
const parentPath = dirname(targetPath);
|
|
316
|
+
ensureDirectory(parentPath);
|
|
317
|
+
const parent = checkPhysicalDirectory(parentPath)!;
|
|
318
|
+
const temporaryPath = join(parentPath, `.agent-hosts-skill-${randomUUID()}.tmp`);
|
|
319
|
+
let created = false;
|
|
320
|
+
let named: Stats | undefined;
|
|
321
|
+
let journal: { image: ConfigImage; link: LinkIdentity } | undefined;
|
|
322
|
+
let renamed = false;
|
|
323
|
+
try {
|
|
324
|
+
symlinkSync(sourceLink(options, targetPath), temporaryPath);
|
|
325
|
+
created = true;
|
|
326
|
+
named = lstatSync(temporaryPath);
|
|
327
|
+
const temporary = identify(temporaryPath, named);
|
|
328
|
+
const pending: SkillReceipt = {
|
|
329
|
+
version: 1, host: options.host, name: options.name, installed: { ...temporary, targetPath },
|
|
330
|
+
pending: { temporary, previous: receipt?.installed ?? null },
|
|
331
|
+
};
|
|
332
|
+
const stagedImage = receiptImage(pending);
|
|
333
|
+
publishImage(receiptPath, receiptLimit, image, stagedImage);
|
|
334
|
+
journal = { image: stagedImage, link: temporary };
|
|
335
|
+
const refreshed = checkPhysicalDirectory(parentPath);
|
|
336
|
+
if (!refreshed || parent.dev !== refreshed.dev || parent.ino !== refreshed.ino
|
|
337
|
+
|| !sameLink(inspect(temporaryPath).identity, temporary)) {
|
|
338
|
+
fail("file-changed", targetPath, "destination directory or staged link changed; inspect it before retrying");
|
|
339
|
+
}
|
|
340
|
+
const previous = receipt?.installed;
|
|
341
|
+
const stillPresent = checkAvailable(targetPath, previous?.targetPath === targetPath ? previous : undefined);
|
|
342
|
+
const expectedPresent = current.change === "replace";
|
|
343
|
+
if (stillPresent !== expectedPresent) {
|
|
344
|
+
fail("changed-since-preview", targetPath, "destination changed after staging; inspect it before retrying");
|
|
345
|
+
}
|
|
346
|
+
// ponytail: rename(2) can replace a foreign file or link created after this check.
|
|
347
|
+
// The receipt lock coordinates cooperating writers only.
|
|
348
|
+
renameSync(temporaryPath, targetPath);
|
|
349
|
+
renamed = true;
|
|
350
|
+
recover(options);
|
|
351
|
+
return result;
|
|
352
|
+
} catch (error) {
|
|
353
|
+
if (journal && !renamed) {
|
|
354
|
+
try {
|
|
355
|
+
rollback(receiptPath, journal.image, journal.link, image);
|
|
356
|
+
} catch (rollbackError) {
|
|
357
|
+
throw new AggregateError([error, rollbackError], "Skill staging failed and cleanup needs inspection");
|
|
358
|
+
}
|
|
359
|
+
} else if (created && !journal) {
|
|
360
|
+
try {
|
|
361
|
+
const currentParent = checkPhysicalDirectory(parentPath);
|
|
362
|
+
const current = stat(temporaryPath);
|
|
363
|
+
if (currentParent?.dev === parent.dev && currentParent.ino === parent.ino
|
|
364
|
+
&& current?.isSymbolicLink() && (!named || (current.dev === named.dev && current.ino === named.ino))) {
|
|
365
|
+
unlinkSync(temporaryPath);
|
|
366
|
+
}
|
|
367
|
+
} catch {
|
|
368
|
+
// Do not replace the publication error with a cleanup error.
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
throw error;
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
} catch (error) {
|
|
375
|
+
throw asEntryRefusal(error, "Apply skill entry", targetPath);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
export function undoSkillEntry(options: SkillEntryTarget): SkillEntryResult {
|
|
380
|
+
const { targetPath, receiptPath } = targetFor(options);
|
|
381
|
+
try {
|
|
382
|
+
if (!readSkillReceipt(options).receipt) return { change: "unchanged", code: "no-receipt", targetPath, receipt: receiptPath };
|
|
383
|
+
return withConfigLock(receiptPath, () => {
|
|
384
|
+
const staged = readSkillReceipt(options).receipt;
|
|
385
|
+
if (staged && staged.installed.targetPath !== targetPath) {
|
|
386
|
+
fail("profile-root-changed", targetPath, `use the recorded root ${dirname(staged.installed.targetPath)} to undo this skill`);
|
|
387
|
+
}
|
|
388
|
+
recover(options);
|
|
389
|
+
const { receipt, image } = readSkillReceipt(options);
|
|
390
|
+
if (!receipt) return { change: "unchanged", code: "no-receipt", targetPath, receipt: receiptPath };
|
|
391
|
+
const installed = receipt.installed;
|
|
392
|
+
if (installed.targetPath !== targetPath) {
|
|
393
|
+
fail("profile-root-changed", targetPath, `use the recorded root ${dirname(installed.targetPath)} to undo this skill`);
|
|
394
|
+
}
|
|
395
|
+
const removed = atRecordedRoot(installed, () => removeOwned(installed));
|
|
396
|
+
publishImage(receiptPath, receiptLimit, image, absentImage);
|
|
397
|
+
return removed
|
|
398
|
+
? { change: "removed", targetPath, receipt: receiptPath }
|
|
399
|
+
: { change: "unchanged", code: "entry-already-absent", targetPath, receipt: receiptPath };
|
|
400
|
+
});
|
|
401
|
+
} catch (error) {
|
|
402
|
+
throw asEntryRefusal(error, "Undo skill entry", targetPath);
|
|
403
|
+
}
|
|
404
|
+
}
|