taskquoin 0.0.0-stage → 2026.12.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/CHANGELOG.md +62 -0
- package/LICENSE +55 -0
- package/README.md +227 -2
- package/SECURITY.md +26 -0
- package/adapters/git/src/git.js +250 -0
- package/adapters/git/src/index.js +1 -0
- package/adapters/hooks-claude/src/canonical.js +45 -0
- package/adapters/hooks-claude/src/index.js +2 -0
- package/adapters/hooks-claude/src/main.js +58 -0
- package/adapters/hooks-claude/src/payload.js +40 -0
- package/adapters/host-probe/src/index.js +2 -0
- package/adapters/host-probe/src/ollama.js +18 -0
- package/adapters/host-probe/src/probe.js +107 -0
- package/adapters/local-tool/src/fingerprint.js +56 -0
- package/adapters/local-tool/src/index.js +4 -0
- package/adapters/local-tool/src/local-tool.js +22 -0
- package/adapters/local-tool/src/sandboxed.js +105 -0
- package/adapters/local-tool/src/scan.js +52 -0
- package/adapters/memory-claude-mem/src/claude-mem.js +115 -0
- package/adapters/memory-claude-mem/src/index.js +1 -0
- package/adapters/process-runner/src/index.js +1 -0
- package/adapters/process-runner/src/runner.js +123 -0
- package/adapters/runtime-api/src/capabilities.json +116 -0
- package/adapters/runtime-api/src/executor.js +131 -0
- package/adapters/runtime-api/src/index.js +1 -0
- package/adapters/runtime-claude/src/capabilities.json +375 -0
- package/adapters/runtime-claude/src/command.js +34 -0
- package/adapters/runtime-claude/src/executor.js +162 -0
- package/adapters/runtime-claude/src/index.js +4 -0
- package/adapters/runtime-claude/src/permissions.js +76 -0
- package/adapters/runtime-claude/src/stream.js +60 -0
- package/adapters/runtime-codex/src/capabilities.json +192 -0
- package/adapters/runtime-codex/src/command.js +36 -0
- package/adapters/runtime-codex/src/executor.js +83 -0
- package/adapters/runtime-codex/src/index.js +4 -0
- package/adapters/runtime-codex/src/scratch.js +32 -0
- package/adapters/runtime-codex/src/stream.js +39 -0
- package/adapters/runtime-opencode/src/capabilities.json +149 -0
- package/adapters/runtime-opencode/src/config.js +33 -0
- package/adapters/runtime-opencode/src/credentials.js +130 -0
- package/adapters/runtime-opencode/src/executor.js +127 -0
- package/adapters/runtime-opencode/src/facts.js +43 -0
- package/adapters/runtime-opencode/src/hosts.js +16 -0
- package/adapters/runtime-opencode/src/hosts.json +3 -0
- package/adapters/runtime-opencode/src/index.js +6 -0
- package/adapters/runtime-opencode/src/mounts.js +58 -0
- package/adapters/runtime-opencode/src/stream.js +63 -0
- package/adapters/skill-store/src/index.js +1 -0
- package/adapters/skill-store/src/skill-store.js +162 -0
- package/adapters/store-fs/src/index.js +2 -0
- package/adapters/store-fs/src/store.js +201 -0
- package/adapters/store-fs/src/trusted-dir.js +37 -0
- package/apps/cli/src/console.js +432 -0
- package/apps/cli/src/dashboard-approve.js +259 -0
- package/apps/cli/src/dashboard-data.js +424 -0
- package/apps/cli/src/dashboard.js +500 -0
- package/apps/cli/src/history.js +35 -0
- package/apps/cli/src/home.js +18 -0
- package/apps/cli/src/i18n/en.js +527 -0
- package/apps/cli/src/i18n/index.js +90 -0
- package/apps/cli/src/i18n/languages.js +25 -0
- package/apps/cli/src/i18n/locales/ar.json +526 -0
- package/apps/cli/src/i18n/locales/de.json +505 -0
- package/apps/cli/src/i18n/locales/es.json +505 -0
- package/apps/cli/src/i18n/locales/fa.json +505 -0
- package/apps/cli/src/i18n/locales/fr.json +505 -0
- package/apps/cli/src/i18n/locales/he.json +505 -0
- package/apps/cli/src/i18n/locales/hi.json +505 -0
- package/apps/cli/src/i18n/locales/id.json +491 -0
- package/apps/cli/src/i18n/locales/it.json +505 -0
- package/apps/cli/src/i18n/locales/ja.json +491 -0
- package/apps/cli/src/i18n/locales/ko.json +491 -0
- package/apps/cli/src/i18n/locales/nl.json +505 -0
- package/apps/cli/src/i18n/locales/pl.json +512 -0
- package/apps/cli/src/i18n/locales/pt-BR.json +505 -0
- package/apps/cli/src/i18n/locales/ru.json +512 -0
- package/apps/cli/src/i18n/locales/th.json +491 -0
- package/apps/cli/src/i18n/locales/tr.json +505 -0
- package/apps/cli/src/i18n/locales/uk.json +512 -0
- package/apps/cli/src/i18n/locales/vi.json +491 -0
- package/apps/cli/src/i18n/locales/zh-CN.json +491 -0
- package/apps/cli/src/i18n/locales/zh-TW.json +491 -0
- package/apps/cli/src/i18n/width.js +40 -0
- package/apps/cli/src/layout.js +18 -0
- package/apps/cli/src/main.js +830 -0
- package/apps/cli/src/preferences.js +46 -0
- package/apps/cli/src/runtime-notices.js +41 -0
- package/apps/cli/src/safe-text.js +3 -0
- package/apps/cli/src/shortcut.js +82 -0
- package/apps/cli/src/skills-cli.js +112 -0
- package/apps/cli/src/tui/caps.js +31 -0
- package/apps/cli/src/tui/components/agent-list.js +58 -0
- package/apps/cli/src/tui/components/approval-center.js +145 -0
- package/apps/cli/src/tui/components/approval.js +95 -0
- package/apps/cli/src/tui/components/dashboard-frame.js +293 -0
- package/apps/cli/src/tui/components/diff-viewer.js +549 -0
- package/apps/cli/src/tui/components/event-viewer.js +46 -0
- package/apps/cli/src/tui/components/help-panel.js +59 -0
- package/apps/cli/src/tui/components/home.js +185 -0
- package/apps/cli/src/tui/components/logo.js +67 -0
- package/apps/cli/src/tui/components/panel.js +70 -0
- package/apps/cli/src/tui/components/status-bar.js +96 -0
- package/apps/cli/src/tui/components/timeline.js +120 -0
- package/apps/cli/src/tui/keys.js +139 -0
- package/apps/cli/src/tui/neutral.js +68 -0
- package/apps/cli/src/tui/screen.js +111 -0
- package/apps/cli/src/tui/text.js +165 -0
- package/apps/cli/src/tui/tokens.js +89 -0
- package/apps/cli/src/tui/view.js +64 -0
- package/apps/cli/src/upgrade-check.js +86 -0
- package/apps/cli/src/upgrade-cli.js +168 -0
- package/apps/cli/src/workflow-cli.js +674 -0
- package/package.json +29 -4
- package/packages/application/src/index.js +8 -0
- package/packages/application/src/lib/digest.js +7 -0
- package/packages/application/src/ports/memory.js +1 -0
- package/packages/application/src/ports/runtime-executor.js +1 -0
- package/packages/application/src/projection/run-view.js +194 -0
- package/packages/application/src/projection/squad-view.js +33 -0
- package/packages/application/src/use-cases/prepare-run.js +68 -0
- package/packages/application/src/workflow/feature-governed.js +420 -0
- package/packages/application/src/workflow/gate-signals.js +40 -0
- package/packages/application/src/workflow/prompts.js +81 -0
- package/packages/config/src/config.js +372 -0
- package/packages/config/src/index.js +1 -0
- package/packages/domain/src/capabilities.js +13 -0
- package/packages/domain/src/capability-matrix.js +63 -0
- package/packages/domain/src/enforcement.js +95 -0
- package/packages/domain/src/index.js +4 -0
- package/packages/domain/src/policy.js +32 -0
- package/packages/rules/src/glob.js +47 -0
- package/packages/rules/src/index.js +5 -0
- package/packages/rules/src/inherit.js +19 -0
- package/packages/rules/src/lists.js +41 -0
- package/packages/rules/src/rules.js +79 -0
- package/packages/rules/src/shell.js +83 -0
- package/packages/skills/src/index.js +1 -0
- package/packages/skills/src/skills.js +108 -0
- package/skills/code-review/SKILL.md +51 -0
- package/skills/egm-design/LICENSE +202 -0
- package/skills/egm-design/SKILL.md +68 -0
- package/skills/egm-design/references/feature-spec-standard.md +39 -0
- package/skills/egm-implementation-readiness/LICENSE +202 -0
- package/skills/egm-implementation-readiness/SKILL.md +67 -0
- package/skills/egm-implementation-readiness/references/implementation-readiness-standard.md +37 -0
- package/skills/first-party.lock.json +10 -0
- package/skills/planning-contract/SKILL.md +51 -0
- package/skills/ponytail/LICENSE +21 -0
- package/skills/ponytail/SKILL.md +56 -0
- package/skills/security-review/SKILL.md +58 -0
- package/skills/tdd/SKILL.md +52 -0
- package/skills/unslop/LICENSE +396 -0
- package/skills/unslop/SKILL.md +239 -0
- package/skills/unslop/references/cjk.md +34 -0
- package/skills/unslop/references/effects.md +113 -0
- package/skills/unslop/references/refs.md +17 -0
- package/skills/unslop/references/rtl.md +111 -0
- package/skills/unslop/references/signs.md +122 -0
- package/skills/unslop/references/tokens.md +139 -0
- package/skills/unslop/references/visuals.md +84 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Taskquoin's own OpenCode connection (spec §5.2): one per user under the control-store base, never the user's personal
|
|
3
|
+
* OpenCode. Each run gets fresh dirs holding ONLY the credential of its model's provider, plus the models catalogue and
|
|
4
|
+
* the plugin manifests fetched at connect time (measured, Task 1). Credential values are never returned or printed.
|
|
5
|
+
*/
|
|
6
|
+
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { dirname, join } from 'node:path';
|
|
8
|
+
import { ensureTrustedDir, stateBase } from '../../store-fs/src/index.js';
|
|
9
|
+
import { authPath, AUTH_TYPE_FIELD, isolationEnv, modelsPath, pluginDir, PLUGIN_MANIFESTS } from "./facts.js";
|
|
10
|
+
const isObj = (x) => typeof x === 'object' && x !== null && !Array.isArray(x);
|
|
11
|
+
function dirsUnder(root) {
|
|
12
|
+
const d = { config: join(root, 'config'), data: join(root, 'data'), cache: join(root, 'cache'), state: join(root, 'state') };
|
|
13
|
+
for (const p of Object.values(d))
|
|
14
|
+
mkdirSync(p, { recursive: true, mode: 0o700 });
|
|
15
|
+
return d;
|
|
16
|
+
}
|
|
17
|
+
/** `<base>/opencode/{config,data,cache,state}`, 0700 (refuses a symlinked or loose directory). */
|
|
18
|
+
export function userOpenCodeDirs(base = stateBase()) {
|
|
19
|
+
return dirsUnder(ensureTrustedDir(join(base, 'opencode')));
|
|
20
|
+
}
|
|
21
|
+
/** The same paths, without creating anything (doctor / gate only read them). */
|
|
22
|
+
export function userOpenCodePaths(base = stateBase()) {
|
|
23
|
+
const r = join(base, 'opencode');
|
|
24
|
+
return { config: join(r, 'config'), data: join(r, 'data'), cache: join(r, 'cache'), state: join(r, 'state') };
|
|
25
|
+
}
|
|
26
|
+
function readAuth(d) {
|
|
27
|
+
try {
|
|
28
|
+
const x = JSON.parse(readFileSync(authPath(d), 'utf8'));
|
|
29
|
+
return isObj(x) ? x : undefined;
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function writeAuth(d, entries) {
|
|
36
|
+
const p = authPath(d);
|
|
37
|
+
mkdirSync(dirname(p), { recursive: true, mode: 0o700 });
|
|
38
|
+
const tmp = `${p}.${process.pid}.tmp`;
|
|
39
|
+
writeFileSync(tmp, JSON.stringify(entries), { mode: 0o600 });
|
|
40
|
+
renameSync(tmp, p);
|
|
41
|
+
}
|
|
42
|
+
/** Connected providers and their non-secret kind (e.g. `oauth` = ChatGPT sign-in, `api` = key). */
|
|
43
|
+
export function connectedProviders(d) {
|
|
44
|
+
const a = readAuth(d);
|
|
45
|
+
if (!a)
|
|
46
|
+
return [];
|
|
47
|
+
return Object.entries(a).filter(([, v]) => isObj(v)).map(([id, v]) => ({ id, type: typeof v[AUTH_TYPE_FIELD] === 'string' ? String(v[AUTH_TYPE_FIELD]) : 'unknown' }));
|
|
48
|
+
}
|
|
49
|
+
/** Fresh per-run dirs under `runBase` with only `providerId`'s credential (0600), the catalogue and the plugin manifests. */
|
|
50
|
+
export function prepareRunDirs(user, runBase, providerId) {
|
|
51
|
+
const entry = readAuth(user)?.[providerId];
|
|
52
|
+
if (!isObj(entry))
|
|
53
|
+
throw new Error(`fournisseur "${providerId}" non connecté pour Taskquoin — lancez : taskquoin connect opencode`);
|
|
54
|
+
const root = mkdtempSync(join(ensureTrustedDir(runBase), 'oc-'));
|
|
55
|
+
const dirs = dirsUnder(root);
|
|
56
|
+
writeAuth(dirs, { [providerId]: entry });
|
|
57
|
+
if (existsSync(modelsPath(user))) {
|
|
58
|
+
mkdirSync(dirname(modelsPath(dirs)), { recursive: true, mode: 0o700 });
|
|
59
|
+
copyFileSync(modelsPath(user), modelsPath(dirs));
|
|
60
|
+
}
|
|
61
|
+
mkdirSync(pluginDir(dirs), { recursive: true, mode: 0o700 });
|
|
62
|
+
for (const f of PLUGIN_MANIFESTS)
|
|
63
|
+
if (existsSync(join(pluginDir(user), f)))
|
|
64
|
+
copyFileSync(join(pluginDir(user), f), join(pluginDir(dirs), f));
|
|
65
|
+
return { root, dirs, initial: JSON.stringify(entry) };
|
|
66
|
+
}
|
|
67
|
+
const expiresOf = (x) => (isObj(x) && typeof x.expires === 'number' ? x.expires : -Infinity);
|
|
68
|
+
/**
|
|
69
|
+
* Copies `providerId`'s entry back to the user connection when THIS run refreshed it (it differs from `initial`, the
|
|
70
|
+
* entry the run started with); never touches another provider. A run that changed nothing never rolls back a newer
|
|
71
|
+
* credential; when two overlapping runs both refreshed, the later expiry wins (final review, Codex MEDIUM 3).
|
|
72
|
+
*/
|
|
73
|
+
export function mergeBackCredential(user, run, providerId, initial, lockWaitMs = 2000) {
|
|
74
|
+
const fromRun = readAuth(run)?.[providerId];
|
|
75
|
+
if (!isObj(fromRun))
|
|
76
|
+
return `credential of the run unreadable — the user connection is unchanged`;
|
|
77
|
+
if (initial !== undefined && JSON.stringify(fromRun) === initial)
|
|
78
|
+
return undefined;
|
|
79
|
+
// Compare-and-swap under a lock file (final review, Claude I1): overlapping runs never interleave their writes.
|
|
80
|
+
const lock = `${authPath(user)}.lock`;
|
|
81
|
+
const until = Date.now() + lockWaitMs;
|
|
82
|
+
for (;;) {
|
|
83
|
+
try {
|
|
84
|
+
writeFileSync(lock, String(process.pid), { flag: 'wx', mode: 0o600 });
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
catch { /* held */ }
|
|
88
|
+
try {
|
|
89
|
+
if (Date.now() - statSync(lock).mtimeMs > 30_000) {
|
|
90
|
+
rmSync(lock, { force: true });
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
continue;
|
|
96
|
+
} // stale
|
|
97
|
+
if (Date.now() >= until)
|
|
98
|
+
return 'connection busy (another run is saving its credential) — the user connection is unchanged';
|
|
99
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
|
|
100
|
+
}
|
|
101
|
+
try {
|
|
102
|
+
return swap(user, providerId, fromRun, initial);
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
rmSync(lock, { force: true });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function swap(user, providerId, fromRun, initial) {
|
|
109
|
+
if (!existsSync(authPath(user)))
|
|
110
|
+
return 'the connection was removed meanwhile (taskquoin connect opencode --remove) — not re-created';
|
|
111
|
+
const current = readAuth(user);
|
|
112
|
+
if (!current)
|
|
113
|
+
return 'user connection unreadable — left unchanged';
|
|
114
|
+
if (JSON.stringify(current[providerId]) === JSON.stringify(fromRun))
|
|
115
|
+
return undefined;
|
|
116
|
+
if (initial !== undefined && JSON.stringify(current[providerId]) !== initial && expiresOf(current[providerId]) >= expiresOf(fromRun))
|
|
117
|
+
return `a newer credential was saved meanwhile by another run — kept it`;
|
|
118
|
+
try {
|
|
119
|
+
writeAuth(user, { ...current, [providerId]: fromRun });
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
catch (e) {
|
|
123
|
+
return `could not save the refreshed credential (${e.message}) — the user connection is unchanged`;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/** For `taskquoin connect opencode`: the run isolation, except that the sign-in may fetch the catalogue and plugin SDK. */
|
|
127
|
+
export function connectEnv(d) {
|
|
128
|
+
const { OPENCODE_DISABLE_MODELS_FETCH: _f, OPENCODE_MODELS_PATH: _m, ...rest } = isolationEnv(d);
|
|
129
|
+
return rest;
|
|
130
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode in Taskquoin's file sandbox, without commands (project B step 1, spec §5.3): version and ticket checked,
|
|
3
|
+
* only fs.read / fs.write, the generated config (no `ask`), HOME hidden, the repository's secrets, instruction files and
|
|
4
|
+
* OpenCode config masked, `.git` and frozen paths read-only, a per-run OpenCode directory holding only the model
|
|
5
|
+
* provider's credential, the host network kept (OpenCode must reach its provider; it has no tool that uses the network).
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, lstatSync, mkdirSync, realpathSync, rmSync, statSync } from 'node:fs';
|
|
8
|
+
import { dirname, isAbsolute, join } from 'node:path';
|
|
9
|
+
import { normalizeGrants } from '../../../packages/domain/src/index.js';
|
|
10
|
+
import { HOME_SECRET_GLOBS } from '../../../packages/rules/src/index.js';
|
|
11
|
+
import { assertTicket, invocationDigest } from '../../../packages/application/src/index.js';
|
|
12
|
+
import { verifyBinaryVersion } from '../../process-runner/src/index.js';
|
|
13
|
+
import { defaultMaskDirs, runSandboxedTool, sandboxedToolAvailable, scanWorkspace } from '../../local-tool/src/index.js';
|
|
14
|
+
import { opencodeConfig } from "./config.js";
|
|
15
|
+
import { mergeBackCredential, prepareRunDirs } from "./credentials.js";
|
|
16
|
+
import { binaryMounts } from "./mounts.js";
|
|
17
|
+
import { parseOpenCodeStream } from "./stream.js";
|
|
18
|
+
import { CONFIG_ENV, isolationEnv, pluginDir, runArgs } from "./facts.js";
|
|
19
|
+
export { binaryMounts } from "./mounts.js";
|
|
20
|
+
const OPENCODE_CAPS = new Set(['fs.read', 'fs.write']);
|
|
21
|
+
const ROOT_HIDDEN = ['AGENTS.md', 'CLAUDE.md', 'opencode.json', 'opencode.jsonc'];
|
|
22
|
+
export class OpenCodeExecutor {
|
|
23
|
+
runtime = 'opencode';
|
|
24
|
+
version;
|
|
25
|
+
binary;
|
|
26
|
+
o;
|
|
27
|
+
constructor(binary, o) { this.binary = binary; this.o = o; }
|
|
28
|
+
async run(req, signal) {
|
|
29
|
+
this.version ??= verifyBinaryVersion(this.binary.bin, this.binary.prefixArgs, req.env);
|
|
30
|
+
const verified = await this.version;
|
|
31
|
+
if (verified !== this.binary.version)
|
|
32
|
+
throw new Error(`opencode binary is ${verified}, declared ${this.binary.version}`);
|
|
33
|
+
assertTicket(req.ticket, 'opencode', verified, req.agent.capabilities, req.agent.id);
|
|
34
|
+
const grants = normalizeGrants(req.agent.capabilities);
|
|
35
|
+
const extra = Object.keys(grants).filter(k => !OPENCODE_CAPS.has(k));
|
|
36
|
+
if (extra.length)
|
|
37
|
+
throw new Error(`refusing: OpenCode agents only read and write files in this version (granted: ${extra.join(', ')})`);
|
|
38
|
+
const model = req.agent.model;
|
|
39
|
+
if (!model || model.indexOf('/') < 1)
|
|
40
|
+
throw new Error('refusing: an OpenCode agent needs a model <provider>/<model>');
|
|
41
|
+
if (!(await (this.o.sandboxAvailable ?? sandboxedToolAvailable)()))
|
|
42
|
+
throw new Error("refusing: bubblewrap unavailable — OpenCode agents never run outside Taskquoin's sandbox");
|
|
43
|
+
const home = req.env.HOME;
|
|
44
|
+
if (!home || !isAbsolute(home) || !existsSync(home))
|
|
45
|
+
throw new Error('refusing: HOME must be an existing absolute path (it is hidden from OpenCode)');
|
|
46
|
+
const scan = scanWorkspace(req.cwd);
|
|
47
|
+
if (!scan.complete)
|
|
48
|
+
throw new Error(`refusing: workspace scan incomplete (${scan.problem}) — cannot mask every secret`);
|
|
49
|
+
// What a secret-NAMED link points to (`.env.local -> credentials.txt`) and what a link leaving the repository points
|
|
50
|
+
// to are masked as well (final review, Codex HIGH 1 — same rule as the Claude executor, Codex CR2 #3 / R4 N10).
|
|
51
|
+
const linkFiles = [];
|
|
52
|
+
const linkDirs = [];
|
|
53
|
+
// HOME secrets that are links (WSL: ~/.aws → /mnt/c/…): hiding HOME hides the link, not its target (Claude I2).
|
|
54
|
+
const homeSecretLinks = HOME_SECRET_GLOBS.map(g => join(home, g.replace(/\/\*\*$/, ''))).filter(p => { try {
|
|
55
|
+
return lstatSync(p).isSymbolicLink();
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return false;
|
|
59
|
+
} });
|
|
60
|
+
for (const l of [...scan.secretLinks, ...scan.externalLinks, ...homeSecretLinks]) {
|
|
61
|
+
let t;
|
|
62
|
+
try {
|
|
63
|
+
t = realpathSync(l);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
continue;
|
|
67
|
+
} // dangling: nothing to read
|
|
68
|
+
(statSync(t).isDirectory() ? linkDirs : linkFiles).push(t);
|
|
69
|
+
}
|
|
70
|
+
const provider = model.slice(0, model.indexOf('/'));
|
|
71
|
+
const write = !!grants['fs.write'];
|
|
72
|
+
const stateRoot = realpathSync(dirname(dirname(this.o.userDirs.config)));
|
|
73
|
+
const run = prepareRunDirs(this.o.userDirs, this.o.runBase, provider);
|
|
74
|
+
const cleanupErrors = [];
|
|
75
|
+
let result;
|
|
76
|
+
try {
|
|
77
|
+
const env = { ...req.env, ...isolationEnv(run.dirs), [CONFIG_ENV]: JSON.stringify(opencodeConfig({ write, ...(req.agent.maxTurns ? { maxTurns: req.agent.maxTurns } : {}) })) };
|
|
78
|
+
const userModules = join(pluginDir(this.o.userDirs), 'node_modules');
|
|
79
|
+
const runModules = join(pluginDir(run.dirs), 'node_modules');
|
|
80
|
+
if (existsSync(userModules))
|
|
81
|
+
mkdirSync(runModules, { recursive: true });
|
|
82
|
+
const profile = {
|
|
83
|
+
writableRoot: req.cwd, home, hideHome: true, shareNetwork: true, extraWritable: [run.root],
|
|
84
|
+
// The control-store base (every provider's credential, other repositories' stores) when it is not under HOME (Claude I3).
|
|
85
|
+
hideDirs: [stateRoot].filter(d => existsSync(d) && !(d === home || d.startsWith(home + '/'))),
|
|
86
|
+
readOnly: [...(write ? [] : [req.cwd]), join(req.cwd, '.git'), ...(req.frozenPaths ?? []), ...binaryMounts(this.binary.bin, req.env.PATH ?? '', home),
|
|
87
|
+
...(this.binary.prefixArgs ?? []).filter(isAbsolute).map(p => dirname(p))],
|
|
88
|
+
readOnlyAt: existsSync(userModules) ? [{ src: userModules, dst: runModules }] : [],
|
|
89
|
+
hideFiles: [...scan.secretFiles, ...scan.instructionFiles, ...ROOT_HIDDEN.map(f => join(req.cwd, f)), ...linkFiles],
|
|
90
|
+
maskDirs: [...defaultMaskDirs(), this.o.controlStore, join(req.cwd, '.opencode'), ...linkDirs],
|
|
91
|
+
};
|
|
92
|
+
const args = [...(this.binary.prefixArgs ?? []), ...runArgs(model)];
|
|
93
|
+
const p = await runSandboxedTool({ bin: this.binary.bin, args, cwd: req.cwd, env, timeoutMs: req.timeoutMs, maxOutputBytes: req.maxOutputBytes,
|
|
94
|
+
stdin: `${req.agent.prompt}\n\n${req.task}` }, profile, signal);
|
|
95
|
+
const s = parseOpenCodeStream(p.stdout.split('\n'));
|
|
96
|
+
const otherModel = s.model && s.model !== model ? s.model : undefined;
|
|
97
|
+
// Every outcome carries a readable message naming the provider (Review Focus 5, final review I4); a stream that
|
|
98
|
+
// ends without a final step is a failure, never a silent `unknown`.
|
|
99
|
+
const status = p.status === 'timeout' || p.status === 'cancelled' ? p.status
|
|
100
|
+
: otherModel || s.error || p.status === 'failed' || !s.completed ? 'failed' : 'completed';
|
|
101
|
+
const tail = p.stderr.trim() ? ` — ${p.stderr.trim().slice(-300)}` : '';
|
|
102
|
+
const terminalMessage = otherModel ? `OpenCode answered with ${otherModel}, not the configured ${model} — refused`
|
|
103
|
+
: s.error ? `OpenCode (${provider}): ${s.error}`
|
|
104
|
+
: p.status === 'timeout' || p.status === 'cancelled' ? `OpenCode (${provider}): ${p.status}`
|
|
105
|
+
: p.status === 'failed' ? `OpenCode (${provider}) exited with code ${p.exitCode}${tail}`
|
|
106
|
+
: !s.completed ? `OpenCode (${provider}): the stream ended without a final step (exit ${p.exitCode}${p.truncated ? ', output truncated at maxOutputBytes' : ''})${tail}`
|
|
107
|
+
: s.text ?? `OpenCode completed without a final message (tools: ${s.toolCalls.map(t => t.name).join(', ') || 'none'})`;
|
|
108
|
+
result = {
|
|
109
|
+
status, runtime: 'opencode', runtimeVersion: this.binary.version, exitCode: p.exitCode, ...(terminalMessage !== undefined ? { terminalMessage } : {}),
|
|
110
|
+
...(s.usage ? { usage: s.usage } : {}), command: { bin: this.binary.bin, args, cwd: req.cwd }, effectiveConfigDigest: invocationDigest(this.binary.bin, args, env),
|
|
111
|
+
toolCalls: s.toolCalls, permissionDenials: s.denials, unsupported: [], stdoutTruncated: p.truncated, stderr: p.stderr, durationMs: p.durationMs,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
const m = mergeBackCredential(this.o.userDirs, run.dirs, provider, run.initial);
|
|
116
|
+
if (m)
|
|
117
|
+
cleanupErrors.push(m);
|
|
118
|
+
try {
|
|
119
|
+
rmSync(run.root, { recursive: true, force: true });
|
|
120
|
+
}
|
|
121
|
+
catch (e) {
|
|
122
|
+
cleanupErrors.push(`run dir cleanup failed: ${e.message}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return cleanupErrors.length ? { ...result, cleanupErrors } : result;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode facts MEASURED on the reference machine (plan Task 1, 2026-11-16) for opencode-ai 1.19.5 — every value
|
|
3
|
+
* comes from docs/reports/opencode-interface-1.19.5.md (recorded runs: test/fixtures/*.ndjson). A new OpenCode version
|
|
4
|
+
* is re-measured before any value here changes.
|
|
5
|
+
*/
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
export const OPENCODE_VERSION = '1.19.5';
|
|
8
|
+
/** Non-interactive run with raw JSON events (NDJSON on stdout); the prompt is read from stdin (measured: ok-stdin). */
|
|
9
|
+
export function runArgs(model) { return ['run', '--format', 'json', '--model', model]; }
|
|
10
|
+
export const PROMPT_VIA_STDIN = true;
|
|
11
|
+
/** The generated config travels in this variable (no file to write; the repository's and the user's configs are ignored). */
|
|
12
|
+
export const CONFIG_ENV = 'OPENCODE_CONFIG_CONTENT';
|
|
13
|
+
/**
|
|
14
|
+
* Isolation: OpenCode's dirs, no project config, no ~/.claude reading, no update/catalogue/LSP download, no external
|
|
15
|
+
* plugin; the models catalogue is a local copy (without it OpenCode knows no provider). NOT set on purpose:
|
|
16
|
+
* OPENCODE_DISABLE_DEFAULT_PLUGINS — it removes the ChatGPT sign-in plugin shipped with OpenCode (measured: "Provider not found").
|
|
17
|
+
*/
|
|
18
|
+
export function isolationEnv(d) {
|
|
19
|
+
return {
|
|
20
|
+
XDG_CONFIG_HOME: d.config, XDG_DATA_HOME: d.data, XDG_CACHE_HOME: d.cache, XDG_STATE_HOME: d.state,
|
|
21
|
+
OPENCODE_DISABLE_AUTOUPDATE: '1', OPENCODE_DISABLE_PROJECT_CONFIG: '1', OPENCODE_DISABLE_CLAUDE_CODE: '1',
|
|
22
|
+
OPENCODE_DISABLE_MODELS_FETCH: '1', OPENCODE_DISABLE_LSP_DOWNLOAD: '1', OPENCODE_PURE: '1',
|
|
23
|
+
OPENCODE_MODELS_PATH: modelsPath(d),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/** Where OpenCode keeps credentials: a JSON object keyed by provider id, mode 0600. */
|
|
27
|
+
export function authPath(d) { return join(d.data, 'opencode', 'auth.json'); }
|
|
28
|
+
/** Non-secret field of a credential entry that says its kind: "oauth" (ChatGPT sign-in) or "api" (key). */
|
|
29
|
+
export const AUTH_TYPE_FIELD = 'type';
|
|
30
|
+
/** Local models catalogue (fetched at connect time, never at run time). */
|
|
31
|
+
export function modelsPath(d) { return join(d.cache, 'opencode', 'models.json'); }
|
|
32
|
+
/** Plugin SDK OpenCode installs in its config dir (npm) — installed at connect time, bound read-only into runs. */
|
|
33
|
+
export function pluginDir(d) { return join(d.config, 'opencode'); }
|
|
34
|
+
export const PLUGIN_MANIFESTS = ['package.json', 'package-lock.json', '.gitignore'];
|
|
35
|
+
/** Interactive login (`providers` alias `auth`); the ChatGPT method label is OpenCode's own (headless = device code). */
|
|
36
|
+
export const LOGIN_ARGS = ['providers', 'login'];
|
|
37
|
+
export const CHATGPT_LOGIN = ['-p', 'openai', '-m', 'ChatGPT Pro/Plus (headless)'];
|
|
38
|
+
/** Rules shape in 1.19.5: `permission: { "<tool>": action | { "<pattern>": action } }`, appended AFTER the built-in agent rules (last match wins). */
|
|
39
|
+
export const PERMISSION_SCHEMA = 'v1-permission-object';
|
|
40
|
+
/** `run` uses the built-in `build` agent; `agent.build.steps` is reflected by `debug agent build` (runtime honouring: Task 8). */
|
|
41
|
+
export function stepLimit(n) { return { agent: { build: { steps: n } } }; }
|
|
42
|
+
/** A tool call refused by a rule ends as tool_use with state.status "error" and this text. */
|
|
43
|
+
export const DENIAL_TEXT = 'The user has specified a rule which prevents you from using this specific tool call';
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Hosts OpenCode reaches during a run, measured per provider and sign-in type (hosts.json, Task 1 / Task 8). */
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
const TABLE = JSON.parse(readFileSync(new URL('./hosts.json', import.meta.url), 'utf8'));
|
|
4
|
+
/** Exact entry for `<provider>:<type>`; without a type, the union of every measured type of that provider. */
|
|
5
|
+
export function measuredHosts(providerId, type) {
|
|
6
|
+
if (type)
|
|
7
|
+
return TABLE[`${providerId}:${type}`];
|
|
8
|
+
const all = Object.entries(TABLE).filter(([k]) => k.startsWith(`${providerId}:`)).map(([, v]) => v);
|
|
9
|
+
if (!all.length)
|
|
10
|
+
return undefined;
|
|
11
|
+
return { code: [...new Set(all.flatMap(h => h.code))], noCode: [...new Set(all.flatMap(h => h.noCode))] };
|
|
12
|
+
}
|
|
13
|
+
/** `<provider>:<type>` connections whose hosts were measured — the only ones certified (final review C1). */
|
|
14
|
+
export const MEASURED_CONNECTIONS = Object.keys(TABLE);
|
|
15
|
+
/** Providers whose models run on this machine. */
|
|
16
|
+
export const LOCAL_PROVIDERS = ['ollama', 'lmstudio'];
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the sandbox must show of the OpenCode binary while HOME is hidden (Review Focus 3): its real file up to its
|
|
3
|
+
* package root (npm layout: …/node_modules/opencode-ai/bin/opencode.exe → …/opencode-ai), and the interpreter of a
|
|
4
|
+
* shebang script. Never HOME itself or one of its ancestors (a stray ~/package.json must not expose HOME).
|
|
5
|
+
*/
|
|
6
|
+
import { closeSync, existsSync, openSync, readSync, realpathSync, statSync } from 'node:fs';
|
|
7
|
+
import { delimiter, dirname, isAbsolute, join } from 'node:path';
|
|
8
|
+
function lookPath(name, PATH) {
|
|
9
|
+
for (const d of PATH.split(delimiter)) {
|
|
10
|
+
if (!d.startsWith('/'))
|
|
11
|
+
continue;
|
|
12
|
+
const p = join(d, name);
|
|
13
|
+
try {
|
|
14
|
+
if (statSync(p).isFile())
|
|
15
|
+
return realpathSync(p);
|
|
16
|
+
}
|
|
17
|
+
catch { /* next */ }
|
|
18
|
+
}
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
function packageRoot(file, home) {
|
|
22
|
+
const own = dirname(file);
|
|
23
|
+
let d = own;
|
|
24
|
+
for (;;) {
|
|
25
|
+
if (d === home || home.startsWith(d + '/') || d === '/')
|
|
26
|
+
return own;
|
|
27
|
+
if (existsSync(join(d, 'package.json')))
|
|
28
|
+
return d;
|
|
29
|
+
d = dirname(d);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function binaryMounts(bin, PATH, home) {
|
|
33
|
+
const real = realpathSync(bin);
|
|
34
|
+
const out = [packageRoot(real, realpathSync(home))];
|
|
35
|
+
let head = '';
|
|
36
|
+
try {
|
|
37
|
+
const fd = openSync(real, 'r');
|
|
38
|
+
try {
|
|
39
|
+
const b = Buffer.alloc(256);
|
|
40
|
+
head = b.subarray(0, readSync(fd, b, 0, 256, 0)).toString('latin1');
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
closeSync(fd);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
catch { /* unreadable: no interpreter */ }
|
|
47
|
+
if (head.startsWith('#!')) {
|
|
48
|
+
const [interp, arg] = head.slice(2).split('\n')[0].trim().split(/\s+/);
|
|
49
|
+
const target = interp?.endsWith('/env') && arg ? lookPath(arg, PATH) : interp;
|
|
50
|
+
if (target && isAbsolute(target)) {
|
|
51
|
+
try {
|
|
52
|
+
out.push(dirname(realpathSync(target)));
|
|
53
|
+
}
|
|
54
|
+
catch { /* missing interpreter: the run fails visibly */ }
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return [...new Set(out)];
|
|
58
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { DENIAL_TEXT } from "./facts.js";
|
|
2
|
+
const isObj = (x) => typeof x === 'object' && x !== null && !Array.isArray(x);
|
|
3
|
+
const num = (x) => (typeof x === 'number' && Number.isFinite(x) && x >= 0 ? x : 0);
|
|
4
|
+
const MAX_TOOL_OUTPUT = 4000;
|
|
5
|
+
export function parseOpenCodeStream(lines) {
|
|
6
|
+
const s = { toolCalls: [], denials: [], completed: false };
|
|
7
|
+
const texts = [];
|
|
8
|
+
let input = 0, output = 0, cost = 0, steps = 0;
|
|
9
|
+
for (const line of lines) {
|
|
10
|
+
let e;
|
|
11
|
+
try {
|
|
12
|
+
e = JSON.parse(line);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
if (!isObj(e))
|
|
18
|
+
continue;
|
|
19
|
+
const part = isObj(e.part) ? e.part : {};
|
|
20
|
+
if (typeof part.modelID === 'string')
|
|
21
|
+
s.model = `${typeof part.providerID === 'string' ? `${part.providerID}/` : ''}${part.modelID}`;
|
|
22
|
+
switch (e.type) {
|
|
23
|
+
case 'step_start':
|
|
24
|
+
s.completed = false;
|
|
25
|
+
break;
|
|
26
|
+
case 'tool_use': {
|
|
27
|
+
const st = isObj(part.state) ? part.state : {};
|
|
28
|
+
const err = typeof st.error === 'string' ? st.error : undefined;
|
|
29
|
+
s.toolCalls.push({ id: String(part.callID ?? part.id ?? ''), name: String(part.tool ?? ''), input: st.input, isError: st.status === 'error',
|
|
30
|
+
output: (err ?? (typeof st.output === 'string' ? st.output : '')).slice(0, MAX_TOOL_OUTPUT) });
|
|
31
|
+
if (st.status === 'error' && err?.startsWith(DENIAL_TEXT))
|
|
32
|
+
s.denials.push({ tool: String(part.tool ?? ''), input: st.input });
|
|
33
|
+
s.completed = false;
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
case 'text':
|
|
37
|
+
if (typeof part.text === 'string' && part.text.trim())
|
|
38
|
+
texts.push(part.text);
|
|
39
|
+
break;
|
|
40
|
+
case 'step_finish': {
|
|
41
|
+
const t = isObj(part.tokens) ? part.tokens : {};
|
|
42
|
+
steps++;
|
|
43
|
+
input += num(t.input);
|
|
44
|
+
output += num(t.output);
|
|
45
|
+
cost += num(part.cost);
|
|
46
|
+
s.completed = part.reason === 'stop';
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
case 'error': {
|
|
50
|
+
const er = isObj(e.error) ? e.error : {};
|
|
51
|
+
const d = isObj(er.data) ? er.data : {};
|
|
52
|
+
s.error = `${String(er.name ?? 'error')}${typeof d.statusCode === 'number' ? ` ${d.statusCode}` : ''}: ${String(d.message ?? er.message ?? 'unknown error').slice(0, 500)}`;
|
|
53
|
+
s.completed = false;
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (texts.length)
|
|
59
|
+
s.text = texts[texts.length - 1];
|
|
60
|
+
if (steps)
|
|
61
|
+
s.usage = { inputTokens: input, outputTokens: output, numTurns: steps, ...(cost ? { costUsd: cost } : {}) };
|
|
62
|
+
return s;
|
|
63
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./skill-store.js";
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skill supply chain (architecture §11), local-only (ADR-0010): Taskquoin never downloads; the owner
|
|
3
|
+
* fetches a repository at a pinned commit and imports a LOCAL directory. Flow: import → quarantine (control store,
|
|
4
|
+
* outside the repo, never executable) → audit report → human approval → approved copy + skills.lock entry → every
|
|
5
|
+
* load re-hashes the approved copy. Trust states are separate: status (quarantined/approved/revoked/invalid), findings,
|
|
6
|
+
* approver. First-party skills ship with Taskquoin and are pinned by skills/first-party.lock.json.
|
|
7
|
+
*/
|
|
8
|
+
import { chmodSync, cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { join, relative } from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { auditSkill, treeHash, validateSkill } from '../../../packages/skills/src/index.js';
|
|
12
|
+
import { ensureTrustedDir } from '../../store-fs/src/index.js';
|
|
13
|
+
const MAX_FILE = 1024 * 1024;
|
|
14
|
+
const MAX_TOTAL = 5 * 1024 * 1024;
|
|
15
|
+
const MAX_FILES = 500;
|
|
16
|
+
const NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
17
|
+
/** Read a local skill directory safely: no symlinks, no special files, bounded size. */
|
|
18
|
+
export function readSkillDir(dir) {
|
|
19
|
+
const out = [];
|
|
20
|
+
let total = 0;
|
|
21
|
+
const walk = (d) => {
|
|
22
|
+
for (const e of readdirSync(d, { withFileTypes: true })) {
|
|
23
|
+
const p = join(d, e.name);
|
|
24
|
+
const st = lstatSync(p);
|
|
25
|
+
const rel = relative(dir, p).split('\\').join('/');
|
|
26
|
+
if (st.isSymbolicLink())
|
|
27
|
+
throw new Error(`refusing ${rel}: symlink`);
|
|
28
|
+
if (st.isDirectory()) {
|
|
29
|
+
walk(p);
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
if (!st.isFile())
|
|
33
|
+
throw new Error(`refusing ${rel}: not a regular file`);
|
|
34
|
+
if (st.size > MAX_FILE)
|
|
35
|
+
throw new Error(`refusing ${rel}: file too large (> ${MAX_FILE} bytes)`);
|
|
36
|
+
total += st.size;
|
|
37
|
+
if (total > MAX_TOTAL)
|
|
38
|
+
throw new Error(`refusing skill: too large (> ${MAX_TOTAL} bytes)`);
|
|
39
|
+
if (out.length >= MAX_FILES)
|
|
40
|
+
throw new Error(`refusing skill: too many files (> ${MAX_FILES})`);
|
|
41
|
+
out.push({ path: rel, bytes: readFileSync(p), exec: (st.mode & 0o111) !== 0 });
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
walk(dir);
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
const dirs = (s) => {
|
|
48
|
+
const base = ensureTrustedDir(join(s.root, 'skills'));
|
|
49
|
+
return { base, quarantine: ensureTrustedDir(join(base, 'quarantine')), approved: ensureTrustedDir(join(base, 'approved')), lock: join(base, 'skills.lock.json') };
|
|
50
|
+
};
|
|
51
|
+
const readLock = (s) => { const f = dirs(s).lock; return existsSync(f) ? JSON.parse(readFileSync(f, 'utf8')) : []; };
|
|
52
|
+
const writeLock = (s, l) => writeFileSync(dirs(s).lock, JSON.stringify(l, null, 2), { mode: 0o600 });
|
|
53
|
+
const short = (h) => h.slice('sha256:'.length, 'sha256:'.length + 12);
|
|
54
|
+
function writeCopy(files, target) {
|
|
55
|
+
for (const f of files) {
|
|
56
|
+
const p = join(target, f.path);
|
|
57
|
+
mkdirSync(join(p, '..'), { recursive: true });
|
|
58
|
+
writeFileSync(p, f.bytes, { mode: 0o644 });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
export function importSkill(s, dir, source) {
|
|
62
|
+
const files = readSkillDir(dir);
|
|
63
|
+
const dirName = dir.replace(/\/+$/, '').split('/').pop();
|
|
64
|
+
const v = validateSkill(dirName, files);
|
|
65
|
+
const name = v.meta?.name ?? dirName;
|
|
66
|
+
if (!/^[A-Za-z0-9._-]{1,64}$/.test(name))
|
|
67
|
+
throw new Error(`refusing skill: unusable name ${JSON.stringify(name)}`);
|
|
68
|
+
const hash = treeHash(files);
|
|
69
|
+
const target = join(dirs(s).quarantine, `${name}-${short(hash)}`);
|
|
70
|
+
rmSync(target, { recursive: true, force: true });
|
|
71
|
+
mkdirSync(target, { mode: 0o700 });
|
|
72
|
+
writeCopy(files, join(target, 'files'));
|
|
73
|
+
const report = { name, source, treeHash: hash, status: v.errors.length ? 'invalid' : 'quarantined', errors: v.errors, findings: auditSkill(files), importedAt: new Date().toISOString(), path: join(target, 'files') };
|
|
74
|
+
writeFileSync(join(target, 'report.json'), JSON.stringify(report, null, 2), { mode: 0o600 });
|
|
75
|
+
return report;
|
|
76
|
+
}
|
|
77
|
+
const latestQuarantined = (s, name) => {
|
|
78
|
+
const q = dirs(s).quarantine;
|
|
79
|
+
return readdirSync(q).filter(n => n.startsWith(name + '-')).map(n => JSON.parse(readFileSync(join(q, n, 'report.json'), 'utf8')))
|
|
80
|
+
.filter(r => r.name === name).sort((a, b) => a.importedAt.localeCompare(b.importedAt)).at(-1);
|
|
81
|
+
};
|
|
82
|
+
export function approveSkill(s, name, o) {
|
|
83
|
+
if (!o.approvedBy.trim())
|
|
84
|
+
throw new Error('approvedBy is required');
|
|
85
|
+
const r = latestQuarantined(s, name);
|
|
86
|
+
if (!r)
|
|
87
|
+
throw new Error(`no quarantined skill "${name}" — import it first`);
|
|
88
|
+
if (r.status === 'invalid')
|
|
89
|
+
throw new Error(`skill "${name}" is invalid (${r.errors.join('; ')}) — cannot be approved`);
|
|
90
|
+
const crit = r.findings.filter(f => f.severity === 'critical');
|
|
91
|
+
if (crit.length)
|
|
92
|
+
throw new Error(`skill "${name}" has critical findings (${crit.map(f => f.rule).join(', ')}) — blocked, cannot be approved`);
|
|
93
|
+
const high = r.findings.filter(f => f.severity === 'high');
|
|
94
|
+
if (high.length && !o.acceptFindings)
|
|
95
|
+
throw new Error(`skill "${name}" has high findings (${[...new Set(high.map(f => f.rule))].join(', ')}) — review them, then approve with --accept-findings`);
|
|
96
|
+
const files = readSkillDir(r.path);
|
|
97
|
+
if (treeHash(files) !== r.treeHash)
|
|
98
|
+
throw new Error(`quarantined copy of "${name}" changed since import — re-import it`);
|
|
99
|
+
const target = join(dirs(s).approved, `${name}-${short(r.treeHash)}`);
|
|
100
|
+
rmSync(target, { recursive: true, force: true });
|
|
101
|
+
writeCopy(files, target);
|
|
102
|
+
const entry = { name, source: r.source, treeHash: r.treeHash, status: 'approved', approvedBy: o.approvedBy.trim(), approvedAt: new Date().toISOString(), acceptedFindings: [...new Set(high.map(f => f.rule))] };
|
|
103
|
+
writeLock(s, [...readLock(s).filter(e => e.name !== name), entry]);
|
|
104
|
+
return entry;
|
|
105
|
+
}
|
|
106
|
+
export function revokeSkill(s, name, by) {
|
|
107
|
+
const lock = readLock(s);
|
|
108
|
+
const e = lock.find(x => x.name === name && x.status === 'approved');
|
|
109
|
+
if (!e)
|
|
110
|
+
throw new Error(`skill "${name}" is not approved`);
|
|
111
|
+
rmSync(join(dirs(s).approved, `${name}-${short(e.treeHash)}`), { recursive: true, force: true });
|
|
112
|
+
writeLock(s, lock.map(x => (x === e ? { ...x, status: 'revoked', revokedBy: by, revokedAt: new Date().toISOString() } : x)));
|
|
113
|
+
}
|
|
114
|
+
/** The skill's references/*.md, sorted: the agent cannot open the skill's folder, so they travel with SKILL.md. */
|
|
115
|
+
const references = (files) => files.filter(f => /^references\/[^/]+\.md$/.test(f.path)).sort((a, b) => (a.path < b.path ? -1 : 1))
|
|
116
|
+
.map(f => ({ path: f.path, text: f.bytes.toString('utf8') }));
|
|
117
|
+
/** Load an approved skill, re-hashing the approved copy (tampering ⇒ refused). */
|
|
118
|
+
export function loadApprovedSkill(s, name) {
|
|
119
|
+
const e = readLock(s).find(x => x.name === name && x.status === 'approved');
|
|
120
|
+
if (!e)
|
|
121
|
+
throw new Error(`skill "${name}" is not approved for this repository`);
|
|
122
|
+
const dir = join(dirs(s).approved, `${name}-${short(e.treeHash)}`);
|
|
123
|
+
if (!existsSync(dir))
|
|
124
|
+
throw new Error(`approved copy of "${name}" is missing`);
|
|
125
|
+
const files = readSkillDir(dir);
|
|
126
|
+
if (treeHash(files) !== e.treeHash)
|
|
127
|
+
throw new Error(`skill "${name}": tree hash mismatch with skills.lock — refusing (tampered?)`);
|
|
128
|
+
return { name, text: files.find(f => f.path === 'SKILL.md').bytes.toString('utf8'), treeHash: e.treeHash, origin: 'approved', references: references(files) };
|
|
129
|
+
}
|
|
130
|
+
export function listSkills(s) {
|
|
131
|
+
const q = dirs(s).quarantine;
|
|
132
|
+
const lock = readLock(s);
|
|
133
|
+
const reports = readdirSync(q).map(n => JSON.parse(readFileSync(join(q, n, 'report.json'), 'utf8')));
|
|
134
|
+
const names = [...new Set([...reports.map(r => r.name), ...lock.map(l => l.name)])].sort();
|
|
135
|
+
return names.map(n => {
|
|
136
|
+
const l = lock.find(x => x.name === n);
|
|
137
|
+
const r = reports.filter(x => x.name === n).at(-1);
|
|
138
|
+
return { name: n, status: (l?.status ?? r?.status ?? 'quarantined'), treeHash: l?.treeHash ?? r?.treeHash ?? '', findings: r?.findings.length ?? 0 };
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
// ── first-party skills (shipped with Taskquoin, pinned) ──────────────────────────────────────────────────────────────
|
|
142
|
+
const FP_ROOT = fileURLToPath(new URL('../../../skills/', import.meta.url));
|
|
143
|
+
export function firstPartyLock() { return JSON.parse(readFileSync(join(FP_ROOT, 'first-party.lock.json'), 'utf8')); }
|
|
144
|
+
export function computeFirstPartyLock() {
|
|
145
|
+
const out = {};
|
|
146
|
+
for (const d of readdirSync(FP_ROOT, { withFileTypes: true }))
|
|
147
|
+
if (d.isDirectory() && NAME_RE.test(d.name))
|
|
148
|
+
out[d.name] = treeHash(readSkillDir(join(FP_ROOT, d.name)));
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
export function loadFirstPartySkill(name) {
|
|
152
|
+
const lock = firstPartyLock();
|
|
153
|
+
if (!Object.hasOwn(lock, name))
|
|
154
|
+
throw new Error(`unknown first-party skill "${name}"`);
|
|
155
|
+
const files = readSkillDir(join(FP_ROOT, name));
|
|
156
|
+
const h = treeHash(files);
|
|
157
|
+
if (h !== lock[name])
|
|
158
|
+
throw new Error(`first-party skill "${name}" does not match skills/first-party.lock.json — refusing (modified Taskquoin checkout?)`);
|
|
159
|
+
return { name, text: files.find(f => f.path === 'SKILL.md').bytes.toString('utf8'), treeHash: h, origin: 'first-party', references: references(files) };
|
|
160
|
+
}
|
|
161
|
+
void chmodSync;
|
|
162
|
+
void cpSync;
|