@viiniolliveira/skillcloud 0.0.0-stage → 0.1.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 +15 -2
- package/dist/index.js +1052 -0
- package/package.json +41 -4
package/README.md
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
-
#
|
|
1
|
+
# SkillCloud CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Sincroniza skills de um servidor SkillCloud com Codex e OpenCode. Requer Node.js 22 ou mais recente.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
bun add --global @viiniolliveira/skillcloud
|
|
7
|
+
skillcloud login --server https://skillcloud.exemplo.com
|
|
8
|
+
skillcloud setup
|
|
9
|
+
skillcloud sync
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Crie um token com `skills:read` nas configurações da sua instância e informe-o no `login`. Use `skillcloud run codex` ou `skillcloud run opencode` para sincronizar antes de iniciar o agente.
|
|
13
|
+
|
|
14
|
+
Se já existir uma pasta local com o mesmo nome, a CLI adota arquivos idênticos sem reescrevê-los. Quando houver diferenças, ela mostra os caminhos afetados e pede confirmação antes de substituir a pasta. Se você aceitar, a pasta original fica em `.skillcloud-backup-<uuid>/<nome-da-skill>` dentro do destino.
|
|
15
|
+
|
|
16
|
+
Use `skillcloud --help` para ver todos os comandos.
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,1052 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { constants } from "node:os";
|
|
5
|
+
import { resolve } from "node:path";
|
|
6
|
+
import { createInterface } from "node:readline/promises";
|
|
7
|
+
import password from "@inquirer/password";
|
|
8
|
+
|
|
9
|
+
// ../../packages/schemas/src/index.ts
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
var IdSchema = z.string().min(1).max(128);
|
|
12
|
+
var HashSchema = z.string().regex(/^[a-f0-9]{64}$/);
|
|
13
|
+
var SkillDescriptionSchema = z.string().trim().min(1).max(1024);
|
|
14
|
+
var ScopeSchema = z.enum(["skills:read", "skills:write"]);
|
|
15
|
+
var windowsDevice = /^(?:con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i;
|
|
16
|
+
var invalidFilenameCharacters = /[<>:"\\|?*]/;
|
|
17
|
+
var SkillNameSchema = z.string().max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).refine((name) => !windowsDevice.test(name), "Nome reservado no Windows.");
|
|
18
|
+
var SkillPathSchema = z.string().min(1).max(1024).refine((path) => {
|
|
19
|
+
const parts = path.split("/");
|
|
20
|
+
return parts.length <= 32 && parts.every((part) => part.length > 0 && part.length <= 255 && !/[. ]$/.test(part) && !invalidFilenameCharacters.test(part) && ![...part].some((character) => character.charCodeAt(0) < 32) && !windowsDevice.test(part));
|
|
21
|
+
}, { message: "Use um caminho relativo válido em Windows, macOS e Linux." });
|
|
22
|
+
var folderId = IdSchema.nullable();
|
|
23
|
+
var versionId = IdSchema;
|
|
24
|
+
var folderName = z.string().trim().min(1).max(128);
|
|
25
|
+
var fileFields = {
|
|
26
|
+
path: SkillPathSchema,
|
|
27
|
+
executable: z.boolean().optional(),
|
|
28
|
+
mimeType: z.string().min(1).max(255).nullable().optional()
|
|
29
|
+
};
|
|
30
|
+
var fileContents = [
|
|
31
|
+
{ content: z.string(), contentBase64: z.never().optional() },
|
|
32
|
+
{ content: z.never().optional(), contentBase64: z.base64() }
|
|
33
|
+
];
|
|
34
|
+
var InputFileSchema = z.union([
|
|
35
|
+
z.object({ ...fileFields, ...fileContents[0] }),
|
|
36
|
+
z.object({ ...fileFields, ...fileContents[1] })
|
|
37
|
+
]);
|
|
38
|
+
var CreateSkillSchema = z.object({
|
|
39
|
+
name: SkillNameSchema,
|
|
40
|
+
description: SkillDescriptionSchema,
|
|
41
|
+
folderId: folderId.optional(),
|
|
42
|
+
files: z.array(InputFileSchema).optional()
|
|
43
|
+
});
|
|
44
|
+
var OperationSchema = z.union([
|
|
45
|
+
z.object({ type: z.literal("put"), ...fileFields, ...fileContents[0] }),
|
|
46
|
+
z.object({ type: z.literal("put"), ...fileFields, ...fileContents[1] }),
|
|
47
|
+
z.object({ type: z.literal("delete"), path: SkillPathSchema }),
|
|
48
|
+
z.object({ type: z.literal("rename"), path: SkillPathSchema, to: SkillPathSchema })
|
|
49
|
+
]);
|
|
50
|
+
var CommitSchema = z.object({
|
|
51
|
+
baseVersionId: versionId,
|
|
52
|
+
changeNote: z.string().trim().max(500).nullable().optional(),
|
|
53
|
+
operations: z.array(OperationSchema).min(1).max(1000)
|
|
54
|
+
});
|
|
55
|
+
var RestoreSchema = z.object({ baseVersionId: versionId, versionId });
|
|
56
|
+
var CreateFolderSchema = z.object({ name: folderName, parentId: folderId.optional() });
|
|
57
|
+
var UpdateFolderSchema = CreateFolderSchema.partial();
|
|
58
|
+
var MoveSkillSchema = z.object({ folderId });
|
|
59
|
+
var CreateKeySchema = z.object({
|
|
60
|
+
name: z.string().trim().min(1).max(128),
|
|
61
|
+
scopes: z.array(ScopeSchema).min(1).max(2).refine((scopes) => new Set(scopes).size === scopes.length),
|
|
62
|
+
expiresAt: z.iso.datetime({ offset: true }).nullable().optional()
|
|
63
|
+
});
|
|
64
|
+
var ListSkillsSchema = z.object({
|
|
65
|
+
query: z.string().trim().max(300).optional(),
|
|
66
|
+
folderId: folderId.optional(),
|
|
67
|
+
page: z.coerce.number().int().min(1).max(1e6).optional(),
|
|
68
|
+
pageSize: z.coerce.number().int().min(1).max(100).optional(),
|
|
69
|
+
sort: z.enum(["newest", "name"]).optional()
|
|
70
|
+
});
|
|
71
|
+
var DiffSchema = z.object({ from: versionId, to: versionId });
|
|
72
|
+
var GithubImportSchema = z.object({
|
|
73
|
+
repository: z.string().trim().min(1).max(500),
|
|
74
|
+
ref: z.string().trim().max(255).optional(),
|
|
75
|
+
path: z.union([SkillPathSchema, z.literal("")]).optional()
|
|
76
|
+
});
|
|
77
|
+
var ImportConfirmSchema = z.object({ previewId: IdSchema, folderId: folderId.optional() });
|
|
78
|
+
var ManifestFileSchema = z.object({
|
|
79
|
+
path: SkillPathSchema,
|
|
80
|
+
hash: HashSchema,
|
|
81
|
+
size: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
|
82
|
+
executable: z.boolean()
|
|
83
|
+
});
|
|
84
|
+
var SyncManifestSchema = z.object({
|
|
85
|
+
schemaVersion: z.literal(1),
|
|
86
|
+
skills: z.array(z.object({
|
|
87
|
+
id: IdSchema,
|
|
88
|
+
name: SkillNameSchema,
|
|
89
|
+
version: z.number().int().positive(),
|
|
90
|
+
versionId,
|
|
91
|
+
manifestHash: HashSchema,
|
|
92
|
+
files: z.array(ManifestFileSchema)
|
|
93
|
+
}))
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
// ../../packages/sdk/src/index.ts
|
|
97
|
+
class ServerUnavailable extends Error {
|
|
98
|
+
}
|
|
99
|
+
function serverOrigin(value) {
|
|
100
|
+
const url = new URL(value.trim());
|
|
101
|
+
const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
102
|
+
if (url.protocol !== "https:" && !(loopback && url.protocol === "http:") || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
|
|
103
|
+
throw new Error("Informe a origem HTTPS do SkillCloud (HTTP permitido apenas localmente).");
|
|
104
|
+
}
|
|
105
|
+
return url.origin;
|
|
106
|
+
}
|
|
107
|
+
function createSkillCloudClient(server, token, timeout = 5000) {
|
|
108
|
+
const origin = serverOrigin(server);
|
|
109
|
+
async function request(path, headers) {
|
|
110
|
+
const requestHeaders = new Headers(headers);
|
|
111
|
+
requestHeaders.set("Authorization", `Bearer ${token}`);
|
|
112
|
+
let response;
|
|
113
|
+
try {
|
|
114
|
+
response = await fetch(`${origin}${path}`, {
|
|
115
|
+
headers: requestHeaders,
|
|
116
|
+
redirect: "error",
|
|
117
|
+
signal: AbortSignal.timeout(timeout)
|
|
118
|
+
});
|
|
119
|
+
} catch (error) {
|
|
120
|
+
throw new ServerUnavailable("Servidor indisponível ou tempo limite atingido.", {
|
|
121
|
+
cause: error
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
if (response.status >= 500 || response.status === 429) {
|
|
125
|
+
await response.body?.cancel();
|
|
126
|
+
throw new ServerUnavailable(`Servidor indisponível (HTTP ${response.status}).`);
|
|
127
|
+
}
|
|
128
|
+
if (response.status === 401 || response.status === 403) {
|
|
129
|
+
await response.body?.cancel();
|
|
130
|
+
throw new Error("Token revogado, inválido ou sem escopo de leitura. Execute skillcloud login.");
|
|
131
|
+
}
|
|
132
|
+
if (!response.ok && response.status !== 304) {
|
|
133
|
+
await response.body?.cancel();
|
|
134
|
+
throw new Error(`Erro na API do SkillCloud (HTTP ${response.status}).`);
|
|
135
|
+
}
|
|
136
|
+
return response;
|
|
137
|
+
}
|
|
138
|
+
async function bytes(response, maxSize) {
|
|
139
|
+
if (!response.body)
|
|
140
|
+
throw new Error("Resposta do SkillCloud sem conteúdo.");
|
|
141
|
+
const reader = response.body.getReader();
|
|
142
|
+
const chunks = [];
|
|
143
|
+
let size = 0;
|
|
144
|
+
try {
|
|
145
|
+
while (true) {
|
|
146
|
+
let chunk;
|
|
147
|
+
try {
|
|
148
|
+
chunk = await reader.read();
|
|
149
|
+
} catch (error) {
|
|
150
|
+
throw new ServerUnavailable("Conexão interrompida durante a transferência.", {
|
|
151
|
+
cause: error
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
if (chunk.done)
|
|
155
|
+
break;
|
|
156
|
+
size += chunk.value.length;
|
|
157
|
+
if (size > maxSize) {
|
|
158
|
+
await reader.cancel();
|
|
159
|
+
throw new Error("Resposta do SkillCloud excede o tamanho esperado.");
|
|
160
|
+
}
|
|
161
|
+
chunks.push(chunk.value);
|
|
162
|
+
}
|
|
163
|
+
} finally {
|
|
164
|
+
reader.releaseLock();
|
|
165
|
+
}
|
|
166
|
+
const output = new Uint8Array(size);
|
|
167
|
+
let offset = 0;
|
|
168
|
+
for (const chunk of chunks) {
|
|
169
|
+
output.set(chunk, offset);
|
|
170
|
+
offset += chunk.length;
|
|
171
|
+
}
|
|
172
|
+
return output;
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
async manifest(etag) {
|
|
176
|
+
const response = await request("/api/sync/manifest", etag ? { "If-None-Match": etag } : undefined);
|
|
177
|
+
if (response.status === 304)
|
|
178
|
+
return null;
|
|
179
|
+
const content = await bytes(response, 64 * 1024 * 1024);
|
|
180
|
+
return {
|
|
181
|
+
manifest: SyncManifestSchema.parse(JSON.parse(new TextDecoder().decode(content))),
|
|
182
|
+
etag: response.headers.get("etag") ?? undefined
|
|
183
|
+
};
|
|
184
|
+
},
|
|
185
|
+
async download(hash, size) {
|
|
186
|
+
return bytes(await request(`/api/storage/${hash}`), size);
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// src/index.ts
|
|
192
|
+
import { Command } from "commander";
|
|
193
|
+
|
|
194
|
+
// src/adapters/agents.ts
|
|
195
|
+
import { writeFile as writeFile2 } from "node:fs/promises";
|
|
196
|
+
import { homedir as homedir2 } from "node:os";
|
|
197
|
+
import { join as join2 } from "node:path";
|
|
198
|
+
import TOML from "@iarna/toml";
|
|
199
|
+
import spawn from "cross-spawn";
|
|
200
|
+
import { applyEdits, modify, parse } from "jsonc-parser";
|
|
201
|
+
import { z as z3 } from "zod";
|
|
202
|
+
|
|
203
|
+
// src/state.ts
|
|
204
|
+
import { randomUUID } from "node:crypto";
|
|
205
|
+
import { lstat, mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
|
|
206
|
+
import { homedir } from "node:os";
|
|
207
|
+
import { dirname, isAbsolute, join } from "node:path";
|
|
208
|
+
import lockfile from "proper-lockfile";
|
|
209
|
+
import { z as z2 } from "zod";
|
|
210
|
+
var stateDirectory = process.env.SKILLCLOUD_HOME || join(homedir(), ".skillcloud");
|
|
211
|
+
var AgentSchema = z2.enum(["codex", "opencode"]);
|
|
212
|
+
var ConfigSchema = z2.object({
|
|
213
|
+
server: z2.string().url().optional(),
|
|
214
|
+
credentials: z2.object({
|
|
215
|
+
id: z2.uuid(),
|
|
216
|
+
backend: z2.enum(["keychain", "file"])
|
|
217
|
+
}).optional(),
|
|
218
|
+
agents: z2.partialRecord(AgentSchema, z2.object({
|
|
219
|
+
destination: z2.string().refine(isAbsolute)
|
|
220
|
+
})).default({})
|
|
221
|
+
});
|
|
222
|
+
function missing(error) {
|
|
223
|
+
return error?.code === "ENOENT";
|
|
224
|
+
}
|
|
225
|
+
async function entry(path) {
|
|
226
|
+
return lstat(path).catch((error) => {
|
|
227
|
+
if (!missing(error))
|
|
228
|
+
throw error;
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
async function readText(path) {
|
|
232
|
+
const item = await entry(path);
|
|
233
|
+
if (!item)
|
|
234
|
+
return;
|
|
235
|
+
if (!item.isFile())
|
|
236
|
+
throw new Error(`Arquivo fora do formato esperado: ${path}`);
|
|
237
|
+
return readFile(path, "utf8");
|
|
238
|
+
}
|
|
239
|
+
async function atomicWrite(path, content) {
|
|
240
|
+
await mkdir(dirname(path), { recursive: true, mode: 448 });
|
|
241
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
242
|
+
try {
|
|
243
|
+
await writeFile(temporary, content, { mode: 384, flag: "wx", flush: true });
|
|
244
|
+
await rename(temporary, path);
|
|
245
|
+
} finally {
|
|
246
|
+
await rm(temporary, { force: true });
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async function readConfig() {
|
|
250
|
+
const contents = await readText(join(stateDirectory, "config.json"));
|
|
251
|
+
return ConfigSchema.parse(contents ? JSON.parse(contents) : {});
|
|
252
|
+
}
|
|
253
|
+
function saveConfig(config) {
|
|
254
|
+
return atomicWrite(join(stateDirectory, "config.json"), `${JSON.stringify(config, null, 2)}
|
|
255
|
+
`);
|
|
256
|
+
}
|
|
257
|
+
async function withConfigLock(operation) {
|
|
258
|
+
await mkdir(stateDirectory, { recursive: true, mode: 448 });
|
|
259
|
+
if (!(await entry(stateDirectory))?.isDirectory()) {
|
|
260
|
+
throw new Error("O diretório do SkillCloud precisa ser uma pasta local, sem link simbólico.");
|
|
261
|
+
}
|
|
262
|
+
const release = await lockfile.lock(stateDirectory);
|
|
263
|
+
try {
|
|
264
|
+
return await operation();
|
|
265
|
+
} finally {
|
|
266
|
+
await release();
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
async function resolveDestination(destination) {
|
|
270
|
+
const info = await entry(destination);
|
|
271
|
+
if (info && !info.isDirectory())
|
|
272
|
+
throw new Error(`Destino não é uma pasta local: ${destination}`);
|
|
273
|
+
await mkdir(destination, { recursive: true });
|
|
274
|
+
return realpath(destination);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// src/adapters/agents.ts
|
|
278
|
+
var openCodeConfig = () => join2(process.env.XDG_CONFIG_HOME || join2(homedir2(), ".config"), "opencode");
|
|
279
|
+
var codexHome = () => process.env.CODEX_HOME || join2(homedir2(), ".codex");
|
|
280
|
+
var tokenVariable = "SKILLCLOUD_MCP_TOKEN";
|
|
281
|
+
var defaultDestination = () => join2(homedir2(), ".agents", "skills");
|
|
282
|
+
var instructionsPath = (agent) => join2(agent === "codex" ? codexHome() : openCodeConfig(), "AGENTS.md");
|
|
283
|
+
var instructions = `## SkillCloud — Skills management
|
|
284
|
+
|
|
285
|
+
SkillCloud is the single source of truth for managed skills.
|
|
286
|
+
Never create, edit, rename or delete managed skills directly on the local filesystem.
|
|
287
|
+
Use the SkillCloud MCP server to create, update, delete or restore managed skills.
|
|
288
|
+
Treat synchronized files as read-only copies.
|
|
289
|
+
If the MCP server is unavailable, do not modify managed skills locally.
|
|
290
|
+
After updating a skill, read its remote version if needed in the current session.`;
|
|
291
|
+
function managedBlock(text, start, end, contents) {
|
|
292
|
+
const lines = text.split(/\r?\n/);
|
|
293
|
+
const starts = lines.flatMap((line, index) => line === start ? [index] : []);
|
|
294
|
+
const ends = lines.flatMap((line, index) => line === end ? [index] : []);
|
|
295
|
+
const newline = text.includes(`\r
|
|
296
|
+
`) ? `\r
|
|
297
|
+
` : `
|
|
298
|
+
`;
|
|
299
|
+
const block = [start, ...contents.split(`
|
|
300
|
+
`), end];
|
|
301
|
+
if (!starts.length && !ends.length) {
|
|
302
|
+
const separator = !text ? "" : text.endsWith(newline) ? newline : newline.repeat(2);
|
|
303
|
+
return `${text}${separator}${block.join(newline)}${newline}`;
|
|
304
|
+
}
|
|
305
|
+
if (starts.length !== 1 || ends.length !== 1 || starts[0] >= ends[0]) {
|
|
306
|
+
throw new Error("O bloco delimitado do SkillCloud está incompleto ou duplicado.");
|
|
307
|
+
}
|
|
308
|
+
lines.splice(starts[0], ends[0] - starts[0] + 1, ...block);
|
|
309
|
+
return lines.join(newline);
|
|
310
|
+
}
|
|
311
|
+
async function detectAgent(agent) {
|
|
312
|
+
return new Promise((resolve, reject) => {
|
|
313
|
+
const child = spawn(agent, ["--version"], {
|
|
314
|
+
windowsHide: true,
|
|
315
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
316
|
+
env: { ...process.env, SKILLCLOUD_RUNNING: "1" }
|
|
317
|
+
});
|
|
318
|
+
const timer = setTimeout(() => {
|
|
319
|
+
child.kill();
|
|
320
|
+
reject(new Error(`Tempo limite ao identificar a versão de ${agent}.`));
|
|
321
|
+
}, 5000);
|
|
322
|
+
let stdout = "";
|
|
323
|
+
child.stdout?.on("data", (chunk) => {
|
|
324
|
+
stdout += chunk;
|
|
325
|
+
});
|
|
326
|
+
child.on("error", (error) => {
|
|
327
|
+
clearTimeout(timer);
|
|
328
|
+
if (error.code === "ENOENT")
|
|
329
|
+
resolve(null);
|
|
330
|
+
else
|
|
331
|
+
reject(error);
|
|
332
|
+
});
|
|
333
|
+
child.on("close", (code) => {
|
|
334
|
+
clearTimeout(timer);
|
|
335
|
+
if (code !== 0) {
|
|
336
|
+
reject(new Error(`Não foi possível executar ${agent} --version.`));
|
|
337
|
+
} else {
|
|
338
|
+
resolve(stdout.trim() || agent);
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
var OpenCodeConfigSchema = z3.object({
|
|
344
|
+
mcp: z3.object({ servers: z3.object({ skillcloud: z3.unknown().optional() }).optional() }).optional()
|
|
345
|
+
});
|
|
346
|
+
var ExistingMcpSchema = z3.looseObject({
|
|
347
|
+
headers: z3.record(z3.string(), z3.string()).optional()
|
|
348
|
+
});
|
|
349
|
+
async function mcpConfig(agent, server) {
|
|
350
|
+
const url = `${server}/mcp`;
|
|
351
|
+
if (agent === "codex") {
|
|
352
|
+
const path = join2(codexHome(), "config.toml");
|
|
353
|
+
const previous = await readText(path) ?? "";
|
|
354
|
+
const parsed = TOML.parse(previous);
|
|
355
|
+
const servers = parsed.mcp_servers;
|
|
356
|
+
if (servers && typeof servers === "object" && "skillcloud" in servers && !previous.split(/\r?\n/).includes("# skillcloud:start")) {
|
|
357
|
+
throw new Error(`Já existe um servidor MCP skillcloud em ${path}.`);
|
|
358
|
+
}
|
|
359
|
+
const updated = managedBlock(previous, "# skillcloud:start", "# skillcloud:end", `[mcp_servers.skillcloud]
|
|
360
|
+
url = ${JSON.stringify(url)}
|
|
361
|
+
bearer_token_env_var = "${tokenVariable}"`);
|
|
362
|
+
TOML.parse(updated);
|
|
363
|
+
return { path, previous, updated };
|
|
364
|
+
}
|
|
365
|
+
const jsonc = join2(openCodeConfig(), "opencode.jsonc");
|
|
366
|
+
const json = join2(openCodeConfig(), "opencode.json");
|
|
367
|
+
const jsoncExists = await entry(jsonc);
|
|
368
|
+
if (jsoncExists && await entry(json)) {
|
|
369
|
+
throw new Error("OpenCode tem opencode.json e opencode.jsonc. Mantenha apenas a configuração ativa antes de continuar.");
|
|
370
|
+
}
|
|
371
|
+
const path = jsoncExists ? jsonc : json;
|
|
372
|
+
const previous = await readText(path) ?? `{}
|
|
373
|
+
`;
|
|
374
|
+
const errors = [];
|
|
375
|
+
const parsed = OpenCodeConfigSchema.safeParse(parse(previous, errors, { allowTrailingComma: true }));
|
|
376
|
+
if (errors.length || !parsed.success) {
|
|
377
|
+
throw new Error(`Configuração OpenCode inválida em ${path}.`);
|
|
378
|
+
}
|
|
379
|
+
const existing = parsed.data.mcp?.servers?.skillcloud;
|
|
380
|
+
const mcp = ExistingMcpSchema.safeParse(existing);
|
|
381
|
+
const authorization = `Bearer {env:${tokenVariable}}`;
|
|
382
|
+
if (existing !== undefined && (!mcp.success || mcp.data.headers?.Authorization !== authorization)) {
|
|
383
|
+
throw new Error(`Já existe um servidor MCP skillcloud em ${path}.`);
|
|
384
|
+
}
|
|
385
|
+
const current = mcp.success ? mcp.data : undefined;
|
|
386
|
+
const updated = applyEdits(previous, modify(previous, ["mcp", "servers", "skillcloud"], {
|
|
387
|
+
...current,
|
|
388
|
+
type: "remote",
|
|
389
|
+
url,
|
|
390
|
+
oauth: false,
|
|
391
|
+
headers: { ...current?.headers, Authorization: authorization }
|
|
392
|
+
}, { formattingOptions: { insertSpaces: true, tabSize: 2 } }));
|
|
393
|
+
return { path, previous, updated };
|
|
394
|
+
}
|
|
395
|
+
async function configureAgent(agent, server) {
|
|
396
|
+
const path = instructionsPath(agent);
|
|
397
|
+
const previous = await readText(path) ?? "";
|
|
398
|
+
const updated = managedBlock(previous, "<!-- skillcloud:start -->", "<!-- skillcloud:end -->", instructions);
|
|
399
|
+
const mcp = await mcpConfig(agent, server);
|
|
400
|
+
for (const config of [mcp, { path, previous, updated }]) {
|
|
401
|
+
if (config.updated === config.previous)
|
|
402
|
+
continue;
|
|
403
|
+
if (await entry(config.path)) {
|
|
404
|
+
await writeFile2(`${config.path}.skillcloud.bak`, config.previous, {
|
|
405
|
+
flag: "wx",
|
|
406
|
+
mode: 384
|
|
407
|
+
}).catch((error) => {
|
|
408
|
+
if (error.code !== "EEXIST")
|
|
409
|
+
throw error;
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
await atomicWrite(config.path, config.updated);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
async function runAgent(agent, args, token) {
|
|
416
|
+
const commandArgs = agent === "opencode" && !args.includes("--standalone") ? ["--standalone", ...args] : args;
|
|
417
|
+
return new Promise((resolve, reject) => {
|
|
418
|
+
const child = spawn(agent, commandArgs, {
|
|
419
|
+
stdio: "inherit",
|
|
420
|
+
env: { ...process.env, SKILLCLOUD_RUNNING: "1", [tokenVariable]: token }
|
|
421
|
+
});
|
|
422
|
+
const terminate = () => {
|
|
423
|
+
child.kill("SIGTERM");
|
|
424
|
+
};
|
|
425
|
+
const interrupt = () => {
|
|
426
|
+
if (!process.stdin.isTTY)
|
|
427
|
+
child.kill("SIGINT");
|
|
428
|
+
};
|
|
429
|
+
const cleanup = () => {
|
|
430
|
+
process.off("SIGTERM", terminate);
|
|
431
|
+
process.off("SIGINT", interrupt);
|
|
432
|
+
};
|
|
433
|
+
process.on("SIGTERM", terminate);
|
|
434
|
+
process.on("SIGINT", interrupt);
|
|
435
|
+
child.once("error", (error) => {
|
|
436
|
+
cleanup();
|
|
437
|
+
reject(error);
|
|
438
|
+
});
|
|
439
|
+
child.once("exit", (code, signal) => {
|
|
440
|
+
cleanup();
|
|
441
|
+
resolve({ code, signal });
|
|
442
|
+
});
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// src/auth/credentials.ts
|
|
447
|
+
import { execFile } from "node:child_process";
|
|
448
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
449
|
+
import { chmod, mkdir as mkdir2, rm as rm2 } from "node:fs/promises";
|
|
450
|
+
import { join as join3 } from "node:path";
|
|
451
|
+
import { promisify } from "node:util";
|
|
452
|
+
var exec = promisify(execFile);
|
|
453
|
+
async function keychain(id) {
|
|
454
|
+
const { Entry } = await import("@napi-rs/keyring");
|
|
455
|
+
return new Entry("SkillCloud", id, { linux: { store: "secret-service" } });
|
|
456
|
+
}
|
|
457
|
+
async function storeToken(token) {
|
|
458
|
+
const id = randomUUID2();
|
|
459
|
+
try {
|
|
460
|
+
const item = await keychain(id);
|
|
461
|
+
item.setPassword(token);
|
|
462
|
+
return { id, backend: "keychain" };
|
|
463
|
+
} catch {
|
|
464
|
+
console.warn("Chaveiro do sistema indisponível. A credencial será salva em um arquivo privado.");
|
|
465
|
+
const directory = join3(stateDirectory, "credentials");
|
|
466
|
+
await mkdir2(directory, { recursive: true, mode: 448 });
|
|
467
|
+
if (!(await entry(directory))?.isDirectory()) {
|
|
468
|
+
throw new Error("O diretório de credenciais deve ser uma pasta local.");
|
|
469
|
+
}
|
|
470
|
+
if (process.platform === "win32") {
|
|
471
|
+
const { stdout } = await exec("whoami.exe", ["/user", "/fo", "csv", "/nh"], {
|
|
472
|
+
windowsHide: true
|
|
473
|
+
});
|
|
474
|
+
const sid = stdout.match(/"(S-\d+(?:-\d+)+)"/)?.[1];
|
|
475
|
+
if (!sid)
|
|
476
|
+
throw new Error("Não foi possível identificar o usuário do Windows para restringir a credencial.");
|
|
477
|
+
await exec("icacls.exe", [directory, "/inheritance:r", "/grant:r", `*${sid}:(OI)(CI)F`], {
|
|
478
|
+
windowsHide: true
|
|
479
|
+
});
|
|
480
|
+
} else {
|
|
481
|
+
await chmod(directory, 448);
|
|
482
|
+
}
|
|
483
|
+
await atomicWrite(join3(directory, id), token);
|
|
484
|
+
return { id, backend: "file" };
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
async function loadToken(config) {
|
|
488
|
+
const credential = config.credentials;
|
|
489
|
+
if (!config.server || !credential)
|
|
490
|
+
throw new Error("Entre primeiro com skillcloud login.");
|
|
491
|
+
const token = credential.backend === "keychain" ? (await keychain(credential.id)).getPassword() : await readText(join3(stateDirectory, "credentials", credential.id));
|
|
492
|
+
if (!token)
|
|
493
|
+
throw new Error("Credencial não encontrada. Execute skillcloud login novamente.");
|
|
494
|
+
return token;
|
|
495
|
+
}
|
|
496
|
+
async function removeToken(credential) {
|
|
497
|
+
if (credential.backend === "keychain") {
|
|
498
|
+
const item = await keychain(credential.id);
|
|
499
|
+
if (item.getPassword())
|
|
500
|
+
item.deletePassword();
|
|
501
|
+
} else {
|
|
502
|
+
await rm2(join3(stateDirectory, "credentials", credential.id), { force: true });
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// src/sync/install.ts
|
|
507
|
+
import { createHash, randomUUID as randomUUID3 } from "node:crypto";
|
|
508
|
+
import { chmod as chmod2, mkdir as mkdir3, readdir, readFile as readFile2, rename as rename2, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
|
|
509
|
+
import { dirname as dirname2, join as join4 } from "node:path";
|
|
510
|
+
import lockfile2 from "proper-lockfile";
|
|
511
|
+
import { z as z4 } from "zod";
|
|
512
|
+
var emptyManifest = { schemaVersion: 1, skills: [] };
|
|
513
|
+
var stateSchema = z4.object({
|
|
514
|
+
server: z4.string(),
|
|
515
|
+
etag: z4.string().optional(),
|
|
516
|
+
manifest: SyncManifestSchema,
|
|
517
|
+
lastSync: z4.iso.datetime(),
|
|
518
|
+
transaction: z4.uuid().optional()
|
|
519
|
+
});
|
|
520
|
+
var journalSchema = z4.object({
|
|
521
|
+
id: z4.uuid(),
|
|
522
|
+
changes: z4.array(z4.object({
|
|
523
|
+
name: SkillNameSchema,
|
|
524
|
+
previous: z4.boolean(),
|
|
525
|
+
install: z4.boolean(),
|
|
526
|
+
keepBackup: z4.boolean().optional()
|
|
527
|
+
}))
|
|
528
|
+
});
|
|
529
|
+
var sha256 = (value) => createHash("sha256").update(value).digest("hex");
|
|
530
|
+
var key = (name) => name.normalize("NFC").toLowerCase();
|
|
531
|
+
var locations = (destination) => {
|
|
532
|
+
const identifier = sha256(process.platform === "win32" ? key(destination) : destination);
|
|
533
|
+
return {
|
|
534
|
+
state: join4(stateDirectory, "manifests", `${identifier}.json`),
|
|
535
|
+
journal: join4(stateDirectory, "manifests", `${identifier}.pending.json`),
|
|
536
|
+
staging: (id) => join4(destination, `.skillcloud-${id}`),
|
|
537
|
+
backup: (id) => join4(destination, `.skillcloud-backup-${id}`)
|
|
538
|
+
};
|
|
539
|
+
};
|
|
540
|
+
function validateManifest(manifest) {
|
|
541
|
+
const names = new Set;
|
|
542
|
+
const ids = new Set;
|
|
543
|
+
for (const skill of manifest.skills) {
|
|
544
|
+
if (ids.has(skill.id) || names.has(key(skill.name)))
|
|
545
|
+
throw new Error("O manifesto contém skills duplicadas.");
|
|
546
|
+
ids.add(skill.id);
|
|
547
|
+
names.add(key(skill.name));
|
|
548
|
+
const paths = new Map;
|
|
549
|
+
for (const file of skill.files) {
|
|
550
|
+
const parts = file.path.split("/");
|
|
551
|
+
for (let length = 1;length <= parts.length; length++) {
|
|
552
|
+
const path = parts.slice(0, length).join("/");
|
|
553
|
+
const isFile = length === parts.length;
|
|
554
|
+
const existing = paths.get(key(path));
|
|
555
|
+
if (existing && (existing.path !== path || existing.isFile || isFile)) {
|
|
556
|
+
throw new Error(`O manifesto contém caminhos incompatíveis: ${skill.name}/${path}`);
|
|
557
|
+
}
|
|
558
|
+
paths.set(key(path), { path, isFile });
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
if (!skill.files.some((file) => file.path === "SKILL.md")) {
|
|
562
|
+
throw new Error(`O manifesto não inclui SKILL.md para ${skill.name}.`);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
async function inspect(destination, skill, previewAdoption = false) {
|
|
567
|
+
const directory = join4(destination, skill.name);
|
|
568
|
+
const known = new Map(skill.files.map((file) => [file.path, file]));
|
|
569
|
+
const folders = new Set;
|
|
570
|
+
for (const path of known.keys()) {
|
|
571
|
+
for (let parent = dirname2(path).replaceAll("\\", "/");parent !== "."; parent = dirname2(parent).replaceAll("\\", "/")) {
|
|
572
|
+
folders.add(parent);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
const reusable = new Map;
|
|
576
|
+
const missing = new Set(known.keys());
|
|
577
|
+
const changes = [];
|
|
578
|
+
let collision;
|
|
579
|
+
async function visit(relative = "") {
|
|
580
|
+
const path = join4(directory, relative);
|
|
581
|
+
const item = await entry(path);
|
|
582
|
+
if (!item)
|
|
583
|
+
return;
|
|
584
|
+
if (item.isDirectory() && (!relative || folders.has(relative) || previewAdoption)) {
|
|
585
|
+
const children = await readdir(path);
|
|
586
|
+
if (previewAdoption && relative && !folders.has(relative)) {
|
|
587
|
+
if (missing.delete(relative))
|
|
588
|
+
changes.push({ path: relative, type: "modified" });
|
|
589
|
+
else if (!children.length)
|
|
590
|
+
changes.push({ path: relative, type: "removed" });
|
|
591
|
+
}
|
|
592
|
+
for (const child of children) {
|
|
593
|
+
await visit(relative ? `${relative}/${child}` : child);
|
|
594
|
+
}
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
const recorded = known.get(relative);
|
|
598
|
+
if (!recorded || !item.isFile()) {
|
|
599
|
+
collision ??= relative ? `${skill.name}/${relative}` : skill.name;
|
|
600
|
+
if (previewAdoption) {
|
|
601
|
+
changes.push({ path: relative, type: missing.delete(relative) ? "modified" : "removed" });
|
|
602
|
+
}
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
missing.delete(relative);
|
|
606
|
+
const sameBytes = item.size === recorded.size && sha256(await readFile2(path)) === recorded.hash;
|
|
607
|
+
if (sameBytes)
|
|
608
|
+
reusable.set(recorded.hash, path);
|
|
609
|
+
const executable = (item.mode & 73) !== 0;
|
|
610
|
+
if (!sameBytes || process.platform !== "win32" && executable !== recorded.executable) {
|
|
611
|
+
changes.push({ path: relative, type: "modified" });
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
await visit();
|
|
615
|
+
for (const path of missing)
|
|
616
|
+
changes.push({ path, type: "added" });
|
|
617
|
+
if (previewAdoption)
|
|
618
|
+
changes.sort((a, b) => a.path < b.path ? -1 : Number(a.path > b.path));
|
|
619
|
+
return { clean: !changes.length && !collision, collision, reusable, changes };
|
|
620
|
+
}
|
|
621
|
+
async function recover(destination) {
|
|
622
|
+
const paths = locations(destination);
|
|
623
|
+
const rawState = await readText(paths.state);
|
|
624
|
+
const state = rawState ? stateSchema.parse(JSON.parse(rawState)) : undefined;
|
|
625
|
+
const rawJournal = await readText(paths.journal);
|
|
626
|
+
if (!rawJournal)
|
|
627
|
+
return state;
|
|
628
|
+
const journal = journalSchema.parse(JSON.parse(rawJournal));
|
|
629
|
+
const staging = paths.staging(journal.id);
|
|
630
|
+
const info = await entry(staging);
|
|
631
|
+
if (info && !info.isDirectory())
|
|
632
|
+
throw new Error("A área de recuperação não é uma pasta local.");
|
|
633
|
+
if (state?.transaction !== journal.id) {
|
|
634
|
+
if (!info)
|
|
635
|
+
throw new Error("A área de recuperação da sincronização não foi encontrada.");
|
|
636
|
+
for (const change of journal.changes.toReversed()) {
|
|
637
|
+
const current = join4(destination, change.name);
|
|
638
|
+
const backup = join4(staging, "previous", change.name);
|
|
639
|
+
const candidate = join4(staging, "next", change.name);
|
|
640
|
+
if (!change.previous || await entry(backup)) {
|
|
641
|
+
if (change.install && !await entry(candidate) && await entry(current)) {
|
|
642
|
+
await rename2(current, candidate);
|
|
643
|
+
}
|
|
644
|
+
if (change.previous && await entry(backup))
|
|
645
|
+
await rename2(backup, current);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
} else {
|
|
649
|
+
const backupDirectory = paths.backup(journal.id);
|
|
650
|
+
for (const change of journal.changes) {
|
|
651
|
+
if (!change.keepBackup)
|
|
652
|
+
continue;
|
|
653
|
+
const original = join4(staging, "previous", change.name);
|
|
654
|
+
if (!await entry(original))
|
|
655
|
+
continue;
|
|
656
|
+
const existing = await entry(backupDirectory);
|
|
657
|
+
if (!existing)
|
|
658
|
+
await mkdir3(backupDirectory, { mode: 448 });
|
|
659
|
+
else if (!existing.isDirectory())
|
|
660
|
+
throw new Error(`Destino de backup inválido: ${backupDirectory}.`);
|
|
661
|
+
const backup = join4(backupDirectory, change.name);
|
|
662
|
+
if (await entry(backup))
|
|
663
|
+
throw new Error(`O backup já existe: ${backup}.`);
|
|
664
|
+
await rename2(original, backup);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
await rm3(paths.journal);
|
|
668
|
+
await rm3(staging, { recursive: true, force: true });
|
|
669
|
+
return state;
|
|
670
|
+
}
|
|
671
|
+
async function withDestination(path, operation) {
|
|
672
|
+
const destination = await resolveDestination(path);
|
|
673
|
+
const release = await lockfile2.lock(destination, {
|
|
674
|
+
lockfilePath: join4(destination, ".skillcloud.lock")
|
|
675
|
+
});
|
|
676
|
+
try {
|
|
677
|
+
return await operation(destination);
|
|
678
|
+
} finally {
|
|
679
|
+
await release();
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
async function apply(destination, previous, next, download, confirmAdoption) {
|
|
683
|
+
const paths = locations(destination);
|
|
684
|
+
const installed = new Map(previous.skills.map((skill) => [skill.name, skill]));
|
|
685
|
+
const desired = new Map(next.manifest.skills.map((skill) => [skill.name, skill]));
|
|
686
|
+
const existing = new Map;
|
|
687
|
+
for (const name of await readdir(destination)) {
|
|
688
|
+
const normalized = key(name);
|
|
689
|
+
const matches = existing.get(normalized);
|
|
690
|
+
if (matches)
|
|
691
|
+
matches.push(name);
|
|
692
|
+
else
|
|
693
|
+
existing.set(normalized, [name]);
|
|
694
|
+
}
|
|
695
|
+
const reusable = new Map;
|
|
696
|
+
const changes = [];
|
|
697
|
+
const adopted = [];
|
|
698
|
+
const approved = new Map;
|
|
699
|
+
for (const name of new Set([...installed.keys(), ...desired.keys()])) {
|
|
700
|
+
const old = installed.get(name);
|
|
701
|
+
const skill = desired.get(name);
|
|
702
|
+
const matches = existing.get(key(name)) ?? [];
|
|
703
|
+
const actualName = matches[0];
|
|
704
|
+
if (matches.length > 1 || actualName && actualName !== name) {
|
|
705
|
+
throw new Error(`Nomes de pasta incompatíveis com a skill ${name}: ${matches.join(", ")}.`);
|
|
706
|
+
}
|
|
707
|
+
if (actualName && !old && skill) {
|
|
708
|
+
if (!(await entry(join4(destination, name)))?.isDirectory()) {
|
|
709
|
+
throw new Error(`A entrada ${name} precisa ser uma pasta local, sem link simbólico.`);
|
|
710
|
+
}
|
|
711
|
+
const inspection = await inspect(destination, skill, true);
|
|
712
|
+
for (const [hash, path] of inspection.reusable)
|
|
713
|
+
reusable.set(hash, path);
|
|
714
|
+
if (inspection.clean) {
|
|
715
|
+
adopted.push(skill);
|
|
716
|
+
continue;
|
|
717
|
+
}
|
|
718
|
+
if (!await confirmAdoption?.({ name, changes: inspection.changes })) {
|
|
719
|
+
throw new Error(`Adoção não confirmada para ${name}. O destino não foi alterado.`);
|
|
720
|
+
}
|
|
721
|
+
approved.set(name, { skill, changes: inspection.changes });
|
|
722
|
+
changes.push({ name, previous: true, install: true, keepBackup: true });
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
if (old) {
|
|
726
|
+
const inspection = await inspect(destination, old);
|
|
727
|
+
if (inspection.collision) {
|
|
728
|
+
throw new Error(`Arquivo não gerenciado ou link simbólico em ${inspection.collision}. Mova-o antes da sincronização.`);
|
|
729
|
+
}
|
|
730
|
+
for (const [hash, path] of inspection.reusable)
|
|
731
|
+
reusable.set(hash, path);
|
|
732
|
+
if (skill?.manifestHash === old.manifestHash && inspection.clean)
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
if (actualName || skill)
|
|
736
|
+
changes.push({ name, previous: !!actualName, install: !!skill });
|
|
737
|
+
}
|
|
738
|
+
async function verifyAdoptedSkills() {
|
|
739
|
+
for (const skill of adopted) {
|
|
740
|
+
if (!(await inspect(destination, skill)).clean) {
|
|
741
|
+
throw new Error(`A pasta ${skill.name} mudou durante a sincronização. Tente novamente.`);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (!changes.length) {
|
|
746
|
+
await verifyAdoptedSkills();
|
|
747
|
+
await atomicWrite(paths.state, JSON.stringify(next));
|
|
748
|
+
return { changed: 0, adopted: adopted.length, backups: [] };
|
|
749
|
+
}
|
|
750
|
+
const journal = { id: randomUUID3(), changes };
|
|
751
|
+
const staging = paths.staging(journal.id);
|
|
752
|
+
await mkdir3(staging, { mode: 448 });
|
|
753
|
+
let journalWritten = false;
|
|
754
|
+
try {
|
|
755
|
+
await mkdir3(join4(staging, "previous"));
|
|
756
|
+
await mkdir3(join4(staging, "next"));
|
|
757
|
+
for (const { name } of changes) {
|
|
758
|
+
const skill = desired.get(name);
|
|
759
|
+
if (!skill)
|
|
760
|
+
continue;
|
|
761
|
+
for (const file of skill.files) {
|
|
762
|
+
const installedPath = reusable.get(file.hash);
|
|
763
|
+
let bytes = installedPath && (await entry(installedPath))?.isFile() ? await readFile2(installedPath) : undefined;
|
|
764
|
+
if (!bytes || bytes.length !== file.size || sha256(bytes) !== file.hash) {
|
|
765
|
+
bytes = Buffer.from(await download(file.hash, file.size));
|
|
766
|
+
}
|
|
767
|
+
if (bytes.length !== file.size || sha256(bytes) !== file.hash) {
|
|
768
|
+
throw new Error(`Objeto inválido recebido para ${skill.name}/${file.path}.`);
|
|
769
|
+
}
|
|
770
|
+
const output = join4(staging, "next", skill.name, file.path);
|
|
771
|
+
await mkdir3(dirname2(output), { recursive: true });
|
|
772
|
+
await writeFile3(output, bytes, { flag: "wx", flush: true });
|
|
773
|
+
if (file.executable)
|
|
774
|
+
await chmod2(output, 493);
|
|
775
|
+
reusable.set(file.hash, output);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
await atomicWrite(paths.journal, JSON.stringify(journal));
|
|
779
|
+
journalWritten = true;
|
|
780
|
+
for (const change of changes) {
|
|
781
|
+
const current = join4(destination, change.name);
|
|
782
|
+
if (change.previous) {
|
|
783
|
+
const previousDirectory = join4(staging, "previous");
|
|
784
|
+
const original = join4(previousDirectory, change.name);
|
|
785
|
+
await rename2(current, original);
|
|
786
|
+
const adoption = approved.get(change.name);
|
|
787
|
+
if (adoption) {
|
|
788
|
+
if (!(await entry(original))?.isDirectory()) {
|
|
789
|
+
throw new Error(`A entrada ${change.name} deixou de ser uma pasta local.`);
|
|
790
|
+
}
|
|
791
|
+
const currentPreview = await inspect(previousDirectory, adoption.skill, true);
|
|
792
|
+
if (JSON.stringify(currentPreview.changes) !== JSON.stringify(adoption.changes)) {
|
|
793
|
+
throw new Error(`A pasta ${change.name} mudou durante a sincronização. Tente novamente.`);
|
|
794
|
+
}
|
|
795
|
+
} else {
|
|
796
|
+
const old = installed.get(change.name);
|
|
797
|
+
if (!old)
|
|
798
|
+
throw new Error(`A skill ${change.name} não está no manifesto local.`);
|
|
799
|
+
const inspection = await inspect(previousDirectory, old);
|
|
800
|
+
if (inspection.collision) {
|
|
801
|
+
throw new Error(`A pasta mudou durante a sincronização: ${inspection.collision}.`);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
} else if (await entry(current)) {
|
|
805
|
+
throw new Error(`O destino passou a conter uma skill não gerenciada: ${change.name}.`);
|
|
806
|
+
}
|
|
807
|
+
if (change.install)
|
|
808
|
+
await rename2(join4(staging, "next", change.name), current);
|
|
809
|
+
}
|
|
810
|
+
await verifyAdoptedSkills();
|
|
811
|
+
await atomicWrite(paths.state, JSON.stringify({ ...next, transaction: journal.id }));
|
|
812
|
+
return {
|
|
813
|
+
changed: changes.length,
|
|
814
|
+
adopted: adopted.length,
|
|
815
|
+
backups: changes.filter((change) => change.keepBackup).map((change) => join4(paths.backup(journal.id), change.name))
|
|
816
|
+
};
|
|
817
|
+
} finally {
|
|
818
|
+
if (journalWritten)
|
|
819
|
+
await recover(destination);
|
|
820
|
+
else
|
|
821
|
+
await rm3(staging, { recursive: true, force: true });
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
async function synchronize(destination, server, client, confirmAdoption) {
|
|
825
|
+
return withDestination(destination, async (root) => {
|
|
826
|
+
const state = await recover(root);
|
|
827
|
+
if (state?.manifest.skills.length && state.server !== server) {
|
|
828
|
+
throw new Error("Este destino contém skills de outro servidor. Remova as cópias gerenciadas ou escolha outro destino.");
|
|
829
|
+
}
|
|
830
|
+
const result = await client.manifest(state?.server === server ? state.etag : undefined);
|
|
831
|
+
const manifest = result?.manifest ?? state?.manifest;
|
|
832
|
+
if (!manifest)
|
|
833
|
+
throw new Error("O servidor indicou um manifesto inalterado sem uma cópia local.");
|
|
834
|
+
validateManifest(manifest);
|
|
835
|
+
const outcome = await apply(root, state?.manifest ?? emptyManifest, {
|
|
836
|
+
manifest,
|
|
837
|
+
server,
|
|
838
|
+
etag: result ? result.etag : state?.etag,
|
|
839
|
+
lastSync: new Date().toISOString()
|
|
840
|
+
}, client.download, confirmAdoption);
|
|
841
|
+
return { total: manifest.skills.length, ...outcome };
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
async function localStatus(destination) {
|
|
845
|
+
return withDestination(destination, async (root) => {
|
|
846
|
+
const state = await recover(root);
|
|
847
|
+
const changed = [];
|
|
848
|
+
let validCount = 0;
|
|
849
|
+
for (const skill of state?.manifest.skills ?? []) {
|
|
850
|
+
const result = await inspect(root, skill);
|
|
851
|
+
if (result.clean)
|
|
852
|
+
validCount++;
|
|
853
|
+
else
|
|
854
|
+
changed.push(result.collision ?? skill.name);
|
|
855
|
+
}
|
|
856
|
+
return {
|
|
857
|
+
destination: root,
|
|
858
|
+
changed,
|
|
859
|
+
validCount,
|
|
860
|
+
lastSync: state?.lastSync,
|
|
861
|
+
total: state?.manifest.skills.length ?? 0
|
|
862
|
+
};
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
async function removeManaged(destination) {
|
|
866
|
+
return withDestination(destination, async (root) => {
|
|
867
|
+
const state = await recover(root);
|
|
868
|
+
if (!state)
|
|
869
|
+
return;
|
|
870
|
+
await apply(root, state.manifest, {
|
|
871
|
+
server: state.server,
|
|
872
|
+
manifest: emptyManifest,
|
|
873
|
+
lastSync: new Date().toISOString()
|
|
874
|
+
}, () => {
|
|
875
|
+
throw new Error("Nenhum download é necessário para remover skills.");
|
|
876
|
+
});
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
// src/index.ts
|
|
881
|
+
var program = new Command().name("skillcloud").description("Sincronize suas skills com Codex e OpenCode.").version("0.1.0").enablePositionalOptions();
|
|
882
|
+
async function ask(question) {
|
|
883
|
+
if (!process.stdin.isTTY)
|
|
884
|
+
throw new Error("Use as opções do comando ou execute em um terminal interativo.");
|
|
885
|
+
const terminal = createInterface({ input: process.stdin, output: process.stdout });
|
|
886
|
+
try {
|
|
887
|
+
return (await terminal.question(question)).trim();
|
|
888
|
+
} finally {
|
|
889
|
+
terminal.close();
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
function timeout() {
|
|
893
|
+
const value = Number(process.env.SKILLCLOUD_TIMEOUT_MS ?? 5000);
|
|
894
|
+
if (!Number.isInteger(value) || value < 1 || value > 120000) {
|
|
895
|
+
throw new Error("SKILLCLOUD_TIMEOUT_MS deve estar entre 1 e 120000.");
|
|
896
|
+
}
|
|
897
|
+
return value;
|
|
898
|
+
}
|
|
899
|
+
var destinationFor = (config, agent) => config.agents[agent]?.destination ?? defaultDestination();
|
|
900
|
+
var destinations = (config) => {
|
|
901
|
+
const configured = Object.values(config.agents).map(({ destination }) => destination);
|
|
902
|
+
return new Set(configured.length ? configured : [defaultDestination()]);
|
|
903
|
+
};
|
|
904
|
+
async function sync(destination, config, token) {
|
|
905
|
+
const server = config.server;
|
|
906
|
+
if (!server)
|
|
907
|
+
throw new Error("Entre primeiro com skillcloud login.");
|
|
908
|
+
const { total, changed, adopted, backups } = await synchronize(destination, server, createSkillCloudClient(server, token, timeout()), async ({ name, changes }) => {
|
|
909
|
+
console.log(`A pasta local ${name} em ${destination} difere da versão do servidor:`);
|
|
910
|
+
const labels = { added: "Adicionar", modified: "Alterar", removed: "Remover" };
|
|
911
|
+
for (const { path, type } of changes) {
|
|
912
|
+
console.log(` ${labels[type]}: ${JSON.stringify(path)}`);
|
|
913
|
+
}
|
|
914
|
+
if (!process.stdin.isTTY) {
|
|
915
|
+
console.log("Execute skillcloud sync em um terminal interativo para confirmar a adoção.");
|
|
916
|
+
return false;
|
|
917
|
+
}
|
|
918
|
+
return /^(s|sim|y|yes)$/i.test(await ask("Fazer backup da pasta local e instalar a versão do servidor? [s/N] "));
|
|
919
|
+
});
|
|
920
|
+
console.log(`${total} skill(s) em ${destination}; ${changed} alterada(s).`);
|
|
921
|
+
if (adopted)
|
|
922
|
+
console.log(`${adopted} skill(s) adotada(s) sem reescrever os arquivos.`);
|
|
923
|
+
for (const backup of backups)
|
|
924
|
+
console.log(`Backup da pasta original: ${backup}`);
|
|
925
|
+
}
|
|
926
|
+
program.command("login").description("Conecte-se ao servidor SkillCloud.").option("--server <url>", "Origem HTTPS do SkillCloud").option("--token-stdin", "Leia o token da entrada padrão sem eco").action(async (options) => {
|
|
927
|
+
const server = serverOrigin(options.server ?? await ask("URL do servidor: "));
|
|
928
|
+
let token;
|
|
929
|
+
if (options.tokenStdin) {
|
|
930
|
+
const chunks = [];
|
|
931
|
+
let size = 0;
|
|
932
|
+
for await (const chunk of process.stdin) {
|
|
933
|
+
const bytes = Buffer.from(chunk);
|
|
934
|
+
size += bytes.length;
|
|
935
|
+
if (size > 4096)
|
|
936
|
+
throw new Error("Token inválido.");
|
|
937
|
+
chunks.push(bytes);
|
|
938
|
+
}
|
|
939
|
+
token = Buffer.concat(chunks).toString("utf8").trim();
|
|
940
|
+
} else {
|
|
941
|
+
if (!process.stdin.isTTY)
|
|
942
|
+
throw new Error("Use um terminal interativo ou passe --token-stdin.");
|
|
943
|
+
token = (await password({ message: "Token do SkillCloud", mask: "*" })).trim();
|
|
944
|
+
}
|
|
945
|
+
if (!token || /\s/.test(token))
|
|
946
|
+
throw new Error("Token inválido.");
|
|
947
|
+
await createSkillCloudClient(server, token, timeout()).manifest();
|
|
948
|
+
await withConfigLock(async () => {
|
|
949
|
+
const old = await readConfig();
|
|
950
|
+
const credentials = await storeToken(token);
|
|
951
|
+
try {
|
|
952
|
+
await saveConfig({ ...old, server, credentials });
|
|
953
|
+
} catch (error) {
|
|
954
|
+
await removeToken(credentials);
|
|
955
|
+
throw error;
|
|
956
|
+
}
|
|
957
|
+
if (old.credentials) {
|
|
958
|
+
await removeToken(old.credentials).catch(() => console.warn("Não foi possível remover a credencial anterior."));
|
|
959
|
+
}
|
|
960
|
+
});
|
|
961
|
+
console.log(`Conectado a ${server}.`);
|
|
962
|
+
});
|
|
963
|
+
program.command("setup").description("Configure o destino das skills, o MCP e o AGENTS.md global.").argument("[agent]", "codex ou opencode", (input) => AgentSchema.parse(input)).option("--destination <path>", "Pasta de skills já reconhecida pelo agente").option("--yes", "Autorize as alterações nos arquivos globais exibidos").action(async (agent, options) => {
|
|
964
|
+
const config = await readConfig();
|
|
965
|
+
await loadToken(config);
|
|
966
|
+
const available = await Promise.all((agent ? [agent] : AgentSchema.options).map(async (name) => ({
|
|
967
|
+
name,
|
|
968
|
+
version: await detectAgent(name)
|
|
969
|
+
})));
|
|
970
|
+
const selected = available.filter(({ version }) => version !== null);
|
|
971
|
+
if (!selected.length)
|
|
972
|
+
throw new Error("Nenhum dos agentes selecionados foi encontrado no PATH.");
|
|
973
|
+
for (const { name, version } of selected) {
|
|
974
|
+
const destination = options.destination ? resolve(options.destination) : destinationFor(config, name);
|
|
975
|
+
console.log(`${version}: ${destination}
|
|
976
|
+
MCP global e instruções: ${instructionsPath(name)}`);
|
|
977
|
+
}
|
|
978
|
+
if (!options.yes && !/^(s|sim|y|yes)$/i.test(await ask("Aplicar configuração global? [s/N] ")))
|
|
979
|
+
return;
|
|
980
|
+
await withConfigLock(async () => {
|
|
981
|
+
const latest = await readConfig();
|
|
982
|
+
if (!latest.server || config.server !== latest.server)
|
|
983
|
+
throw new Error("A conexão mudou durante a configuração. Tente novamente.");
|
|
984
|
+
for (const { name } of selected) {
|
|
985
|
+
const current = destinationFor(latest, name);
|
|
986
|
+
const destination = options.destination ? resolve(options.destination) : current;
|
|
987
|
+
if (destination !== current && (await localStatus(current)).total) {
|
|
988
|
+
throw new Error("Remova as cópias gerenciadas do destino anterior antes de mudar o caminho.");
|
|
989
|
+
}
|
|
990
|
+
await configureAgent(name, latest.server);
|
|
991
|
+
latest.agents[name] = { destination };
|
|
992
|
+
await saveConfig(latest);
|
|
993
|
+
}
|
|
994
|
+
});
|
|
995
|
+
console.log("Configuração aplicada. Use skillcloud run para carregar o token MCP e sincronizar.");
|
|
996
|
+
});
|
|
997
|
+
program.command("sync").description("Baixe e aplique as versões atuais.").argument("[agent]", "codex ou opencode", (input) => AgentSchema.parse(input)).action(async (agent) => {
|
|
998
|
+
const config = await readConfig();
|
|
999
|
+
const token = await loadToken(config);
|
|
1000
|
+
for (const destination of agent ? [destinationFor(config, agent)] : destinations(config)) {
|
|
1001
|
+
await sync(destination, config, token);
|
|
1002
|
+
}
|
|
1003
|
+
});
|
|
1004
|
+
program.command("status").description("Mostre as cópias gerenciadas e as divergências locais.").action(async () => {
|
|
1005
|
+
const config = await readConfig();
|
|
1006
|
+
console.log(config.server ? `Servidor: ${config.server}` : "Nenhuma conexão configurada.");
|
|
1007
|
+
for (const destination of destinations(config)) {
|
|
1008
|
+
const status = await localStatus(destination);
|
|
1009
|
+
console.log(`${status.destination}: ${status.total} skill(s); última sincronização: ${status.lastSync ?? "nenhuma"}.`);
|
|
1010
|
+
if (status.changed.length)
|
|
1011
|
+
console.log(`Divergências: ${status.changed.join(", ")}`);
|
|
1012
|
+
}
|
|
1013
|
+
});
|
|
1014
|
+
program.command("run").description("Sincronize e abra o agente. Passe os argumentos dele após o nome.").argument("<agent>", "codex ou opencode", (input) => AgentSchema.parse(input)).argument("[args...]", "Argumentos do agente").passThroughOptions().action(async (agent, args) => {
|
|
1015
|
+
if (process.env.SKILLCLOUD_RUNNING === "1")
|
|
1016
|
+
throw new Error("Chamada recursiva do SkillCloud.");
|
|
1017
|
+
const config = await readConfig();
|
|
1018
|
+
const token = await loadToken(config);
|
|
1019
|
+
const destination = destinationFor(config, agent);
|
|
1020
|
+
if (!await detectAgent(agent))
|
|
1021
|
+
throw new Error(`O executável ${agent} não foi encontrado no PATH.`);
|
|
1022
|
+
try {
|
|
1023
|
+
await sync(destination, config, token);
|
|
1024
|
+
} catch (error) {
|
|
1025
|
+
if (!(error instanceof ServerUnavailable))
|
|
1026
|
+
throw error;
|
|
1027
|
+
const status = await localStatus(destination);
|
|
1028
|
+
if (status.changed.length) {
|
|
1029
|
+
throw new Error("Servidor indisponível e cópias locais divergentes. Não é possível abrir o agente com segurança.");
|
|
1030
|
+
}
|
|
1031
|
+
console.warn(status.validCount ? "Servidor indisponível. Usando a última cópia sincronizada." : "Servidor indisponível. Nenhuma skill foi sincronizada neste destino.");
|
|
1032
|
+
}
|
|
1033
|
+
const result = await runAgent(agent, args, token);
|
|
1034
|
+
process.exitCode = result.code ?? 128 + (result.signal ? constants.signals[result.signal] : 0);
|
|
1035
|
+
});
|
|
1036
|
+
program.command("logout").description("Remova a credencial local.").option("--remove-skills", "Remova também as cópias gerenciadas nos destinos configurados").action(async (options) => {
|
|
1037
|
+
await withConfigLock(async () => {
|
|
1038
|
+
const config = await readConfig();
|
|
1039
|
+
if (options.removeSkills) {
|
|
1040
|
+
for (const destination of destinations(config))
|
|
1041
|
+
await removeManaged(destination);
|
|
1042
|
+
}
|
|
1043
|
+
if (config.credentials)
|
|
1044
|
+
await removeToken(config.credentials);
|
|
1045
|
+
await saveConfig({ agents: config.agents });
|
|
1046
|
+
});
|
|
1047
|
+
console.log("Credencial local removida.");
|
|
1048
|
+
});
|
|
1049
|
+
await program.parseAsync().catch((error) => {
|
|
1050
|
+
console.error(error instanceof Error ? error.message : "O comando não pôde ser concluído.");
|
|
1051
|
+
process.exitCode = 1;
|
|
1052
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@viiniolliveira/skillcloud",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Sincronize skills do SkillCloud com Codex e OpenCode.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/viiniolliveira/skillcloud.git",
|
|
8
|
+
"directory": "apps/cli"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"bin": {
|
|
12
|
+
"skillcloud": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist/index.js"
|
|
16
|
+
],
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=22"
|
|
19
|
+
},
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "bun build src/index.ts --target node --format esm --external @napi-rs/keyring --external @iarna/toml --external @inquirer/password --external commander --external cross-spawn --external jsonc-parser --external proper-lockfile --external zod --outfile dist/index.js",
|
|
22
|
+
"typecheck": "tsc --noEmit"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@iarna/toml": "2.2.5",
|
|
26
|
+
"@inquirer/password": "4.0.23",
|
|
27
|
+
"commander": "14.0.3",
|
|
28
|
+
"cross-spawn": "7.0.6",
|
|
29
|
+
"jsonc-parser": "3.3.1",
|
|
30
|
+
"proper-lockfile": "4.1.2",
|
|
31
|
+
"zod": "4.6.7"
|
|
32
|
+
},
|
|
33
|
+
"optionalDependencies": {
|
|
34
|
+
"@napi-rs/keyring": "2.1.2"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@skillcloud/schemas": "0.1.0",
|
|
38
|
+
"@skillcloud/sdk": "0.1.0",
|
|
39
|
+
"@types/cross-spawn": "6.0.6",
|
|
40
|
+
"@types/node": "22.20.7",
|
|
41
|
+
"@types/proper-lockfile": "4.1.4"
|
|
42
|
+
}
|
|
43
|
+
}
|