cli-swarm 7.0.37 → 7.0.39
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 +14 -0
- package/broker-account-storage.mjs +135 -0
- package/broker-credentials.mjs +125 -0
- package/broker.mjs +13 -93
- package/installer-storage.mjs +205 -0
- package/installer.mjs +48 -63
- package/official-skill-update.mjs +151 -0
- package/package.json +16 -2
- package/skill/SKILL.md +82 -134
- package/skill/references/ops-heartbeat.md +3 -3
- package/skill/references/org-chart.md +5 -26
- package/skill/references/task-lifecycle.md +10 -2
- package/skill/references/task-routing.md +64 -0
- package/skill/references/traffic-light.md +3 -3
- package/skill/skill.json +1 -1
- package/swarm-coordinator-model.mjs +52 -0
- package/swarm-coordinator-waits.mjs +44 -24
- package/swarm-coordinator.mjs +11 -4
- package/swarm-runtime.mjs +45 -111
- package/swarm-task-contract.mjs +8 -0
- package/swarm-task-handoff.mjs +180 -0
- package/swarm-task-policy.mjs +142 -0
- package/swarm-task-routing-model.mjs +163 -0
- package/swarm-task-routing-schemas.mjs +24 -0
- package/swarm-task-routing.mjs +178 -0
package/README.md
CHANGED
|
@@ -42,3 +42,17 @@ Brain Client 服务端在同一次 runtime 请求的事务中绑定真实响应
|
|
|
42
42
|
仅在 TLS 握手前确定尚未发送 HTTP 请求时,broker 才允许最多 3 次连接尝试,并受总超时约束。请求发出后发生断线或响应中断,只用 GET 查询原 requestId 的服务端回执,禁止重发 POST;未取得有效回执时保留不确定状态,不得假定成功或继续依赖步骤。
|
|
43
43
|
|
|
44
44
|
`npx cli-swarm@latest recover <operation> <requestId>` 可重新查询原调用,不会重做操作或重复计费。链恢复不会跳过人工确认,也不会自动重跑结果不确定的本地命令。代理连接需 Node.js 22.21+ 或 24.5+;不支持的运行时会明确报错。
|
|
45
|
+
|
|
46
|
+
## 账号共享凭据与自动更新
|
|
47
|
+
|
|
48
|
+
在已登录的能力市场复制安装入口,将内容粘贴给 IDE。页面只展示原地址,剪贴板会携带当前账号凭据。IDE 将四字段凭据 JSON 经标准输入交给 `npx cli-aimlock@latest configure`;不要放到命令参数、项目文件或日志中。一次配置供同一操作系统账号的所有项目、分支和任务使用,八个技能共享同一文件。
|
|
49
|
+
|
|
50
|
+
默认位置:macOS 为 `~/Library/Application Support/CLI.Tax/broker/credential.json`,Linux 为 `~/.local/share/CLI.Tax/broker/credential.json`,Windows 为 `%LOCALAPPDATA%\CLI.Tax\broker\credential.json`。显式 `CLITAX_BRAIN_CLIENT_TOKEN_FILE` 仍按绝对路径覆盖默认位置;迁移旧 IDE 配置时移除其过时覆盖,再使用账号共享文件。macOS/Linux 校验当前账号所有权和0600权限;Windows校验仅当前账号与SYSTEM可访问的ACL。
|
|
51
|
+
|
|
52
|
+
每次新技能调用先查询官方发布版本,精确版本下载并校验身份后自动使用;更新已托管的当前项目与账号技能目录,失败恢复旧目录,禁止覆盖 Git 跟踪源码或未托管内容。升级返回 `upgrade.reloadRequired` 和说明路径时,IDE 应读取更新后的 SKILL.md、核对本任务合同再继续。install/check同样自动更新,不需要每次人工发升级指令。查询不确定调用的原回执不升级、不重发操作。
|
|
53
|
+
|
|
54
|
+
升级不会清除账号凭据;各调用重新读取共享文件,因此重新同步一次密钥后所有任务使用新值。已撤销或失效的密钥不能为自己取得新权限,必须从已认证网页重新同步一次。两个不同操作系统账号不共享私密文件。
|
|
55
|
+
|
|
56
|
+
English: configure once using JSON stdin; all tasks under the same OS account reuse the credential. Each new invocation checks and updates the official package and managed documentation. Reload updated instructions when indicated. Revoked keys require a fresh authenticated copy.
|
|
57
|
+
|
|
58
|
+
Русский: настройте ключ один раз через JSON stdin для всех задач пользователя ОС. Перед новым вызовом пакет и управляемые инструкции обновляются автоматически. Отозванный ключ требует повторной синхронизации с авторизованной страницы.
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { lstat, mkdir, readFile, rm } from 'node:fs/promises'
|
|
3
|
+
import { dirname, join, parse, resolve, win32 } from 'node:path'
|
|
4
|
+
import { userInfo } from 'node:os'
|
|
5
|
+
import { promisify } from 'node:util'
|
|
6
|
+
import { randomUUID } from 'node:crypto'
|
|
7
|
+
|
|
8
|
+
const runFile = promisify(execFile)
|
|
9
|
+
const DIRECTORY_MODE = 0o700
|
|
10
|
+
const FILE_MODE = 0o600
|
|
11
|
+
const SYSTEM_SID = 'S-1-5-18'
|
|
12
|
+
const ACL_SID_ALIASES = Object.freeze({ SY: SYSTEM_SID, WD: 'S-1-1-0', BA: 'S-1-5-32-544',
|
|
13
|
+
BU: 'S-1-5-32-545', AU: 'S-1-5-11', CO: 'S-1-3-0', CG: 'S-1-3-1', AN: 'S-1-5-7' })
|
|
14
|
+
const SID_PATTERN = /^S-1-(?:[0-9]+-)*[0-9]+$/
|
|
15
|
+
const ACL_TIMEOUT_MS = 15_000
|
|
16
|
+
|
|
17
|
+
export function currentAccountHome() {
|
|
18
|
+
const home = userInfo().homedir
|
|
19
|
+
if (typeof home !== 'string' || !parse(home).root) throw new Error('The current account has no absolute home directory')
|
|
20
|
+
return home
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function assertAccountAncestors(path, platform = process.platform) {
|
|
24
|
+
const paths = platform === 'win32' ? win32 : { dirname, resolve, parse }
|
|
25
|
+
let current = paths.resolve(path)
|
|
26
|
+
const ancestors = []
|
|
27
|
+
while (current !== paths.parse(current).root) {
|
|
28
|
+
ancestors.unshift(current)
|
|
29
|
+
current = paths.dirname(current)
|
|
30
|
+
}
|
|
31
|
+
for (const ancestor of ancestors) {
|
|
32
|
+
let status
|
|
33
|
+
try { status = await lstat(ancestor) } catch (error) {
|
|
34
|
+
if (error.code === 'ENOENT') continue
|
|
35
|
+
throw error
|
|
36
|
+
}
|
|
37
|
+
if (status.isSymbolicLink() || !status.isDirectory()) throw new Error('Account storage cannot traverse symlink or non-directory parents')
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function aclText(bytes) {
|
|
42
|
+
return bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe
|
|
43
|
+
? bytes.subarray(2).toString('utf16le') : bytes.toString('utf8')
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function windowsAclEntries(text) {
|
|
47
|
+
const descriptor = text.split(/\r?\n/).find(line => line.startsWith('D:'))
|
|
48
|
+
if (!descriptor) throw new Error('Windows ACL descriptor is missing')
|
|
49
|
+
const entries = [...descriptor.matchAll(/\(([^()]*)\)/g)].map(match => {
|
|
50
|
+
const fields = match[1].split(';')
|
|
51
|
+
if (fields.length !== 6) throw new Error('Windows ACL entry is invalid')
|
|
52
|
+
return { type: fields[0], flags: fields[1], rights: fields[2], sid: fields[5] }
|
|
53
|
+
})
|
|
54
|
+
if (!entries.length) throw new Error('Windows ACL cannot be empty')
|
|
55
|
+
return { descriptor, entries }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function assertRestrictedWindowsAcl(text, ownerSid) {
|
|
59
|
+
const { descriptor, entries } = windowsAclEntries(text)
|
|
60
|
+
if (!descriptor.startsWith('D:P') || entries.length !== 2) throw new Error('Windows account ACL must be protected and grant only the user and SYSTEM')
|
|
61
|
+
const expected = new Set([ownerSid, SYSTEM_SID])
|
|
62
|
+
for (const entry of entries) {
|
|
63
|
+
const sid = Object.hasOwn(ACL_SID_ALIASES, entry.sid) ? ACL_SID_ALIASES[entry.sid] : entry.sid
|
|
64
|
+
if (entry.type !== 'A' || !['FA', '0x1f01ff'].includes(entry.rights)
|
|
65
|
+
|| entry.flags.replaceAll('OI', '').replaceAll('CI', '') !== '' || !expected.delete(sid)) {
|
|
66
|
+
throw new Error('Windows account ACL contains unexpected access')
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (expected.size) throw new Error('Windows account ACL is missing the user or SYSTEM')
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function windowsOwnerSid(run) {
|
|
73
|
+
const result = await run('whoami.exe', ['/user', '/fo', 'csv', '/nh'], { windowsHide: true, timeout: ACL_TIMEOUT_MS })
|
|
74
|
+
const candidates = result.stdout.match(/S-1-(?:[0-9]+-)*[0-9]+/g)
|
|
75
|
+
if (candidates === null || candidates.length !== 1 || !SID_PATTERN.test(candidates[0])) throw new Error('Current Windows account SID could not be verified')
|
|
76
|
+
return candidates[0]
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function readWindowsAcl(path, run) {
|
|
80
|
+
const temporary = join(dirname(path), '.acl-' + randomUUID() + '.txt')
|
|
81
|
+
try {
|
|
82
|
+
await run('icacls.exe', [path, '/save', temporary, '/q'], { windowsHide: true, timeout: ACL_TIMEOUT_MS })
|
|
83
|
+
return aclText(await readFile(temporary))
|
|
84
|
+
} finally {
|
|
85
|
+
try { await rm(temporary) } catch (error) { if (error.code !== 'ENOENT') throw error }
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function protectWindowsPath(path, directory, dependencies) {
|
|
90
|
+
const run = dependencies.execFile === undefined ? runFile : dependencies.execFile
|
|
91
|
+
const owner = await windowsOwnerSid(run)
|
|
92
|
+
const flags = directory ? '(OI)(CI)F' : 'F'
|
|
93
|
+
await run('icacls.exe', [path, '/inheritance:r', '/grant:r', '*' + owner + ':' + flags,
|
|
94
|
+
'*' + SYSTEM_SID + ':' + flags], { windowsHide: true, timeout: ACL_TIMEOUT_MS })
|
|
95
|
+
const { entries } = windowsAclEntries(await readWindowsAcl(path, run))
|
|
96
|
+
for (const entry of entries) {
|
|
97
|
+
const sid = Object.hasOwn(ACL_SID_ALIASES, entry.sid) ? ACL_SID_ALIASES[entry.sid] : entry.sid
|
|
98
|
+
if (entry.type === 'A' && [owner, SYSTEM_SID].includes(sid)) continue
|
|
99
|
+
if (!SID_PATTERN.test(sid)) throw new Error('Unexpected Windows ACL trustee')
|
|
100
|
+
await run('icacls.exe', [path, entry.type === 'D' ? '/remove:d' : '/remove:g', '*' + sid],
|
|
101
|
+
{ windowsHide: true, timeout: ACL_TIMEOUT_MS })
|
|
102
|
+
}
|
|
103
|
+
assertRestrictedWindowsAcl(await readWindowsAcl(path, run), owner)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export async function protectAccountPath(path, directory, dependencies = {}) {
|
|
107
|
+
const platform = dependencies.platform === undefined ? process.platform : dependencies.platform
|
|
108
|
+
await assertAccountAncestors(dirname(path), platform)
|
|
109
|
+
const status = await lstat(path)
|
|
110
|
+
if (status.isSymbolicLink() || (directory ? !status.isDirectory() : !status.isFile())) throw new Error('Account storage object has an unsafe type')
|
|
111
|
+
if (platform === 'win32') return protectWindowsPath(path, directory, dependencies)
|
|
112
|
+
const mode = directory ? DIRECTORY_MODE : FILE_MODE
|
|
113
|
+
if (status.uid !== process.getuid() || (status.mode & 0o777) !== mode) throw new Error('Account storage must be owned by the current account with restricted permissions')
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function ensureAccountDirectory(path, dependencies = {}) {
|
|
117
|
+
const platform = dependencies.platform === undefined ? process.platform : dependencies.platform
|
|
118
|
+
await assertAccountAncestors(path, platform)
|
|
119
|
+
await mkdir(path, { recursive: true, mode: DIRECTORY_MODE })
|
|
120
|
+
await protectAccountPath(path, true, dependencies)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function verifyAccountPath(path, dependencies = {}) {
|
|
124
|
+
const platform = dependencies.platform === undefined ? process.platform : dependencies.platform
|
|
125
|
+
await assertAccountAncestors(dirname(path), platform)
|
|
126
|
+
const status = await lstat(path)
|
|
127
|
+
if (!status.isFile() || status.isSymbolicLink()) throw new Error('Credential must be a regular account file')
|
|
128
|
+
if (platform !== 'win32') {
|
|
129
|
+
if (status.uid !== process.getuid() || (status.mode & 0o777) !== FILE_MODE) throw new Error('Credential must be owned by the account with mode 0600')
|
|
130
|
+
return
|
|
131
|
+
}
|
|
132
|
+
const run = dependencies.execFile === undefined ? runFile : dependencies.execFile
|
|
133
|
+
const owner = await windowsOwnerSid(run)
|
|
134
|
+
assertRestrictedWindowsAcl(await readWindowsAcl(path, run), owner)
|
|
135
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { constants } from 'node:fs'
|
|
2
|
+
import { lstat, open, rename, rm } from 'node:fs/promises'
|
|
3
|
+
import { currentAccountHome, ensureAccountDirectory, protectAccountPath, verifyAccountPath } from './broker-account-storage.mjs'
|
|
4
|
+
import { isAbsolute, join, resolve, win32 } from 'node:path'
|
|
5
|
+
import { randomUUID } from 'node:crypto'
|
|
6
|
+
|
|
7
|
+
const TOKEN_FILE_ENV = 'CLITAX_BRAIN_CLIENT_TOKEN_FILE'
|
|
8
|
+
const TOKEN_FILE_VERSION = 'member-brain.client-token-file/1.0'
|
|
9
|
+
const TOKEN_FILE_MAX_BYTES = 16_384
|
|
10
|
+
const AUTH_SCHEME = 'BrainClient'
|
|
11
|
+
const TOKEN_ENDPOINT = 'https://cli.tax/api/v1/telemetry/skill-usage'
|
|
12
|
+
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/
|
|
13
|
+
const TOKEN_MODE = 0o600
|
|
14
|
+
|
|
15
|
+
export function accountBrokerDirectory(environment, platform = process.platform, home = currentAccountHome()) {
|
|
16
|
+
if (platform === 'win32') {
|
|
17
|
+
if (typeof environment.LOCALAPPDATA !== 'string' || !win32.isAbsolute(environment.LOCALAPPDATA)) {
|
|
18
|
+
throw new Error('LOCALAPPDATA must identify the current account directory')
|
|
19
|
+
}
|
|
20
|
+
const relative = win32.relative(home, environment.LOCALAPPDATA)
|
|
21
|
+
if (relative === '..' || relative.startsWith('..\\') || win32.isAbsolute(relative)) throw new Error('LOCALAPPDATA must belong to the current account home')
|
|
22
|
+
return win32.join(environment.LOCALAPPDATA, 'CLI.Tax', 'broker')
|
|
23
|
+
}
|
|
24
|
+
if (!isAbsolute(home)) throw new Error('Account home directory must be absolute')
|
|
25
|
+
return platform === 'darwin' ? join(home, 'Library', 'Application Support', 'CLI.Tax', 'broker')
|
|
26
|
+
: join(home, '.local', 'share', 'CLI.Tax', 'broker')
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function brainClientTokenPath(environment, platform = process.platform, home = currentAccountHome()) {
|
|
30
|
+
const configured = environment[TOKEN_FILE_ENV]
|
|
31
|
+
const directory = accountBrokerDirectory(environment, platform, home)
|
|
32
|
+
if (configured === undefined) return platform === 'win32'
|
|
33
|
+
? win32.join(directory, 'credential.json') : join(directory, 'credential.json')
|
|
34
|
+
if (typeof configured !== 'string' || !configured.trim()) throw new Error(TOKEN_FILE_ENV + ' must be an absolute path')
|
|
35
|
+
const candidate = configured.trim()
|
|
36
|
+
if (platform !== 'win32') {
|
|
37
|
+
if (!isAbsolute(candidate)) throw new Error(TOKEN_FILE_ENV + ' must be absolute and independent of the project directory')
|
|
38
|
+
return resolve(candidate)
|
|
39
|
+
}
|
|
40
|
+
if (!win32.isAbsolute(candidate)) throw new Error('Windows Brain Client token file path must be absolute')
|
|
41
|
+
const path = win32.resolve(candidate), relative = win32.relative(directory, path)
|
|
42
|
+
if (relative === '..' || relative.startsWith('..\\') || win32.isAbsolute(relative)) {
|
|
43
|
+
throw new Error('Windows Brain Client token file must be inside its account broker directory')
|
|
44
|
+
}
|
|
45
|
+
return path
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function validateBrainClientCredential(value, endpoint = TOKEN_ENDPOINT) {
|
|
49
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
50
|
+
|| Object.keys(value).sort().join(',') !== 'authorizationScheme,endpoint,schemaVersion,token') {
|
|
51
|
+
throw new Error('Brain Client credential has unknown or missing fields')
|
|
52
|
+
}
|
|
53
|
+
if (value.schemaVersion !== TOKEN_FILE_VERSION || value.authorizationScheme !== AUTH_SCHEME
|
|
54
|
+
|| value.endpoint !== TOKEN_ENDPOINT || new URL(endpoint).origin !== new URL(TOKEN_ENDPOINT).origin
|
|
55
|
+
|| typeof value.token !== 'string' || !TOKEN_PATTERN.test(value.token)) {
|
|
56
|
+
throw new Error('Brain Client token file authority is invalid')
|
|
57
|
+
}
|
|
58
|
+
return value
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function parseCredential(source) {
|
|
62
|
+
if (Buffer.byteLength(source) > TOKEN_FILE_MAX_BYTES) throw new Error('Brain Client credential exceeds the size limit')
|
|
63
|
+
let parsed
|
|
64
|
+
try { parsed = JSON.parse(source) } catch { throw new Error('Brain Client credential must contain valid JSON') }
|
|
65
|
+
return validateBrainClientCredential(parsed)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function assertRestrictedFile(status, platform, currentUserId) {
|
|
69
|
+
if (!status.isFile() || status.size < 1 || status.size > TOKEN_FILE_MAX_BYTES) {
|
|
70
|
+
throw new Error('Brain Client token file must be a non-empty restricted file')
|
|
71
|
+
}
|
|
72
|
+
if (platform === 'win32') return
|
|
73
|
+
if (!Number.isInteger(currentUserId) || status.uid !== currentUserId || (status.mode & 0o777) !== TOKEN_MODE) {
|
|
74
|
+
throw new Error('Brain Client token file must be owned by the current user with mode 0600')
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function brainClientAuthorization(context, environment, dependencies = {}) {
|
|
79
|
+
const platform = dependencies.platform === undefined ? process.platform : dependencies.platform
|
|
80
|
+
const path = brainClientTokenPath(environment, platform, dependencies.homeDirectory === undefined ? currentAccountHome() : dependencies.homeDirectory)
|
|
81
|
+
const inspect = dependencies.lstat === undefined ? lstat : dependencies.lstat
|
|
82
|
+
const openFile = dependencies.open === undefined ? open : dependencies.open
|
|
83
|
+
const currentUserId = platform === 'win32' ? null : (dependencies.getuid === undefined ? process.getuid : dependencies.getuid)()
|
|
84
|
+
let status
|
|
85
|
+
try { status = await inspect(path) } catch (error) {
|
|
86
|
+
if (error.code === 'ENOENT') throw new Error('Brain Client credential is not configured; copy the authenticated setup from CLI.Tax and run configure with JSON stdin')
|
|
87
|
+
throw error
|
|
88
|
+
}
|
|
89
|
+
if (status.isSymbolicLink()) throw new Error('Brain Client token file cannot be a symlink')
|
|
90
|
+
const verifyPath = dependencies.verifyPath === undefined ? verifyAccountPath : dependencies.verifyPath
|
|
91
|
+
await verifyPath(path, { ...dependencies, platform })
|
|
92
|
+
const handle = await openFile(path, constants.O_RDONLY | (platform === 'win32' ? 0 : constants.O_NOFOLLOW))
|
|
93
|
+
try {
|
|
94
|
+
assertRestrictedFile(await handle.stat(), platform, currentUserId)
|
|
95
|
+
const value = validateBrainClientCredential(parseCredential(await handle.readFile('utf8')), context.endpoint)
|
|
96
|
+
return AUTH_SCHEME + ' ' + value.token
|
|
97
|
+
} finally { await handle.close() }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function configureBrainClientCredential(source, environment = process.env, dependencies = {}) {
|
|
101
|
+
const credential = parseCredential(source)
|
|
102
|
+
const platform = dependencies.platform === undefined ? process.platform : dependencies.platform
|
|
103
|
+
const home = dependencies.homeDirectory === undefined ? currentAccountHome() : dependencies.homeDirectory
|
|
104
|
+
const directory = accountBrokerDirectory(environment, platform, home)
|
|
105
|
+
await ensureAccountDirectory(directory, { ...dependencies, platform })
|
|
106
|
+
const path = join(directory, 'credential.json')
|
|
107
|
+
try { await protectAccountPath(path, false, { ...dependencies, platform }) }
|
|
108
|
+
catch (error) { if (error.code !== 'ENOENT') throw error }
|
|
109
|
+
const temporary = join(directory, 'credential-' + randomUUID() + '.json')
|
|
110
|
+
const handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL
|
|
111
|
+
| (platform === 'win32' ? 0 : constants.O_NOFOLLOW), TOKEN_MODE)
|
|
112
|
+
try {
|
|
113
|
+
await handle.writeFile(JSON.stringify(credential) + '\n')
|
|
114
|
+
await handle.sync()
|
|
115
|
+
} finally { await handle.close() }
|
|
116
|
+
try {
|
|
117
|
+
await protectAccountPath(temporary, false, { ...dependencies, platform })
|
|
118
|
+
await rename(temporary, path)
|
|
119
|
+
await protectAccountPath(path, false, { ...dependencies, platform })
|
|
120
|
+
} catch (error) {
|
|
121
|
+
try { await rm(temporary) } catch (cleanupError) { if (cleanupError.code !== 'ENOENT') throw cleanupError }
|
|
122
|
+
throw error
|
|
123
|
+
}
|
|
124
|
+
return { configured: true, path, scope: 'current-account', requiresEnvironmentOverrideRemoval: environment[TOKEN_FILE_ENV] !== undefined }
|
|
125
|
+
}
|
package/broker.mjs
CHANGED
|
@@ -1,25 +1,17 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
2
|
+
import { brainClientAuthorization } from './broker-credentials.mjs'
|
|
3
|
+
import { prepareOfficialSkillUse, withUpgradeMetadata } from './official-skill-update.mjs'
|
|
4
|
+
export { brainClientAuthorization, brainClientTokenPath } from './broker-credentials.mjs'
|
|
5
|
+
export { LOOKUP_TIMEOUT_MS } from './official-skill-update.mjs'
|
|
5
6
|
import { OfficialSkillInvocationError, OfficialSkillResponseError, transportFailureCode, transportDiagnostics } from './broker-failures.mjs'
|
|
6
7
|
import { queryOfficialSkillReceipt, SKILL_RECEIPT_HEADER, SKILL_RECEIPT_SCHEMA } from './broker-recovery.mjs'
|
|
7
8
|
export { officialSkillFailureResponse, transportFailureCode } from './broker-failures.mjs'
|
|
8
9
|
|
|
9
|
-
export const LOOKUP_TIMEOUT_MS = 8000
|
|
10
10
|
export const CALL_TIMEOUT_MS = 120_000
|
|
11
|
-
const FEEDBACK_API_PATH = '/api/v1/telemetry/skill-usage'
|
|
12
|
-
const TOKEN_FILE_ENV = 'CLITAX_BRAIN_CLIENT_TOKEN_FILE'
|
|
13
|
-
const TOKEN_FILE_VERSION = 'member-brain.client-token-file/1.0'
|
|
14
|
-
const AUTH_SCHEME = 'BrainClient'
|
|
15
|
-
const TOKEN_FILE_MAX_BYTES = 16_384
|
|
16
|
-
const POSIX_TOKEN_FILE_MODE = 0o600
|
|
17
|
-
const WINDOWS_BROKER_DIRECTORY = ['CLI.Tax', 'broker']
|
|
18
11
|
const FEEDBACK_COMMENT_MAX = 500
|
|
19
12
|
const EVALUATION_DURATION_MAX = 86_400_000
|
|
20
13
|
const SCORE_MIN = 0
|
|
21
14
|
const SCORE_MAX = 100
|
|
22
|
-
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/
|
|
23
15
|
const INVOCATION_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
|
|
24
16
|
const DIGEST_PATTERN = /^[0-9a-f]{64}$/
|
|
25
17
|
const PROTOCOL_STATUSES = new Set(['succeeded', 'blocked', 'failed'])
|
|
@@ -48,84 +40,6 @@ function boundedInteger(value, label) {
|
|
|
48
40
|
return value
|
|
49
41
|
}
|
|
50
42
|
|
|
51
|
-
function insideWindowsDirectory(candidate, directory) {
|
|
52
|
-
const relative = win32.relative(directory, candidate)
|
|
53
|
-
return relative === '' || (!relative.startsWith('..\\') && relative !== '..' && !win32.isAbsolute(relative))
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export function brainClientTokenPath(environment, platform = process.platform) {
|
|
57
|
-
const configured = requiredString(environment[TOKEN_FILE_ENV], TOKEN_FILE_ENV)
|
|
58
|
-
if (platform !== 'win32') return resolve(configured)
|
|
59
|
-
if (!win32.isAbsolute(configured)) {
|
|
60
|
-
throw new Error('Windows Brain Client token file path must be absolute')
|
|
61
|
-
}
|
|
62
|
-
const localAppData = requiredString(environment.LOCALAPPDATA, 'LOCALAPPDATA')
|
|
63
|
-
const brokerDirectory = win32.resolve(localAppData, ...WINDOWS_BROKER_DIRECTORY)
|
|
64
|
-
const candidate = win32.resolve(configured)
|
|
65
|
-
if (!insideWindowsDirectory(candidate, brokerDirectory)) {
|
|
66
|
-
throw new Error(`Windows Brain Client token file must be inside ${brokerDirectory}`)
|
|
67
|
-
}
|
|
68
|
-
return candidate
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function assertTokenFileStatus(status, platform, currentUserId) {
|
|
72
|
-
if (!status.isFile() || status.size < 1 || status.size > TOKEN_FILE_MAX_BYTES) {
|
|
73
|
-
throw new Error('Brain Client token file must be a non-empty restricted file')
|
|
74
|
-
}
|
|
75
|
-
if (platform === 'win32') return
|
|
76
|
-
if (!Number.isInteger(currentUserId)) {
|
|
77
|
-
throw new Error('Brain Client token file ownership cannot be verified')
|
|
78
|
-
}
|
|
79
|
-
if (status.uid !== currentUserId || (status.mode & 0o777) !== POSIX_TOKEN_FILE_MODE) {
|
|
80
|
-
throw new Error('Brain Client token file must be owned by the current user with mode 0600')
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
function parseTokenFile(source) {
|
|
85
|
-
let tokenFile
|
|
86
|
-
try {
|
|
87
|
-
tokenFile = asObject(JSON.parse(source), 'Brain Client token file')
|
|
88
|
-
} catch {
|
|
89
|
-
throw new Error('Brain Client token file must contain valid JSON')
|
|
90
|
-
}
|
|
91
|
-
const expectedKeys = ['authorizationScheme', 'endpoint', 'schemaVersion', 'token']
|
|
92
|
-
if (Object.keys(tokenFile).sort().join('\n') !== expectedKeys.join('\n')) {
|
|
93
|
-
throw new Error('Brain Client token file contains unknown or missing fields')
|
|
94
|
-
}
|
|
95
|
-
return tokenFile
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export async function brainClientAuthorization(context, environment, dependencies = {}) {
|
|
99
|
-
const platform = dependencies.platform ?? process.platform
|
|
100
|
-
const tokenFilePath = brainClientTokenPath(environment, platform)
|
|
101
|
-
const inspectPath = dependencies.lstat ?? lstat
|
|
102
|
-
const openPath = dependencies.open ?? open
|
|
103
|
-
const currentUserId = platform === 'win32'
|
|
104
|
-
? null
|
|
105
|
-
: (dependencies.getuid ?? process.getuid)?.()
|
|
106
|
-
const linkStatus = await inspectPath(tokenFilePath)
|
|
107
|
-
if (linkStatus.isSymbolicLink()) throw new Error('Brain Client token file cannot be a symlink')
|
|
108
|
-
const noFollow = platform === 'win32' ? 0 : (constants.O_NOFOLLOW ?? 0)
|
|
109
|
-
const handle = await openPath(tokenFilePath, constants.O_RDONLY | noFollow)
|
|
110
|
-
try {
|
|
111
|
-
const status = await handle.stat()
|
|
112
|
-
assertTokenFileStatus(status, platform, currentUserId)
|
|
113
|
-
const tokenFile = parseTokenFile(await handle.readFile('utf8'))
|
|
114
|
-
const endpoint = new URL(requiredString(tokenFile.endpoint, 'Brain Client endpoint'))
|
|
115
|
-
if (tokenFile.schemaVersion !== TOKEN_FILE_VERSION
|
|
116
|
-
|| tokenFile.authorizationScheme !== AUTH_SCHEME
|
|
117
|
-
|| endpoint.origin !== new URL(context.endpoint).origin
|
|
118
|
-
|| endpoint.pathname !== FEEDBACK_API_PATH || endpoint.search || endpoint.hash
|
|
119
|
-
|| endpoint.username || endpoint.password
|
|
120
|
-
|| !TOKEN_PATTERN.test(tokenFile.token)) {
|
|
121
|
-
throw new Error('Brain Client token file authority is invalid')
|
|
122
|
-
}
|
|
123
|
-
return `${AUTH_SCHEME} ${tokenFile.token}`
|
|
124
|
-
} finally {
|
|
125
|
-
await handle.close()
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
|
|
129
43
|
function canonicalJson(value) {
|
|
130
44
|
if (value === null || typeof value === 'string' || typeof value === 'boolean') {
|
|
131
45
|
return JSON.stringify(value)
|
|
@@ -205,6 +119,9 @@ export function authoritativeEvaluation(value, expected) {
|
|
|
205
119
|
|
|
206
120
|
async function responsePayload(response, context, request) {
|
|
207
121
|
const label = `${context.displayName} ${request.operation} response`
|
|
122
|
+
if (response.status === 401 || response.status === 403) {
|
|
123
|
+
throw new OfficialSkillResponseError(request, 'http-response', 'Brain Client authorization was rejected; copy the current authenticated setup from CLI.Tax and run configure again. Revoked credentials cannot renew themselves.')
|
|
124
|
+
}
|
|
208
125
|
let payload
|
|
209
126
|
try {
|
|
210
127
|
payload = await response.json()
|
|
@@ -235,6 +152,9 @@ function invocationRequest(context, operation, input) {
|
|
|
235
152
|
}
|
|
236
153
|
|
|
237
154
|
export async function invokeOfficialSkill(context, operation, input, dependencies) {
|
|
155
|
+
const prepared = await prepareOfficialSkillUse(context, 'broker.mjs', dependencies)
|
|
156
|
+
if (prepared.module !== null) return withUpgradeMetadata(
|
|
157
|
+
await prepared.module.invokeOfficialSkill(prepared.context, operation, input, dependencies), prepared.upgrade)
|
|
238
158
|
const environment = asObject(dependencies.environment, 'broker environment')
|
|
239
159
|
if (typeof dependencies.request !== 'function') {
|
|
240
160
|
throw new Error('broker request dependency is required')
|
|
@@ -252,14 +172,14 @@ export async function invokeOfficialSkill(context, operation, input, dependencie
|
|
|
252
172
|
})
|
|
253
173
|
} catch (error) {
|
|
254
174
|
const failure = new OfficialSkillInvocationError(context, requestEnvelope, transportFailureCode(error), 'request', error?.transport)
|
|
255
|
-
return recoverTransportFailure(context, requestEnvelope, dependencies, authorization, failure)
|
|
175
|
+
return withUpgradeMetadata(await recoverTransportFailure(context, requestEnvelope, dependencies, authorization, failure), prepared.upgrade)
|
|
256
176
|
}
|
|
257
177
|
let payload
|
|
258
178
|
try {
|
|
259
179
|
payload = await responsePayload(response, context, requestEnvelope)
|
|
260
180
|
} catch (error) {
|
|
261
181
|
if (!(error instanceof OfficialSkillInvocationError)) throw error
|
|
262
|
-
return recoverTransportFailure(context, requestEnvelope, dependencies, authorization, error)
|
|
182
|
+
return withUpgradeMetadata(await recoverTransportFailure(context, requestEnvelope, dependencies, authorization, error), prepared.upgrade)
|
|
263
183
|
}
|
|
264
184
|
if (!response.ok || payload.ok !== true) {
|
|
265
185
|
throw new OfficialSkillResponseError(requestEnvelope, 'http-response', `${context.displayName} ${operation} failed: HTTP ${response.status}`)
|
|
@@ -267,7 +187,7 @@ export async function invokeOfficialSkill(context, operation, input, dependencie
|
|
|
267
187
|
try {
|
|
268
188
|
const invocation = validateInvocationResponse(context, operation, payload, requestEnvelope)
|
|
269
189
|
const transport = transportDiagnostics(response.transport)
|
|
270
|
-
return transport ? { ...invocation, transport } : invocation
|
|
190
|
+
return withUpgradeMetadata(transport ? { ...invocation, transport } : invocation, prepared.upgrade)
|
|
271
191
|
} catch (error) {
|
|
272
192
|
throw new OfficialSkillResponseError(requestEnvelope, 'response-validation',
|
|
273
193
|
error instanceof Error ? error.message : 'Skill response validation failed')
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
4
|
+
import { cp, lstat, mkdir, readdir, rename, rm, writeFile } from 'node:fs/promises'
|
|
5
|
+
import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
6
|
+
import { promisify } from 'node:util'
|
|
7
|
+
import { assertAccountAncestors, currentAccountHome } from './broker-account-storage.mjs'
|
|
8
|
+
|
|
9
|
+
const runFile = promisify(execFile)
|
|
10
|
+
const INSTALL_META = 'install-meta.json'
|
|
11
|
+
const MAX_SKILL_FILES = 256
|
|
12
|
+
const GIT_TIMEOUT_MS = 8000
|
|
13
|
+
|
|
14
|
+
function object(value, label) {
|
|
15
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(label + ' must be an object')
|
|
16
|
+
return value
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function readInstallMeta(target) {
|
|
20
|
+
const path = join(target, INSTALL_META)
|
|
21
|
+
if (!existsSync(path)) return null
|
|
22
|
+
return object(JSON.parse(readFileSync(path, 'utf8')), INSTALL_META)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function installTarget(skillName, explicit, environment = process.env, workingDirectory = process.cwd()) {
|
|
26
|
+
if (explicit !== undefined) {
|
|
27
|
+
if (typeof explicit !== 'string' || !explicit.trim()) throw new Error('Install directory must be non-empty')
|
|
28
|
+
return resolve(explicit)
|
|
29
|
+
}
|
|
30
|
+
if (environment.CODEX_HOME !== undefined) {
|
|
31
|
+
if (typeof environment.CODEX_HOME !== 'string' || !isAbsolute(environment.CODEX_HOME)) throw new Error('CODEX_HOME must be absolute')
|
|
32
|
+
return join(environment.CODEX_HOME, 'skills', skillName)
|
|
33
|
+
}
|
|
34
|
+
return join(workingDirectory, '.codex', 'skills', skillName)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function contained(root, path) {
|
|
38
|
+
const inside = relative(root, path)
|
|
39
|
+
return inside === '' || (!inside.startsWith('..' + '/') && inside !== '..' && !isAbsolute(inside)
|
|
40
|
+
&& !inside.startsWith('..' + '\\'))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function sameIdentity(meta, context) {
|
|
44
|
+
return meta.source === context.runtimeCode && meta.slug === context.skillName && meta.endpoint === context.endpoint
|
|
45
|
+
&& typeof meta.version === 'string' && /^v?\d+\.\d+\.\d+$/.test(meta.version)
|
|
46
|
+
&& typeof meta.packageVersion === 'string' && /^\d+\.\d+\.\d+$/.test(meta.packageVersion)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function newerVersion(installed, selected) {
|
|
50
|
+
const parts = version => {
|
|
51
|
+
if (typeof version !== 'string' || !/^v?\d+\.\d+\.\d+$/.test(version)) {
|
|
52
|
+
throw new Error('Managed skill comparison requires a semantic release version')
|
|
53
|
+
}
|
|
54
|
+
return version.replace(/^v/, '').split('.').map(value => BigInt(value))
|
|
55
|
+
}
|
|
56
|
+
const left = parts(installed), right = parts(selected)
|
|
57
|
+
const index = left.findIndex((part, position) => part !== right[position])
|
|
58
|
+
return index !== -1 && left[index] > right[index]
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function assertNoManagedDowngrade(previous, context) {
|
|
62
|
+
if (previous !== null && (newerVersion(previous.version, context.skillVersion)
|
|
63
|
+
|| newerVersion(previous.packageVersion, context.packageVersion))) {
|
|
64
|
+
throw new Error('The managed skill is newer than the selected release; refusing to downgrade its installation')
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function targetExists(path) {
|
|
69
|
+
try { return await lstat(path) } catch (error) { if (error.code === 'ENOENT') return null; throw error }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function trackedSource(target) {
|
|
73
|
+
let current = dirname(target)
|
|
74
|
+
for (;;) {
|
|
75
|
+
if (await targetExists(join(current, '.git')) !== null) {
|
|
76
|
+
try {
|
|
77
|
+
const result = await runFile('git', ['-C', current, 'ls-files', '--', relative(current, target)],
|
|
78
|
+
{ timeout: GIT_TIMEOUT_MS, maxBuffer: 1_048_576 })
|
|
79
|
+
return result.stdout.trim().length > 0
|
|
80
|
+
} catch { throw new Error('Cannot verify whether the install target contains repository source files') }
|
|
81
|
+
}
|
|
82
|
+
const parent = dirname(current)
|
|
83
|
+
if (parent === current) return false
|
|
84
|
+
current = parent
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function managedTarget(context, target, allowCreate) {
|
|
89
|
+
const path = resolve(target)
|
|
90
|
+
await assertAccountAncestors(dirname(path))
|
|
91
|
+
if (contained(resolve(context.packageRoot), path) || contained(path, resolve(context.packageRoot))) {
|
|
92
|
+
return { path, status: 'skipped', reason: 'package-source' }
|
|
93
|
+
}
|
|
94
|
+
const status = await targetExists(path)
|
|
95
|
+
if (status === null) return allowCreate ? { path, status: 'new', meta: null }
|
|
96
|
+
: { path, status: 'skipped', reason: 'not-installed' }
|
|
97
|
+
if (!status.isDirectory() || status.isSymbolicLink()) throw new Error('Installed skill target must be a regular directory')
|
|
98
|
+
if (await trackedSource(path)) return { path, status: 'skipped', reason: 'repository-source' }
|
|
99
|
+
const metaStatus = await targetExists(join(path, INSTALL_META))
|
|
100
|
+
if (metaStatus === null) return { path, status: 'skipped', reason: 'unmanaged' }
|
|
101
|
+
if (!metaStatus.isFile() || metaStatus.isSymbolicLink()) throw new Error('Install metadata must be a regular file')
|
|
102
|
+
if (process.platform !== 'win32' && (status.uid !== process.getuid() || metaStatus.uid !== process.getuid())) throw new Error('Managed skill installation must belong to the current account')
|
|
103
|
+
const meta = readInstallMeta(path)
|
|
104
|
+
if (!sameIdentity(meta, context)) return { path, status: 'skipped', reason: 'identity-mismatch' }
|
|
105
|
+
return { path, status: 'managed', meta }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function verifySkillSource(directory, context) {
|
|
109
|
+
let files = 0
|
|
110
|
+
async function visit(path) {
|
|
111
|
+
const status = await lstat(path)
|
|
112
|
+
if (status.isSymbolicLink()) throw new Error('Skill package cannot contain symbolic links')
|
|
113
|
+
if (status.isDirectory()) {
|
|
114
|
+
for (const entry of await readdir(path)) await visit(join(path, entry))
|
|
115
|
+
return
|
|
116
|
+
}
|
|
117
|
+
if (!status.isFile() || ++files > MAX_SKILL_FILES) throw new Error('Skill package contains an unsupported or excessive file set')
|
|
118
|
+
}
|
|
119
|
+
await assertAccountAncestors(directory)
|
|
120
|
+
await visit(directory)
|
|
121
|
+
const skill = object(JSON.parse(readFileSync(join(directory, 'skill.json'), 'utf8')), 'skill.json')
|
|
122
|
+
if (skill.name !== context.skillName || skill.endpoint !== context.endpoint || skill.version !== context.skillVersion) {
|
|
123
|
+
throw new Error('Skill package documentation identity does not match the selected version')
|
|
124
|
+
}
|
|
125
|
+
const markdown = await lstat(join(directory, 'SKILL.md'))
|
|
126
|
+
if (!markdown.isFile() || markdown.size === 0) throw new Error('Skill package must contain its actual SKILL.md')
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function restoreInstallation(target, backup, placed, renamePath) {
|
|
130
|
+
if (placed) await rm(target, { recursive: true })
|
|
131
|
+
if (backup !== null) await renamePath(backup, target)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function replaceInstallation(context, target, previous, dependencies) {
|
|
135
|
+
const renamePath = dependencies.rename === undefined ? rename : dependencies.rename
|
|
136
|
+
const suffix = randomUUID()
|
|
137
|
+
const stage = join(dirname(target), '.' + context.skillName + '.stage-' + suffix)
|
|
138
|
+
const backup = previous === null ? null : join(dirname(target), '.' + context.skillName + '.backup-' + suffix)
|
|
139
|
+
let moved = false, placed = false
|
|
140
|
+
await mkdir(stage, { mode: 0o700 })
|
|
141
|
+
try {
|
|
142
|
+
await verifySkillSource(context.skillDir, context)
|
|
143
|
+
for (const entry of await readdir(context.skillDir)) {
|
|
144
|
+
await cp(join(context.skillDir, entry), join(stage, entry), { recursive: true, force: false, errorOnExist: true })
|
|
145
|
+
}
|
|
146
|
+
await writeFile(join(stage, INSTALL_META), JSON.stringify({ source: context.runtimeCode, slug: context.skillName,
|
|
147
|
+
version: context.skillVersion, packageVersion: context.packageVersion, endpoint: context.endpoint,
|
|
148
|
+
installedAt: new Date().toISOString() }) + '\n', { flag: 'wx', mode: 0o600 })
|
|
149
|
+
await verifySkillSource(stage, context)
|
|
150
|
+
if (backup !== null) { await renamePath(target, backup); moved = true }
|
|
151
|
+
await renamePath(stage, target)
|
|
152
|
+
placed = true
|
|
153
|
+
return { path: target, status: previous === null ? 'installed' : 'updated',
|
|
154
|
+
previousVersion: previous === null ? null : previous.version, version: context.skillVersion,
|
|
155
|
+
documentationPath: join(target, 'SKILL.md'), backupPath: backup }
|
|
156
|
+
} catch (error) {
|
|
157
|
+
if (moved || placed) await restoreInstallation(target, moved ? backup : null, placed, renamePath)
|
|
158
|
+
throw error
|
|
159
|
+
} finally {
|
|
160
|
+
const remaining = await targetExists(stage)
|
|
161
|
+
if (remaining !== null) await rm(stage, { recursive: true })
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export async function writeManagedSkill(context, target, options = {}) {
|
|
166
|
+
const allowCreate = options.allowCreate === true
|
|
167
|
+
const candidate = await managedTarget(context, target, allowCreate)
|
|
168
|
+
if (candidate.status === 'skipped') return candidate
|
|
169
|
+
assertNoManagedDowngrade(candidate.meta, context)
|
|
170
|
+
if (candidate.meta !== null && candidate.meta.version === context.skillVersion
|
|
171
|
+
&& candidate.meta.packageVersion === context.packageVersion) {
|
|
172
|
+
await verifySkillSource(candidate.path, context)
|
|
173
|
+
return { path: candidate.path, status: 'current', version: context.skillVersion,
|
|
174
|
+
documentationPath: join(candidate.path, 'SKILL.md') }
|
|
175
|
+
}
|
|
176
|
+
await mkdir(dirname(candidate.path), { recursive: true })
|
|
177
|
+
await assertAccountAncestors(dirname(candidate.path))
|
|
178
|
+
const lock = join(dirname(candidate.path), '.' + context.skillName + '.install-lock')
|
|
179
|
+
try { await mkdir(lock, { mode: 0o700 }) } catch (error) {
|
|
180
|
+
if (error.code === 'EEXIST') throw new Error('Skill installation is already locked; inspect its pending update before retrying')
|
|
181
|
+
throw error
|
|
182
|
+
}
|
|
183
|
+
try {
|
|
184
|
+
const checked = await managedTarget(context, candidate.path, allowCreate)
|
|
185
|
+
if (checked.status === 'skipped') throw new Error('Skill installation ownership changed before update')
|
|
186
|
+
assertNoManagedDowngrade(checked.meta, context)
|
|
187
|
+
return await replaceInstallation(context, checked.path, checked.meta, options)
|
|
188
|
+
} finally { await rm(lock, { recursive: true }) }
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export async function refreshManagedSkillCopies(context, dependencies = {}) {
|
|
192
|
+
const environment = dependencies.environment === undefined ? process.env : dependencies.environment
|
|
193
|
+
const home = dependencies.homeDirectory === undefined ? currentAccountHome() : dependencies.homeDirectory
|
|
194
|
+
const workingDirectory = dependencies.workingDirectory === undefined ? process.cwd() : dependencies.workingDirectory
|
|
195
|
+
if (!isAbsolute(home) || !isAbsolute(workingDirectory)) throw new Error('Account and project directories must be absolute')
|
|
196
|
+
const accountCodex = environment.CODEX_HOME === undefined ? join(home, '.codex') : environment.CODEX_HOME
|
|
197
|
+
if (typeof accountCodex !== 'string' || !isAbsolute(accountCodex) || !contained(home, accountCodex)) {
|
|
198
|
+
throw new Error('Automatic skill refresh requires CODEX_HOME inside the current account home')
|
|
199
|
+
}
|
|
200
|
+
const targets = [...new Set([join(workingDirectory, '.codex', 'skills', context.skillName),
|
|
201
|
+
join(accountCodex, 'skills', context.skillName)])]
|
|
202
|
+
const results = []
|
|
203
|
+
for (const target of targets) results.push(await writeManagedSkill(context, target, dependencies))
|
|
204
|
+
return results
|
|
205
|
+
}
|