@agentsky/sky 3.42.0 → 3.44.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.
@@ -0,0 +1,497 @@
1
+ import {
2
+ MCP_SERVER_NAME,
3
+ withoutSettingsBlock,
4
+ withoutTomlServer
5
+ } from "./chunk-BCSZO4BR.js";
6
+ import {
7
+ ApiError,
8
+ api
9
+ } from "./chunk-W2WEEVIM.js";
10
+ import {
11
+ configPath,
12
+ currentUniverse
13
+ } from "./chunk-XHZJG3QT.js";
14
+
15
+ // src/setup-journal.ts
16
+ import { createHash } from "crypto";
17
+ import { chmodSync, existsSync as existsSync2, lstatSync, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmdirSync, rmSync, statSync, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
18
+ import { dirname as dirname2, join as join2, sep } from "path";
19
+
20
+ // src/shell-env.ts
21
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
22
+ import { homedir } from "os";
23
+ import { basename, dirname, join } from "path";
24
+ var TOKEN_ENV = "AGENTSKY_API_KEY";
25
+ var SHELL_HOOK_MARK = "# AgentSky API token, kept current by sky";
26
+ function shellEnvFiles() {
27
+ const dir = dirname(configPath());
28
+ return { sh: join(dir, "env.sh"), fish: join(dir, "env.fish") };
29
+ }
30
+ function quoted(value) {
31
+ return `'${value.replace(/'/g, `'\\''`)}'`;
32
+ }
33
+ function shellStartupFiles(env = process.env, home = homedir(), platform = process.platform) {
34
+ const shell = basename(env.SHELL ?? "");
35
+ const files = [];
36
+ const zshenv = join(env.ZDOTDIR || home, ".zshenv");
37
+ if (shell === "zsh" || platform === "darwin" || existsSync(zshenv)) files.push({ path: zshenv, kind: "sh" });
38
+ const bashrc = join(home, ".bashrc");
39
+ if (shell === "bash" || existsSync(bashrc)) files.push({ path: bashrc, kind: "sh" });
40
+ const bashProfile = join(home, ".bash_profile");
41
+ if (existsSync(bashProfile)) files.push({ path: bashProfile, kind: "sh" });
42
+ const fish = join(env.XDG_CONFIG_HOME || join(home, ".config"), "fish");
43
+ if (shell === "fish" || existsSync(fish)) files.push({ path: join(fish, "conf.d", "agentsky.fish"), kind: "fish" });
44
+ return files;
45
+ }
46
+ function writeShellEnv(token, opts = {}) {
47
+ const { sh, fish } = shellEnvFiles();
48
+ const startup = shellStartupFiles(opts.env, opts.home, opts.platform);
49
+ if (opts.dryRun) return { outcome: "planned", files: [sh, fish, ...startup.map((file) => file.path)] };
50
+ const header = "# Written by sky. `sky auth login` and `sky auth logout` rewrite this file.\n";
51
+ const hooked = [];
52
+ try {
53
+ mkdirSync(dirname(sh), { recursive: true });
54
+ writeFileSync(sh, `${header}${token ? `export ${TOKEN_ENV}=${quoted(token)}` : `unset ${TOKEN_ENV}`}
55
+ `, { mode: 384 });
56
+ writeFileSync(fish, `${header}${token ? `set -gx ${TOKEN_ENV} ${quoted(token)}` : `set -e ${TOKEN_ENV}`}
57
+ `, { mode: 384 });
58
+ for (const file of startup) {
59
+ const existing = existsSync(file.path) ? readFileSync(file.path, "utf8") : "";
60
+ if (existing.includes(SHELL_HOOK_MARK)) continue;
61
+ const line = file.kind === "fish" ? `${SHELL_HOOK_MARK}
62
+ test -f ${quoted(fish)}; and source ${quoted(fish)}
63
+ ` : `${SHELL_HOOK_MARK}
64
+ [ -f ${quoted(sh)} ] && . ${quoted(sh)}
65
+ `;
66
+ mkdirSync(dirname(file.path), { recursive: true });
67
+ appendFileSync(file.path, `${existing && !existing.endsWith("\n") ? "\n" : ""}${line}`);
68
+ hooked.push(file.path);
69
+ }
70
+ } catch (err) {
71
+ return { outcome: "failed", files: [sh, fish, ...hooked], detail: String(err) };
72
+ }
73
+ return { outcome: token ? "written" : "cleared", files: [sh, fish, ...hooked] };
74
+ }
75
+
76
+ // src/setup-journal.ts
77
+ var sha = (bytes) => bytes ? createHash("sha256").update(bytes).digest("hex") : null;
78
+ function readBytes(path) {
79
+ try {
80
+ return readFileSync2(path);
81
+ } catch {
82
+ return null;
83
+ }
84
+ }
85
+ function journalPath() {
86
+ return join2(dirname2(configPath()), "setup-journal.json");
87
+ }
88
+ var SetupJournal = class {
89
+ constructor(path = journalPath()) {
90
+ this.path = path;
91
+ let loaded = {};
92
+ try {
93
+ loaded = JSON.parse(readFileSync2(path, "utf8"));
94
+ } catch {
95
+ loaded = {};
96
+ }
97
+ this.data = { version: 1, files: loaded.files ?? {}, owned: loaded.owned ?? [], dirs: loaded.dirs ?? [], jobs: loaded.jobs ?? [] };
98
+ }
99
+ path;
100
+ data;
101
+ touched = /* @__PURE__ */ new Set();
102
+ /** Whether this machine has anything setup could remove. */
103
+ get empty() {
104
+ return !Object.keys(this.data.files).length && !this.data.owned.length && !this.data.dirs.length && !this.data.jobs.length;
105
+ }
106
+ createdDirs(path) {
107
+ const missing = [];
108
+ for (let dir = dirname2(path); !existsSync2(dir) && dirname2(dir) !== dir; dir = dirname2(dir)) missing.push(dir);
109
+ for (const dir of missing.reverse()) if (!this.data.dirs.includes(dir)) this.data.dirs.push(dir);
110
+ }
111
+ /** Call before setup writes `path`: keeps its bytes the first time, and notes the entries setup puts in it. */
112
+ track(path, entries = []) {
113
+ if (this.owns(path)) return;
114
+ const record = this.data.files[path];
115
+ const current = readBytes(path);
116
+ if (!record) {
117
+ this.createdDirs(path);
118
+ let mode = null;
119
+ try {
120
+ mode = statSync(path).mode & 4095;
121
+ } catch {
122
+ mode = null;
123
+ }
124
+ this.data.files[path] = { original: current ? current.toString("base64") : null, mode, written: sha(current), entries: [...new Set(entries)] };
125
+ } else {
126
+ if (!this.touched.has(path) && sha(current) !== record.written) record.edited = true;
127
+ record.entries = [.../* @__PURE__ */ new Set([...record.entries, ...entries])];
128
+ }
129
+ this.touched.add(path);
130
+ }
131
+ /** Whether setup has written `path` before, so a change to it since is someone else's. */
132
+ tracks(path) {
133
+ return Boolean(this.data.files[path]) || this.owns(path);
134
+ }
135
+ /** Call before setup creates a path it owns outright (its own state, a CLI it installs); one that already existed is left to its owner. */
136
+ own(path) {
137
+ if (existsSync2(path) || this.owns(path) || this.data.files[path]) return;
138
+ this.createdDirs(path);
139
+ this.data.owned.push(path);
140
+ }
141
+ /** Whether `path` is, or lies inside, a path setup owns outright. */
142
+ owns(path) {
143
+ return this.data.owned.some((owned) => path === owned || path.startsWith(`${owned}${sep}`));
144
+ }
145
+ /** A launchd job setup loaded, unloaded first on removal. */
146
+ job(label) {
147
+ if (!this.data.jobs.includes(label)) this.data.jobs.push(label);
148
+ }
149
+ /** After a run: record what setup left in each file it touched, and save. */
150
+ save() {
151
+ for (const path of this.touched) {
152
+ const record = this.data.files[path];
153
+ if (record) record.written = sha(readBytes(path));
154
+ }
155
+ this.touched.clear();
156
+ if (this.empty) {
157
+ rmSync(this.path, { force: true });
158
+ return;
159
+ }
160
+ mkdirSync2(dirname2(this.path), { recursive: true });
161
+ writeFileSync2(this.path, `${JSON.stringify(this.data, null, 2)}
162
+ `, { mode: 384 });
163
+ }
164
+ /**
165
+ * Put back everything setup changed: unload its jobs (with `unload`), restore each file, delete what it owns, remove
166
+ * the directories it created when they are empty, and delete the journal. Returns what was done with each path.
167
+ */
168
+ restore(unload = () => {
169
+ }) {
170
+ const results = [];
171
+ for (const label of this.data.jobs) {
172
+ try {
173
+ unload(label);
174
+ } catch {
175
+ }
176
+ }
177
+ for (const [path, record] of Object.entries(this.data.files)) results.push(restoreFile(path, record));
178
+ for (const path of this.data.owned) {
179
+ if (!existsSync2(path) && !isLink(path)) continue;
180
+ rmSync(path, { recursive: true, force: true });
181
+ results.push({ path, outcome: "removed" });
182
+ }
183
+ rmSync(this.path, { force: true });
184
+ for (const dir of [...this.data.dirs].sort((a, b) => b.length - a.length)) {
185
+ try {
186
+ if (readdirSync(dir).length === 0) {
187
+ rmdirSync(dir);
188
+ results.push({ path: dir, outcome: "removed" });
189
+ }
190
+ } catch {
191
+ }
192
+ }
193
+ this.data = { version: 1, files: {}, owned: [], dirs: [], jobs: [] };
194
+ return results;
195
+ }
196
+ };
197
+ function isLink(path) {
198
+ try {
199
+ return lstatSync(path).isSymbolicLink();
200
+ } catch {
201
+ return false;
202
+ }
203
+ }
204
+ function restoreFile(path, record) {
205
+ const current = readBytes(path);
206
+ const original = record.original === null ? null : Buffer.from(record.original, "base64");
207
+ if (sha(current) === sha(original)) return { path, outcome: "unchanged" };
208
+ if (!record.edited && sha(current) === record.written) {
209
+ if (original === null) {
210
+ unlinkSync(path);
211
+ return { path, outcome: "removed" };
212
+ }
213
+ mkdirSync2(dirname2(path), { recursive: true });
214
+ writeFileSync2(path, original);
215
+ if (record.mode !== null) chmodSync(path, record.mode);
216
+ return { path, outcome: "restored" };
217
+ }
218
+ if (current === null) return { path, outcome: "left", detail: "deleted since setup" };
219
+ const before = original?.toString("utf8") ?? "";
220
+ let text = current.toString("utf8");
221
+ for (const entry of record.entries) {
222
+ const remove = ENTRY_REMOVERS[entry];
223
+ if (original !== null && remove(before) !== before) continue;
224
+ text = remove(text);
225
+ }
226
+ if (text === current.toString("utf8")) return { path, outcome: "left", detail: "changed since setup; nothing of setup's is left in it" };
227
+ writeFileSync2(path, text);
228
+ return { path, outcome: "entries_removed", detail: "changed since setup, so only setup's entries were taken out" };
229
+ }
230
+ var CAPTURE_HOOK_ARGS = ["trace", "sync", "--hook"];
231
+ var isCaptureCommand = (command) => /\btrace\b.*\bsync\b.*--hook\b/.test(command);
232
+ function withoutClaudeHook(text) {
233
+ let settings;
234
+ try {
235
+ settings = JSON.parse(text);
236
+ } catch {
237
+ return text;
238
+ }
239
+ if (!settings || typeof settings !== "object" || !settings.hooks) return text;
240
+ let changed = false;
241
+ for (const [event, groups] of Object.entries(settings.hooks)) {
242
+ if (!Array.isArray(groups)) continue;
243
+ const kept = groups.filter((group) => !group.hooks?.some((hook) => typeof hook.command === "string" && isCaptureCommand(hook.command)));
244
+ if (kept.length === groups.length) continue;
245
+ changed = true;
246
+ if (kept.length) settings.hooks[event] = kept;
247
+ else delete settings.hooks[event];
248
+ }
249
+ if (!changed) return text;
250
+ if (!Object.keys(settings.hooks).length) delete settings.hooks;
251
+ return `${JSON.stringify(settings, null, 2)}
252
+ `;
253
+ }
254
+ var NOTIFY_LINE = /^\s*notify\s*=.*$/;
255
+ function withoutCodexNotify(text) {
256
+ const lines = text.split("\n");
257
+ const at = lines.findIndex((line) => NOTIFY_LINE.test(line) && isCaptureCommand(line.replace(/["',[\]]/g, " ")));
258
+ if (at < 0) return text;
259
+ lines.splice(at, 1);
260
+ return lines.join("\n");
261
+ }
262
+ function withoutJsonServer(text) {
263
+ let config;
264
+ try {
265
+ config = JSON.parse(text);
266
+ } catch {
267
+ return text;
268
+ }
269
+ if (!config?.mcpServers || !(MCP_SERVER_NAME in config.mcpServers)) return text;
270
+ delete config.mcpServers[MCP_SERVER_NAME];
271
+ return `${JSON.stringify(config, null, 2)}
272
+ `;
273
+ }
274
+ function withoutTomlServerText(text) {
275
+ const rest = withoutTomlServer(text, MCP_SERVER_NAME);
276
+ return rest === text.replace(/\n+$/, "") ? text : `${rest}
277
+ `;
278
+ }
279
+ function withoutYamlServer(text) {
280
+ const lines = text.split("\n");
281
+ const parent = lines.findIndex((line) => /^mcp_servers:\s*$/.test(line));
282
+ if (parent < 0) return text;
283
+ const start = lines.findIndex((line, index) => index > parent && new RegExp(`^(\\s+)${MCP_SERVER_NAME}:\\s*`).test(line));
284
+ if (start < 0) return text;
285
+ const indent = /^(\s*)/.exec(lines[start])[1].length;
286
+ let end = start + 1;
287
+ while (end < lines.length && (lines[end].trim() === "" || /^(\s*)/.exec(lines[end])[1].length > indent)) end++;
288
+ lines.splice(start, end - start);
289
+ const rest = lines.slice(parent + 1).some((line) => line.trim() && /^\s/.test(line));
290
+ if (!rest) lines.splice(parent, 1);
291
+ return lines.join("\n").replace(/^\n+/, "");
292
+ }
293
+ function withoutShellLine(text) {
294
+ const lines = text.split("\n");
295
+ const at = lines.indexOf(SHELL_HOOK_MARK);
296
+ if (at < 0) return text;
297
+ lines.splice(at, 2);
298
+ return lines.join("\n");
299
+ }
300
+ function withCaptureOff(text) {
301
+ let config;
302
+ try {
303
+ config = JSON.parse(text);
304
+ } catch {
305
+ return text;
306
+ }
307
+ if (!config?.enabled) return text;
308
+ return `${JSON.stringify({ ...config, enabled: false }, null, 2)}
309
+ `;
310
+ }
311
+ var ENTRY_REMOVERS = {
312
+ claude_hook: withoutClaudeHook,
313
+ codex_notify: withoutCodexNotify,
314
+ mcp_json: withoutJsonServer,
315
+ mcp_toml: withoutTomlServerText,
316
+ mcp_yaml: withoutYamlServer,
317
+ shell_line: withoutShellLine,
318
+ sync_config: withCaptureOff,
319
+ settings_block: withoutSettingsBlock
320
+ };
321
+
322
+ // src/workspace.ts
323
+ import { createInterface } from "readline";
324
+ var KINDS = ["TOOL_CALL", "SPEND_CAP", "CALL_COUNT", "CAPABILITY"];
325
+ async function workspaceSlug(explicit) {
326
+ if (explicit) return explicit;
327
+ const current = currentUniverse();
328
+ if (current) return current;
329
+ return (await api("GET", "/whoami")).universe.slug;
330
+ }
331
+ var workspacePath = (slug) => `/universes/${encodeURIComponent(slug)}`;
332
+ async function listMembers(slug, page = {}) {
333
+ const query = new URLSearchParams({ ...page.limit ? { limit: page.limit } : {}, ...page.cursor ? { cursor: page.cursor } : {} }).toString();
334
+ return api("GET", `${workspacePath(slug)}/members${query ? `?${query}` : ""}`);
335
+ }
336
+ function findMember(members, ref) {
337
+ const needle = ref.toLowerCase();
338
+ const found = members.find((m) => m.user_id === ref || m.email?.toLowerCase() === needle);
339
+ if (!found) throw new ApiError(404, "not_found", `no member ${ref} in this workspace`);
340
+ return found;
341
+ }
342
+ function inviteBody(emails, options) {
343
+ if (options.role && options.role !== "admin" && options.role !== "member") {
344
+ throw new ApiError(400, "invalid_request", "--role is admin or member");
345
+ }
346
+ return {
347
+ emails,
348
+ ...options.role ? { role: options.role } : {},
349
+ ...options.sendEmail ? { send_email: true } : {}
350
+ };
351
+ }
352
+ async function invite(slug, emails, options) {
353
+ return api("POST", `${workspacePath(slug)}/invites`, inviteBody(emails, options));
354
+ }
355
+ async function withdrawInvite(slug, inviteId) {
356
+ await api("DELETE", `${workspacePath(slug)}/invites/${encodeURIComponent(inviteId)}`);
357
+ }
358
+ async function setRole(slug, memberRef, role) {
359
+ if (role !== "admin" && role !== "member") throw new ApiError(400, "invalid_request", "a role is admin or member");
360
+ const member = findMember((await listMembers(slug)).members, memberRef);
361
+ await api("PATCH", `${workspacePath(slug)}/members/${encodeURIComponent(member.user_id)}`, { role });
362
+ return member;
363
+ }
364
+ async function removeMember(slug, memberRef) {
365
+ if (memberRef === "me") {
366
+ await leaveWorkspace(slug);
367
+ return null;
368
+ }
369
+ const member = findMember((await listMembers(slug)).members, memberRef);
370
+ await api("DELETE", `${workspacePath(slug)}/members/${encodeURIComponent(member.user_id)}`);
371
+ return member;
372
+ }
373
+ async function leaveWorkspace(slug) {
374
+ await api("DELETE", `${workspacePath(slug)}/members/me`);
375
+ }
376
+ async function joinWorkspace(token) {
377
+ return (await api("POST", `/invites/${encodeURIComponent(token)}`)).workspace;
378
+ }
379
+ function renderMembers(page) {
380
+ const lines = page.members.map((m) => `${m.role.padEnd(6)} ${m.email ?? m.user_id}${m.name ? ` (${m.name})` : ""} ${m.user_id}`);
381
+ for (const i of page.invites) lines.push(`invited ${i.email} as ${i.role} by ${i.invited_by} until ${i.expires_at.slice(0, 10)} ${i.id}`);
382
+ if (page.next_cursor) lines.push(`more: --cursor ${page.next_cursor}`);
383
+ return lines;
384
+ }
385
+ function policyRuleBody(options) {
386
+ const kind = options.kind.toUpperCase().replace(/-/g, "_");
387
+ if (!KINDS.includes(kind)) throw new ApiError(400, "invalid_request", `--kind is one of ${KINDS.join(", ")}`);
388
+ let config;
389
+ try {
390
+ config = JSON.parse(options.config);
391
+ } catch {
392
+ throw new ApiError(400, "invalid_request", "--config must be a JSON object");
393
+ }
394
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
395
+ throw new ApiError(400, "invalid_request", "--config must be a JSON object");
396
+ }
397
+ const position = options.position === void 0 ? void 0 : Number(options.position);
398
+ if (position !== void 0 && !Number.isInteger(position)) throw new ApiError(400, "invalid_request", "--position is a whole number");
399
+ return {
400
+ name: options.name,
401
+ kind,
402
+ config,
403
+ ...position !== void 0 ? { position } : {},
404
+ ...options.disabled ? { enabled: false } : {}
405
+ };
406
+ }
407
+ var policiesPath = (scope) => "session" in scope ? `/sessions/${encodeURIComponent(scope.session)}/policies` : `${workspacePath(scope.slug)}/policies`;
408
+ async function listPolicies(scope, effective = false) {
409
+ if (effective && "session" in scope) return api("GET", `/sessions/${encodeURIComponent(scope.session)}/effective-policy`);
410
+ return api("GET", policiesPath(scope));
411
+ }
412
+ async function addPolicy(scope, options) {
413
+ return (await api("POST", policiesPath(scope), policyRuleBody(options))).rule;
414
+ }
415
+ async function setPolicyEnabled(scope, ruleId, enabled) {
416
+ return (await api("PATCH", `${policiesPath(scope)}/${encodeURIComponent(ruleId)}`, { enabled })).rule;
417
+ }
418
+ async function removePolicy(scope, ruleId) {
419
+ await api("DELETE", `${policiesPath(scope)}/${encodeURIComponent(ruleId)}`);
420
+ }
421
+ function renderPolicy(rule) {
422
+ const state = rule.enabled ? "on " : "off";
423
+ return `${state} ${rule.layer.padEnd(9)} ${rule.kind.padEnd(10)} ${rule.name} ${JSON.stringify(rule.config)} ${rule.id}`;
424
+ }
425
+ var REMOVED_KINDS = [
426
+ ["sessions", "sessions and their transcripts"],
427
+ ["agents", "agents"],
428
+ ["artifacts", "artifacts"],
429
+ ["files", "task files"],
430
+ ["memory_stores", "memory stores"],
431
+ ["routines", "routines"],
432
+ ["channels", "channel connections"],
433
+ ["webhooks", "webhooks"],
434
+ ["api_keys", "API keys"],
435
+ ["vaults", "vaults"],
436
+ ["skills", "skills"],
437
+ ["environments", "environments"],
438
+ ["connections", "connected apps"],
439
+ ["traces", "uploaded traces"],
440
+ ["members", "other members"],
441
+ ["invites", "pending invitations"]
442
+ ];
443
+ async function deletionPreview(slug) {
444
+ return api("GET", `/universes/${encodeURIComponent(slug)}/deletion`);
445
+ }
446
+ function renderDeletionPreview(preview) {
447
+ if (!preview.can_delete) return [`${preview.workspace.slug} cannot be deleted:`, ...preview.blockers.map((b) => ` ${b.message}`)];
448
+ const lines = [`Deleting ${preview.workspace.slug} (${preview.workspace.name}) permanently removes:`];
449
+ const removed = REMOVED_KINDS.filter(([key]) => (preview.removes[key] ?? 0) > 0);
450
+ for (const [key, label] of removed) lines.push(` ${preview.removes[key]} ${label}`);
451
+ if (!removed.length) lines.push(" nothing: the workspace is empty");
452
+ const running = preview.removes.running_sessions ?? 0;
453
+ if (running) lines.push(`${running} running session${running === 1 ? " is" : "s are"} stopped first.`);
454
+ if (preview.wallet) lines.push(`$${(preview.wallet.balance_micros / 1e6).toFixed(2)} in its wallet goes back to ${preview.wallet.returns_to ?? "you"}.`);
455
+ lines.push("This cannot be undone.");
456
+ return lines;
457
+ }
458
+ async function deleteWorkspace(slug) {
459
+ return (await api("DELETE", `/universes/${encodeURIComponent(slug)}`)).deleted;
460
+ }
461
+ function typedConfirmation(slug) {
462
+ return new Promise((done) => {
463
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
464
+ rl.question(`Type ${slug} to delete it: `, (answer) => {
465
+ rl.close();
466
+ done(answer.trim() === slug);
467
+ });
468
+ });
469
+ }
470
+
471
+ export {
472
+ TOKEN_ENV,
473
+ shellEnvFiles,
474
+ shellStartupFiles,
475
+ writeShellEnv,
476
+ SetupJournal,
477
+ CAPTURE_HOOK_ARGS,
478
+ isCaptureCommand,
479
+ workspaceSlug,
480
+ listMembers,
481
+ invite,
482
+ withdrawInvite,
483
+ setRole,
484
+ removeMember,
485
+ leaveWorkspace,
486
+ joinWorkspace,
487
+ renderMembers,
488
+ listPolicies,
489
+ addPolicy,
490
+ setPolicyEnabled,
491
+ removePolicy,
492
+ renderPolicy,
493
+ deletionPreview,
494
+ renderDeletionPreview,
495
+ deleteWorkspace,
496
+ typedConfirmation
497
+ };