@notis_ai/cli 0.2.0-beta.178.1 → 0.2.0-beta.1792022492092.1
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 +548 -98
- package/config/portal-route-roots.json +47 -0
- package/dist/agent-hooks/notis-agent-hook.mjs +32901 -5934
- package/dist/base-skills/notis-apps/SKILL.md +76 -51
- package/dist/base-skills/notis-apps/references/architecture.md +116 -164
- package/dist/base-skills/notis-apps/references/design.md +26 -107
- package/dist/base-skills/notis-apps/references/memory.md +58 -0
- package/dist/base-skills/notis-apps/references/reading.md +52 -74
- package/dist/base-skills/notis-apps/references/release.md +105 -96
- package/dist/base-skills/notis-apps/references/sdk.md +115 -60
- package/dist/base-skills/notis-apps/references/troubleshooting.md +22 -21
- package/dist/base-skills/notis-apps/references/views.md +145 -0
- package/dist/base-skills/notis-cli/SKILL.md +29 -12
- package/dist/base-skills/notis-cli/references/app-delivery.md +12 -11
- package/dist/base-skills/notis-cli/references/intelligence.md +94 -0
- package/dist/base-skills/notis-cli/references/native-databases.md +6 -5
- package/dist/base-skills/notis-cli/references/tool-examples.md +4 -4
- package/dist/base-skills/notis-query/SKILL.md +34 -60
- package/dist/base-skills/notis-query/references/database-discovery.md +60 -59
- package/dist/base-skills/notis-query/references/documents.md +53 -39
- package/dist/base-skills/notis-query/references/query.md +57 -524
- package/dist/sdk/src/bundleModule.ts +79 -0
- package/dist/sdk/src/components/DocumentEditor.tsx +6 -3
- package/dist/sdk/src/components/DocumentPage.tsx +144 -0
- package/dist/sdk/src/components/RecordComponents.tsx +33 -0
- package/dist/sdk/src/components/RenderChartData.tsx +19 -0
- package/dist/sdk/src/config.ts +4 -26
- package/dist/sdk/src/documents.ts +2 -0
- package/dist/sdk/src/hooks/useAction.ts +28 -0
- package/dist/sdk/src/hooks/useBackend.ts +3 -2
- package/dist/sdk/src/hooks/useCloudComputer.ts +35 -4
- package/dist/sdk/src/hooks/useCloudComputerShell.ts +114 -0
- package/dist/sdk/src/hooks/useCollectionInteractions.ts +4 -2
- package/dist/sdk/src/hooks/useHandover.ts +7 -7
- package/dist/sdk/src/hooks/useNativeDocumentBody.ts +50 -0
- package/dist/sdk/src/hooks/useNativeDocuments.ts +83 -0
- package/dist/sdk/src/hooks/useNotis.ts +3 -0
- package/dist/sdk/src/hooks/useNotisNavigation.ts +26 -11
- package/dist/sdk/src/hooks/useQuery.ts +7 -4
- package/dist/sdk/src/hooks/useViewParams.ts +121 -0
- package/dist/sdk/src/hooks/useViewerReads.ts +129 -0
- package/dist/sdk/src/index.ts +36 -0
- package/dist/sdk/src/interactions/shortcuts.tsx +42 -5
- package/dist/sdk/src/nativeData.ts +39 -0
- package/dist/sdk/src/presentation.tsx +82 -0
- package/dist/sdk/src/provider.tsx +9 -4
- package/dist/sdk/src/queryCache.ts +5 -3
- package/dist/sdk/src/queryErrors.ts +51 -0
- package/dist/sdk/src/runtime.ts +163 -13
- package/dist/sdk/src/space.ts +425 -0
- package/dist/sdk/src/styles.css +96 -72
- package/dist/sdk/src/vite.ts +11 -1
- package/dist/skill-sync/index.js +571 -80
- package/dist/skill-sync/index.js.map +4 -4
- package/dist/skill-sync-worker.mjs +858 -233
- package/dist/space-harness/host.js +66 -0
- package/dist/view-renderer/dist/host.css +1 -0
- package/dist/view-renderer/dist/host.js +1028 -0
- package/dist/view-renderer/dist/theme.css +73 -0
- package/dist/view-renderer/src/dom.js +180 -0
- package/dist/view-renderer/src/errors.js +8 -0
- package/dist/view-renderer/src/host.tsx +175 -0
- package/dist/view-renderer/src/index.js +4 -0
- package/dist/view-renderer/src/pool.js +76 -0
- package/dist/view-renderer/src/remote-broker.js +59 -0
- package/dist/view-renderer/src/renderer.js +201 -0
- package/package.json +16 -5
- package/skills/notis-apps/cli.md +323 -163
- package/skills/notis-cli/AGENT_INSTRUCTIONS.md +3 -3
- package/skills/notis-onboarding/BRIEF.md +7 -3
- package/src/command-specs/apps.js +2 -1
- package/src/command-specs/auth.js +2 -2
- package/src/command-specs/files.js +29 -0
- package/src/command-specs/handover.js +331 -79
- package/src/command-specs/helpers.js +2 -0
- package/src/command-specs/index.js +11 -5
- package/src/command-specs/profile.js +42 -1
- package/src/command-specs/skills.js +242 -1
- package/src/command-specs/spaces.js +645 -0
- package/src/command-specs/tools.js +0 -6
- package/src/command-specs/views.js +69 -0
- package/src/runtime/agent-browser.js +92 -29
- package/src/runtime/app-boundary-validator.js +7 -4
- package/src/runtime/app-data-literals.js +82 -0
- package/src/runtime/app-platform.js +321 -253
- package/src/runtime/computer-identity.d.ts +30 -0
- package/src/runtime/computer-identity.js +151 -0
- package/src/runtime/config-lock.js +135 -0
- package/src/runtime/confined-space-build.js +74 -0
- package/src/runtime/confined-space-verify.js +49 -0
- package/src/runtime/delegated-context.js +5 -21
- package/src/runtime/native-record-files.js +47 -0
- package/src/runtime/oauth.js +18 -1
- package/src/runtime/profiles.js +5 -107
- package/src/runtime/retired-sdk-files.js +20 -0
- package/src/runtime/screenshot-framing.js +85 -0
- package/src/runtime/skill-sync/cloud-client.ts +26 -4
- package/src/runtime/skill-sync/index.ts +230 -35
- package/src/runtime/skill-sync/local-scanner.ts +188 -29
- package/src/runtime/skill-sync/native-identity.ts +102 -0
- package/src/runtime/skill-sync/native-plan.ts +70 -0
- package/src/runtime/skill-sync/sync-plan.ts +16 -9
- package/src/runtime/skill-sync/types.ts +32 -6
- package/src/runtime/source-root.js +32 -0
- package/src/runtime/space-collection-scaffold.js +66 -0
- package/src/runtime/space-database-structures.js +229 -0
- package/src/runtime/space-fixture-broker.js +50 -0
- package/src/runtime/space-lock.js +337 -0
- package/src/runtime/space-platform.js +105 -0
- package/src/runtime/space-source.js +281 -0
- package/src/runtime/space-test-server.js +327 -0
- package/src/runtime/space-verification.js +89 -0
- package/src/runtime/space-verify-browser-worker.js +51 -0
- package/src/runtime/space-view-manifest.js +254 -0
- package/src/runtime/store-screenshot.js +10 -7
- package/src/runtime/sync-skills.d.ts +3 -1
- package/src/runtime/sync-skills.js +10 -2
- package/src/runtime/transport.js +8 -6
- package/src/runtime/view-render.js +49 -0
- package/src/skill-sync-worker.js +14 -2
- package/src/space-harness-host.ts +103 -0
- package/template/.harness/index.html.tmpl +7 -10
- package/template/app/globals.css +1 -0
- package/src/command-specs/reports.js +0 -97
|
@@ -1,21 +1,18 @@
|
|
|
1
1
|
// src/skill-sync-worker.js
|
|
2
|
-
import { mkdirSync as
|
|
3
|
-
import { homedir as
|
|
4
|
-
import { join as
|
|
2
|
+
import { mkdirSync as mkdirSync5, renameSync as renameSync5, writeFileSync as writeFileSync5 } from "node:fs";
|
|
3
|
+
import { homedir as homedir5 } from "node:os";
|
|
4
|
+
import { join as join8 } from "node:path";
|
|
5
5
|
|
|
6
6
|
// src/runtime/profiles.js
|
|
7
|
-
import { randomUUID } from "node:crypto";
|
|
8
7
|
import {
|
|
9
|
-
existsSync,
|
|
10
|
-
mkdirSync,
|
|
11
|
-
readFileSync,
|
|
12
|
-
renameSync,
|
|
13
|
-
|
|
14
|
-
statSync,
|
|
15
|
-
writeFileSync
|
|
8
|
+
existsSync as existsSync2,
|
|
9
|
+
mkdirSync as mkdirSync2,
|
|
10
|
+
readFileSync as readFileSync2,
|
|
11
|
+
renameSync as renameSync2,
|
|
12
|
+
writeFileSync as writeFileSync2
|
|
16
13
|
} from "node:fs";
|
|
17
|
-
import { homedir } from "node:os";
|
|
18
|
-
import { dirname, join, parse, resolve } from "node:path";
|
|
14
|
+
import { homedir as homedir2 } from "node:os";
|
|
15
|
+
import { dirname as dirname2, join as join2, parse, resolve as resolve2 } from "node:path";
|
|
19
16
|
|
|
20
17
|
// src/runtime/errors.js
|
|
21
18
|
var EXIT_CODES = {
|
|
@@ -51,6 +48,109 @@ var CliError = class extends Error {
|
|
|
51
48
|
}
|
|
52
49
|
};
|
|
53
50
|
|
|
51
|
+
// src/runtime/config-lock.js
|
|
52
|
+
import { randomUUID } from "node:crypto";
|
|
53
|
+
import {
|
|
54
|
+
existsSync,
|
|
55
|
+
mkdirSync,
|
|
56
|
+
readFileSync,
|
|
57
|
+
renameSync,
|
|
58
|
+
rmSync,
|
|
59
|
+
statSync,
|
|
60
|
+
writeFileSync
|
|
61
|
+
} from "node:fs";
|
|
62
|
+
import { homedir } from "node:os";
|
|
63
|
+
import { dirname, join, resolve } from "node:path";
|
|
64
|
+
var CONFIG_WRITE_LOCK_TIMEOUT_MS = 5e3;
|
|
65
|
+
var CONFIG_WRITE_LOCK_STALE_MS = 2e3;
|
|
66
|
+
var CONFIG_WRITE_LOCK_POLL_MS = 10;
|
|
67
|
+
function resolveCliConfigFile() {
|
|
68
|
+
const envConfigFile = process.env.NOTIS_CLI_CONFIG_FILE;
|
|
69
|
+
if (envConfigFile) {
|
|
70
|
+
return resolve(envConfigFile);
|
|
71
|
+
}
|
|
72
|
+
return join(homedir(), ".notis", "config.json");
|
|
73
|
+
}
|
|
74
|
+
function readLockOwner(lockDirectory) {
|
|
75
|
+
try {
|
|
76
|
+
return JSON.parse(readFileSync(join(lockDirectory, "owner"), "utf-8"));
|
|
77
|
+
} catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function lockDirectoryMtime(lockDirectory) {
|
|
82
|
+
try {
|
|
83
|
+
return statSync(lockDirectory).mtimeMs;
|
|
84
|
+
} catch {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function publishConfigWriteLock(lockDirectory, ownerId) {
|
|
89
|
+
const candidateDirectory = `${lockDirectory}.candidate-${ownerId}`;
|
|
90
|
+
try {
|
|
91
|
+
mkdirSync(candidateDirectory);
|
|
92
|
+
writeFileSync(
|
|
93
|
+
join(candidateDirectory, "owner"),
|
|
94
|
+
JSON.stringify({ id: ownerId, at: Date.now() }),
|
|
95
|
+
{ mode: 384 }
|
|
96
|
+
);
|
|
97
|
+
try {
|
|
98
|
+
renameSync(candidateDirectory, lockDirectory);
|
|
99
|
+
return true;
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (!existsSync(lockDirectory)) throw error;
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
} finally {
|
|
105
|
+
rmSync(candidateDirectory, { recursive: true, force: true });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function withConfigFileWriteLock(configFile, callback) {
|
|
109
|
+
const lockDirectory = `${configFile}.write-lock`;
|
|
110
|
+
const ownerId = `${process.pid}.${randomUUID()}`;
|
|
111
|
+
const deadline = Date.now() + CONFIG_WRITE_LOCK_TIMEOUT_MS;
|
|
112
|
+
mkdirSync(dirname(configFile), { recursive: true });
|
|
113
|
+
for (; ; ) {
|
|
114
|
+
if (!existsSync(lockDirectory) && publishConfigWriteLock(lockDirectory, ownerId)) {
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
const owner = readLockOwner(lockDirectory);
|
|
118
|
+
const observedMtime = lockDirectoryMtime(lockDirectory);
|
|
119
|
+
const ownerIsStale = owner?.id && Date.now() - Number(owner.at) > CONFIG_WRITE_LOCK_STALE_MS;
|
|
120
|
+
const ownerlessIsStale = !owner && observedMtime !== null && Date.now() - observedMtime > CONFIG_WRITE_LOCK_STALE_MS;
|
|
121
|
+
if (ownerIsStale || ownerlessIsStale) {
|
|
122
|
+
try {
|
|
123
|
+
const currentOwner = readLockOwner(lockDirectory);
|
|
124
|
+
const ownerUnchanged = owner?.id ? currentOwner?.id === owner.id : !currentOwner && lockDirectoryMtime(lockDirectory) === observedMtime;
|
|
125
|
+
if (ownerUnchanged) {
|
|
126
|
+
rmSync(lockDirectory, { recursive: true, force: true });
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
} catch {
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (Date.now() >= deadline) {
|
|
133
|
+
throw new Error(`Timed out waiting to update ${configFile}`);
|
|
134
|
+
}
|
|
135
|
+
Atomics.wait(
|
|
136
|
+
new Int32Array(new SharedArrayBuffer(4)),
|
|
137
|
+
0,
|
|
138
|
+
0,
|
|
139
|
+
CONFIG_WRITE_LOCK_POLL_MS
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
return callback(configFile);
|
|
144
|
+
} finally {
|
|
145
|
+
try {
|
|
146
|
+
if (readLockOwner(lockDirectory)?.id === ownerId) {
|
|
147
|
+
rmSync(lockDirectory, { recursive: true, force: true });
|
|
148
|
+
}
|
|
149
|
+
} catch {
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
54
154
|
// src/runtime/channel.js
|
|
55
155
|
var RELEASE_CHANNELS = ["stable", "beta"];
|
|
56
156
|
var CHANNEL_TAGS = { stable: "latest", beta: "beta" };
|
|
@@ -115,9 +215,9 @@ function getAuthRecovery(runtime = {}, { mode = "expired" } = {}) {
|
|
|
115
215
|
}
|
|
116
216
|
|
|
117
217
|
// src/runtime/profiles.js
|
|
118
|
-
var CONFIG_DIR =
|
|
119
|
-
var CONFIG_FILE =
|
|
120
|
-
var WORKSPACE_DIR =
|
|
218
|
+
var CONFIG_DIR = join2(homedir2(), ".notis");
|
|
219
|
+
var CONFIG_FILE = join2(CONFIG_DIR, "config.json");
|
|
220
|
+
var WORKSPACE_DIR = join2(CONFIG_DIR, "workspace");
|
|
121
221
|
var DEFAULT_API_BASE = "https://api.notis.ai";
|
|
122
222
|
var BETA_API_BASE = "https://api-beta.notis.ai";
|
|
123
223
|
var DEFAULT_PROFILE = "default";
|
|
@@ -131,13 +231,10 @@ var LEGACY_DESKTOP_PROFILE_KEYS = [
|
|
|
131
231
|
"desktop_app_name",
|
|
132
232
|
"desktop_pid"
|
|
133
233
|
];
|
|
134
|
-
var WORKTREE_RUNTIME_FILENAME =
|
|
135
|
-
var WORKTREE_ROUTING_FILENAME =
|
|
234
|
+
var WORKTREE_RUNTIME_FILENAME = join2(".context", "notis-runtime.json");
|
|
235
|
+
var WORKTREE_ROUTING_FILENAME = join2(".context", "notis-routing.json");
|
|
136
236
|
var LOCAL_API_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1"]);
|
|
137
237
|
var LIVE_API_HOSTS = /* @__PURE__ */ new Set(["api.notis.ai", "api-beta.notis.ai"]);
|
|
138
|
-
var CONFIG_WRITE_LOCK_TIMEOUT_MS = 5e3;
|
|
139
|
-
var CONFIG_WRITE_LOCK_STALE_MS = 2e3;
|
|
140
|
-
var CONFIG_WRITE_LOCK_POLL_MS = 10;
|
|
141
238
|
function clone(value) {
|
|
142
239
|
return JSON.parse(JSON.stringify(value));
|
|
143
240
|
}
|
|
@@ -211,23 +308,23 @@ function normalizeConfig(rawConfig = {}) {
|
|
|
211
308
|
}
|
|
212
309
|
function readJsonFile(path3) {
|
|
213
310
|
try {
|
|
214
|
-
return JSON.parse(
|
|
311
|
+
return JSON.parse(readFileSync2(path3, "utf-8"));
|
|
215
312
|
} catch {
|
|
216
313
|
return null;
|
|
217
314
|
}
|
|
218
315
|
}
|
|
219
316
|
function findUp(filename, startDir = process.cwd()) {
|
|
220
|
-
let current =
|
|
317
|
+
let current = resolve2(startDir);
|
|
221
318
|
const root = parse(current).root;
|
|
222
319
|
while (true) {
|
|
223
|
-
const candidate =
|
|
224
|
-
if (
|
|
320
|
+
const candidate = join2(current, filename);
|
|
321
|
+
if (existsSync2(candidate)) {
|
|
225
322
|
return candidate;
|
|
226
323
|
}
|
|
227
324
|
if (current === root) {
|
|
228
325
|
return null;
|
|
229
326
|
}
|
|
230
|
-
current =
|
|
327
|
+
current = dirname2(current);
|
|
231
328
|
}
|
|
232
329
|
}
|
|
233
330
|
function processIsAlive(pid) {
|
|
@@ -298,17 +395,17 @@ function resolveWorktreeRuntime(startDir = process.cwd()) {
|
|
|
298
395
|
function resolveConfigFile() {
|
|
299
396
|
const envConfigFile = process.env.NOTIS_CLI_CONFIG_FILE;
|
|
300
397
|
if (envConfigFile) {
|
|
301
|
-
return
|
|
398
|
+
return resolve2(envConfigFile);
|
|
302
399
|
}
|
|
303
400
|
return CONFIG_FILE;
|
|
304
401
|
}
|
|
305
402
|
function loadConfig() {
|
|
306
403
|
const configFile = resolveConfigFile();
|
|
307
|
-
if (!
|
|
404
|
+
if (!existsSync2(configFile)) {
|
|
308
405
|
return normalizeConfig({});
|
|
309
406
|
}
|
|
310
407
|
try {
|
|
311
|
-
return normalizeConfig(JSON.parse(
|
|
408
|
+
return normalizeConfig(JSON.parse(readFileSync2(configFile, "utf-8")));
|
|
312
409
|
} catch {
|
|
313
410
|
return normalizeConfig({});
|
|
314
411
|
}
|
|
@@ -316,7 +413,7 @@ function loadConfig() {
|
|
|
316
413
|
function writeConfig(configFile, config) {
|
|
317
414
|
let rawConfig = null;
|
|
318
415
|
try {
|
|
319
|
-
rawConfig = JSON.parse(
|
|
416
|
+
rawConfig = JSON.parse(readFileSync2(configFile, "utf-8"));
|
|
320
417
|
} catch {
|
|
321
418
|
}
|
|
322
419
|
const normalized = normalizeConfig(config);
|
|
@@ -334,90 +431,13 @@ function writeConfig(configFile, config) {
|
|
|
334
431
|
writeRawConfig(configFile, persisted);
|
|
335
432
|
}
|
|
336
433
|
function writeRawConfig(configFile, config) {
|
|
337
|
-
|
|
434
|
+
mkdirSync2(dirname2(configFile), { recursive: true });
|
|
338
435
|
const temporaryFile = `${configFile}.${process.pid}.${Date.now()}.tmp`;
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
}
|
|
342
|
-
function readLockOwner(lockDirectory) {
|
|
343
|
-
try {
|
|
344
|
-
return JSON.parse(readFileSync(join(lockDirectory, "owner"), "utf-8"));
|
|
345
|
-
} catch {
|
|
346
|
-
return null;
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
function lockDirectoryMtime(lockDirectory) {
|
|
350
|
-
try {
|
|
351
|
-
return statSync(lockDirectory).mtimeMs;
|
|
352
|
-
} catch {
|
|
353
|
-
return null;
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
function publishConfigWriteLock(lockDirectory, ownerId) {
|
|
357
|
-
const candidateDirectory = `${lockDirectory}.candidate-${ownerId}`;
|
|
358
|
-
try {
|
|
359
|
-
mkdirSync(candidateDirectory);
|
|
360
|
-
writeFileSync(
|
|
361
|
-
join(candidateDirectory, "owner"),
|
|
362
|
-
JSON.stringify({ id: ownerId, at: Date.now() }),
|
|
363
|
-
{ mode: 384 }
|
|
364
|
-
);
|
|
365
|
-
try {
|
|
366
|
-
renameSync(candidateDirectory, lockDirectory);
|
|
367
|
-
return true;
|
|
368
|
-
} catch (error) {
|
|
369
|
-
if (!existsSync(lockDirectory)) throw error;
|
|
370
|
-
return false;
|
|
371
|
-
}
|
|
372
|
-
} finally {
|
|
373
|
-
rmSync(candidateDirectory, { recursive: true, force: true });
|
|
374
|
-
}
|
|
436
|
+
writeFileSync2(temporaryFile, JSON.stringify(config, null, 2), { mode: 384 });
|
|
437
|
+
renameSync2(temporaryFile, configFile);
|
|
375
438
|
}
|
|
376
439
|
function withConfigWriteLock(callback) {
|
|
377
|
-
|
|
378
|
-
const lockDirectory = `${configFile}.write-lock`;
|
|
379
|
-
const ownerId = `${process.pid}.${randomUUID()}`;
|
|
380
|
-
const deadline = Date.now() + CONFIG_WRITE_LOCK_TIMEOUT_MS;
|
|
381
|
-
mkdirSync(dirname(configFile), { recursive: true });
|
|
382
|
-
for (; ; ) {
|
|
383
|
-
if (!existsSync(lockDirectory) && publishConfigWriteLock(lockDirectory, ownerId)) {
|
|
384
|
-
break;
|
|
385
|
-
}
|
|
386
|
-
const owner = readLockOwner(lockDirectory);
|
|
387
|
-
const observedMtime = lockDirectoryMtime(lockDirectory);
|
|
388
|
-
const ownerIsStale = owner?.id && Date.now() - Number(owner.at) > CONFIG_WRITE_LOCK_STALE_MS;
|
|
389
|
-
const ownerlessIsStale = !owner && observedMtime !== null && Date.now() - observedMtime > CONFIG_WRITE_LOCK_STALE_MS;
|
|
390
|
-
if (ownerIsStale || ownerlessIsStale) {
|
|
391
|
-
try {
|
|
392
|
-
const currentOwner = readLockOwner(lockDirectory);
|
|
393
|
-
const ownerUnchanged = owner?.id ? currentOwner?.id === owner.id : !currentOwner && lockDirectoryMtime(lockDirectory) === observedMtime;
|
|
394
|
-
if (ownerUnchanged) {
|
|
395
|
-
rmSync(lockDirectory, { recursive: true, force: true });
|
|
396
|
-
continue;
|
|
397
|
-
}
|
|
398
|
-
} catch {
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
if (Date.now() >= deadline) {
|
|
402
|
-
throw new Error(`Timed out waiting to update ${configFile}`);
|
|
403
|
-
}
|
|
404
|
-
Atomics.wait(
|
|
405
|
-
new Int32Array(new SharedArrayBuffer(4)),
|
|
406
|
-
0,
|
|
407
|
-
0,
|
|
408
|
-
CONFIG_WRITE_LOCK_POLL_MS
|
|
409
|
-
);
|
|
410
|
-
}
|
|
411
|
-
try {
|
|
412
|
-
return callback(configFile);
|
|
413
|
-
} finally {
|
|
414
|
-
try {
|
|
415
|
-
if (readLockOwner(lockDirectory)?.id === ownerId) {
|
|
416
|
-
rmSync(lockDirectory, { recursive: true, force: true });
|
|
417
|
-
}
|
|
418
|
-
} catch {
|
|
419
|
-
}
|
|
420
|
-
}
|
|
440
|
+
return withConfigFileWriteLock(resolveConfigFile(), callback);
|
|
421
441
|
}
|
|
422
442
|
function updateConfig(updater) {
|
|
423
443
|
return withConfigWriteLock((configFile) => {
|
|
@@ -432,6 +452,13 @@ function getProfile(config, profileName) {
|
|
|
432
452
|
const normalized = normalizeConfig(config);
|
|
433
453
|
return Object.hasOwn(normalized.profiles, profileName) ? normalized.profiles[profileName] : {};
|
|
434
454
|
}
|
|
455
|
+
function getCurrentProfileName(config, preferredName) {
|
|
456
|
+
const normalized = normalizeConfig(config);
|
|
457
|
+
if (preferredName && Object.hasOwn(normalized.profiles, preferredName)) {
|
|
458
|
+
return preferredName;
|
|
459
|
+
}
|
|
460
|
+
return normalized.current_profile || DEFAULT_PROFILE;
|
|
461
|
+
}
|
|
435
462
|
function resolveProfileSelection(globalOptions = {}, worktreeRuntime = null, config, { allowUnknownProfile = false } = {}) {
|
|
436
463
|
const normalized = normalizeConfig(config);
|
|
437
464
|
const requested = globalOptions.profile || process.env.NOTIS_PROFILE || "";
|
|
@@ -813,20 +840,126 @@ import {
|
|
|
813
840
|
timingSafeEqual
|
|
814
841
|
} from "node:crypto";
|
|
815
842
|
import {
|
|
816
|
-
mkdirSync as
|
|
843
|
+
mkdirSync as mkdirSync4,
|
|
817
844
|
readdirSync,
|
|
818
|
-
readFileSync as
|
|
819
|
-
renameSync as
|
|
845
|
+
readFileSync as readFileSync4,
|
|
846
|
+
renameSync as renameSync4,
|
|
820
847
|
rmdirSync,
|
|
821
848
|
rmSync as rmSync2,
|
|
822
849
|
statSync as statSync2,
|
|
823
|
-
writeFileSync as
|
|
850
|
+
writeFileSync as writeFileSync4
|
|
824
851
|
} from "node:fs";
|
|
825
|
-
import { homedir as
|
|
826
|
-
import { basename, dirname as
|
|
852
|
+
import { homedir as homedir3 } from "node:os";
|
|
853
|
+
import { basename, dirname as dirname4, join as join4 } from "node:path";
|
|
827
854
|
import { fileURLToPath } from "node:url";
|
|
828
855
|
import { createInterface } from "node:readline/promises";
|
|
829
|
-
|
|
856
|
+
|
|
857
|
+
// src/runtime/computer-identity.js
|
|
858
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
859
|
+
import { execFileSync } from "node:child_process";
|
|
860
|
+
import { mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
|
|
861
|
+
import { hostname as osHostname } from "node:os";
|
|
862
|
+
import { dirname as dirname3, join as join3 } from "node:path";
|
|
863
|
+
var COMPUTER_IDENTITY_VERSION = 1;
|
|
864
|
+
var COMPUTER_NAME_MAX_LENGTH = 64;
|
|
865
|
+
var COMPUTER_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
866
|
+
var FALLBACK_COMPUTER_NAME = "Computer";
|
|
867
|
+
function computerIdentityFile(configFile = resolveCliConfigFile()) {
|
|
868
|
+
return join3(dirname3(configFile), "computer.json");
|
|
869
|
+
}
|
|
870
|
+
function normalizeComputerName(value) {
|
|
871
|
+
if (typeof value !== "string") return null;
|
|
872
|
+
const collapsed = value.replace(/\s+/gu, " ").trim();
|
|
873
|
+
if (!collapsed) return null;
|
|
874
|
+
const characters = Array.from(collapsed);
|
|
875
|
+
if (characters.length <= COMPUTER_NAME_MAX_LENGTH) return collapsed;
|
|
876
|
+
return characters.slice(0, COMPUTER_NAME_MAX_LENGTH).join("").trim();
|
|
877
|
+
}
|
|
878
|
+
function readMacComputerName() {
|
|
879
|
+
try {
|
|
880
|
+
return execFileSync("/usr/sbin/scutil", ["--get", "ComputerName"], {
|
|
881
|
+
encoding: "utf8",
|
|
882
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
883
|
+
timeout: 2e3
|
|
884
|
+
});
|
|
885
|
+
} catch {
|
|
886
|
+
return null;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
function defaultComputerName(options = {}) {
|
|
890
|
+
const platform = options.platform ?? process.platform;
|
|
891
|
+
if (platform === "darwin") {
|
|
892
|
+
const macName = normalizeComputerName((options.readMacComputerName ?? readMacComputerName)());
|
|
893
|
+
if (macName) return macName;
|
|
894
|
+
}
|
|
895
|
+
let host = "";
|
|
896
|
+
try {
|
|
897
|
+
host = String((options.hostname ?? osHostname)() || "");
|
|
898
|
+
} catch {
|
|
899
|
+
host = "";
|
|
900
|
+
}
|
|
901
|
+
return normalizeComputerName(host.replace(/\.local\.?$/iu, "")) || FALLBACK_COMPUTER_NAME;
|
|
902
|
+
}
|
|
903
|
+
function parseIdentityFile(file) {
|
|
904
|
+
let raw;
|
|
905
|
+
try {
|
|
906
|
+
raw = JSON.parse(readFileSync3(file, "utf8"));
|
|
907
|
+
} catch {
|
|
908
|
+
return null;
|
|
909
|
+
}
|
|
910
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
|
911
|
+
return raw;
|
|
912
|
+
}
|
|
913
|
+
function validStored(raw) {
|
|
914
|
+
if (!raw || raw.version !== COMPUTER_IDENTITY_VERSION) return null;
|
|
915
|
+
if (typeof raw.computer_id !== "string" || !COMPUTER_ID_PATTERN.test(raw.computer_id)) return null;
|
|
916
|
+
return {
|
|
917
|
+
computerId: raw.computer_id.toLowerCase(),
|
|
918
|
+
name: normalizeComputerName(raw.name)
|
|
919
|
+
};
|
|
920
|
+
}
|
|
921
|
+
function writeIdentityFile(file, stored) {
|
|
922
|
+
mkdirSync3(dirname3(file), { recursive: true });
|
|
923
|
+
const contents = {
|
|
924
|
+
version: COMPUTER_IDENTITY_VERSION,
|
|
925
|
+
computer_id: stored.computerId,
|
|
926
|
+
...stored.name ? { name: stored.name } : {}
|
|
927
|
+
};
|
|
928
|
+
const temporaryFile = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
929
|
+
writeFileSync3(temporaryFile, `${JSON.stringify(contents, null, 2)}
|
|
930
|
+
`, { mode: 384 });
|
|
931
|
+
renameSync3(temporaryFile, file);
|
|
932
|
+
}
|
|
933
|
+
function withIdentity(stored, options) {
|
|
934
|
+
const defaultName = defaultComputerName(options);
|
|
935
|
+
return {
|
|
936
|
+
computerId: stored.computerId,
|
|
937
|
+
name: stored.name,
|
|
938
|
+
defaultName,
|
|
939
|
+
displayName: stored.name ?? defaultName
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
function readOrCreateLocked(configFile, file) {
|
|
943
|
+
const raw = parseIdentityFile(file);
|
|
944
|
+
const existing = validStored(raw);
|
|
945
|
+
if (existing) return existing;
|
|
946
|
+
const created = {
|
|
947
|
+
computerId: randomUUID2(),
|
|
948
|
+
// A file with a broken id keeps the name the user chose.
|
|
949
|
+
name: normalizeComputerName(raw?.name)
|
|
950
|
+
};
|
|
951
|
+
writeIdentityFile(file, created);
|
|
952
|
+
return created;
|
|
953
|
+
}
|
|
954
|
+
function readComputerIdentity(options = {}) {
|
|
955
|
+
const configFile = options.configFile ?? resolveCliConfigFile();
|
|
956
|
+
const file = computerIdentityFile(configFile);
|
|
957
|
+
const stored = validStored(parseIdentityFile(file)) ?? withConfigFileWriteLock(configFile, () => readOrCreateLocked(configFile, file));
|
|
958
|
+
return withIdentity(stored, options);
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
// src/runtime/oauth.js
|
|
962
|
+
var OAUTH_LOCK_DIR = join4(homedir3(), ".notis", "oauth.lock");
|
|
830
963
|
var DEFAULT_REFRESH_EXPIRES_IN = 30 * 24 * 60 * 60;
|
|
831
964
|
var PENDING_LOGIN_TTL_SECONDS = 30 * 60;
|
|
832
965
|
var OAUTH_HTTP_TIMEOUT_MS = 1e4;
|
|
@@ -903,6 +1036,14 @@ function storedOAuthMetadata(runtime, profile) {
|
|
|
903
1036
|
revocationEndpoint: `${issuer}/oauth/revoke`
|
|
904
1037
|
};
|
|
905
1038
|
}
|
|
1039
|
+
function cliDeviceParams() {
|
|
1040
|
+
try {
|
|
1041
|
+
const identity = readComputerIdentity({ configFile: resolveConfigFile() });
|
|
1042
|
+
return { device_id: identity.computerId, device_name: identity.displayName };
|
|
1043
|
+
} catch {
|
|
1044
|
+
return {};
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
906
1047
|
function persistOAuthTokenResponse(runtime, metadata, tokenResponse) {
|
|
907
1048
|
const now = Math.floor(Date.now() / 1e3);
|
|
908
1049
|
const payload = decodeJwtPayload(tokenResponse.access_token);
|
|
@@ -959,11 +1100,11 @@ function listenerGlobalLockDir() {
|
|
|
959
1100
|
return `${resolveConfigFile()}.oauth-listener-global.lock`;
|
|
960
1101
|
}
|
|
961
1102
|
function listenerGlobalLockOwnerFile(lockDir) {
|
|
962
|
-
return
|
|
1103
|
+
return join4(lockDir, "owner.json");
|
|
963
1104
|
}
|
|
964
1105
|
function readListenerGlobalLockOwner(lockDir) {
|
|
965
1106
|
try {
|
|
966
|
-
return JSON.parse(
|
|
1107
|
+
return JSON.parse(readFileSync4(listenerGlobalLockOwnerFile(lockDir), "utf-8"));
|
|
967
1108
|
} catch {
|
|
968
1109
|
return null;
|
|
969
1110
|
}
|
|
@@ -971,7 +1112,7 @@ function readListenerGlobalLockOwner(lockDir) {
|
|
|
971
1112
|
function writeListenerGlobalLockOwner(lock) {
|
|
972
1113
|
const current = readListenerGlobalLockOwner(lock.lockDir);
|
|
973
1114
|
if (current && current.owner_token !== lock.ownerToken) return false;
|
|
974
|
-
|
|
1115
|
+
writeFileSync4(listenerGlobalLockOwnerFile(lock.lockDir), JSON.stringify({
|
|
975
1116
|
owner_token: lock.ownerToken,
|
|
976
1117
|
owner_pid: process.pid,
|
|
977
1118
|
updated_at: Date.now()
|
|
@@ -992,7 +1133,7 @@ function listenerGlobalLockIsStale(lockDir, staleMs) {
|
|
|
992
1133
|
function retireStaleListenerGlobalLock(lockDir) {
|
|
993
1134
|
const retiredDir = `${lockDir}.stale-${process.pid}-${base64url(randomBytes(8))}`;
|
|
994
1135
|
try {
|
|
995
|
-
|
|
1136
|
+
renameSync4(lockDir, retiredDir);
|
|
996
1137
|
} catch {
|
|
997
1138
|
return false;
|
|
998
1139
|
}
|
|
@@ -1001,11 +1142,11 @@ function retireStaleListenerGlobalLock(lockDir) {
|
|
|
1001
1142
|
}
|
|
1002
1143
|
async function acquireListenerStartLock(runtime) {
|
|
1003
1144
|
const lockDir = listenerStartLockDir(runtime);
|
|
1004
|
-
|
|
1145
|
+
mkdirSync4(dirname4(lockDir), { recursive: true });
|
|
1005
1146
|
const deadline = Date.now() + LISTENER_START_LOCK_STALE_MS * 2;
|
|
1006
1147
|
for (; ; ) {
|
|
1007
1148
|
try {
|
|
1008
|
-
|
|
1149
|
+
mkdirSync4(lockDir);
|
|
1009
1150
|
return lockDir;
|
|
1010
1151
|
} catch (error) {
|
|
1011
1152
|
if (error?.code !== "EEXIST") throw error;
|
|
@@ -1022,7 +1163,7 @@ async function acquireListenerStartLock(runtime) {
|
|
|
1022
1163
|
"Timed out waiting for another CLI process to start browser authorization."
|
|
1023
1164
|
);
|
|
1024
1165
|
}
|
|
1025
|
-
await new Promise((
|
|
1166
|
+
await new Promise((resolve4) => setTimeout(resolve4, 50));
|
|
1026
1167
|
}
|
|
1027
1168
|
}
|
|
1028
1169
|
}
|
|
@@ -1039,11 +1180,11 @@ async function acquireListenerGlobalLock({
|
|
|
1039
1180
|
heartbeatMs = LISTENER_GLOBAL_LOCK_HEARTBEAT_MS
|
|
1040
1181
|
} = {}) {
|
|
1041
1182
|
const lockDir = listenerGlobalLockDir();
|
|
1042
|
-
|
|
1183
|
+
mkdirSync4(dirname4(lockDir), { recursive: true });
|
|
1043
1184
|
const deadline = Date.now() + waitMs;
|
|
1044
1185
|
for (; ; ) {
|
|
1045
1186
|
try {
|
|
1046
|
-
|
|
1187
|
+
mkdirSync4(lockDir);
|
|
1047
1188
|
const lock = {
|
|
1048
1189
|
lockDir,
|
|
1049
1190
|
ownerToken: base64url(randomBytes(24)),
|
|
@@ -1069,7 +1210,7 @@ async function acquireListenerGlobalLock({
|
|
|
1069
1210
|
"Timed out waiting for another CLI process to finish OAuth account changes."
|
|
1070
1211
|
);
|
|
1071
1212
|
}
|
|
1072
|
-
await new Promise((
|
|
1213
|
+
await new Promise((resolve4) => setTimeout(resolve4, 50));
|
|
1073
1214
|
}
|
|
1074
1215
|
}
|
|
1075
1216
|
}
|
|
@@ -1080,14 +1221,14 @@ function releaseListenerGlobalLock(lock) {
|
|
|
1080
1221
|
if (owner?.owner_token !== lock.ownerToken) return;
|
|
1081
1222
|
const releasedDir = `${lock.lockDir}.released-${process.pid}-${lock.ownerToken}`;
|
|
1082
1223
|
try {
|
|
1083
|
-
|
|
1224
|
+
renameSync4(lock.lockDir, releasedDir);
|
|
1084
1225
|
} catch {
|
|
1085
1226
|
return;
|
|
1086
1227
|
}
|
|
1087
1228
|
const movedOwner = readListenerGlobalLockOwner(releasedDir);
|
|
1088
1229
|
if (movedOwner?.owner_token !== lock.ownerToken) {
|
|
1089
1230
|
try {
|
|
1090
|
-
|
|
1231
|
+
renameSync4(releasedDir, lock.lockDir);
|
|
1091
1232
|
} catch {
|
|
1092
1233
|
}
|
|
1093
1234
|
return;
|
|
@@ -1159,11 +1300,11 @@ function lockIsStale() {
|
|
|
1159
1300
|
}
|
|
1160
1301
|
}
|
|
1161
1302
|
async function acquireRefreshLock(runtime, waitMs = 6e4) {
|
|
1162
|
-
|
|
1303
|
+
mkdirSync4(join4(homedir3(), ".notis"), { recursive: true });
|
|
1163
1304
|
const deadline = Date.now() + waitMs;
|
|
1164
1305
|
for (; ; ) {
|
|
1165
1306
|
try {
|
|
1166
|
-
|
|
1307
|
+
mkdirSync4(OAUTH_LOCK_DIR);
|
|
1167
1308
|
return true;
|
|
1168
1309
|
} catch (error) {
|
|
1169
1310
|
if (error?.code !== "EEXIST") throw error;
|
|
@@ -1182,7 +1323,7 @@ async function acquireRefreshLock(runtime, waitMs = 6e4) {
|
|
|
1182
1323
|
if (Date.now() >= deadline) {
|
|
1183
1324
|
throw oauthError("oauth_refresh_lock_timeout", "Timed out waiting for another CLI process to refresh OAuth.");
|
|
1184
1325
|
}
|
|
1185
|
-
await new Promise((
|
|
1326
|
+
await new Promise((resolve4) => setTimeout(resolve4, 100));
|
|
1186
1327
|
}
|
|
1187
1328
|
}
|
|
1188
1329
|
}
|
|
@@ -1217,7 +1358,8 @@ async function refreshOAuthCredential(runtime, fetchImpl = fetch) {
|
|
|
1217
1358
|
grant_type: "refresh_token",
|
|
1218
1359
|
refresh_token: profile.oauth_refresh_token,
|
|
1219
1360
|
client_id: profile.oauth_client_id,
|
|
1220
|
-
resource: metadata.resource
|
|
1361
|
+
resource: metadata.resource,
|
|
1362
|
+
...cliDeviceParams()
|
|
1221
1363
|
})
|
|
1222
1364
|
},
|
|
1223
1365
|
fetchImpl
|
|
@@ -1256,13 +1398,17 @@ async function refreshOAuthCredential(runtime, fetchImpl = fetch) {
|
|
|
1256
1398
|
}
|
|
1257
1399
|
|
|
1258
1400
|
// dist/skill-sync/index.js
|
|
1401
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
1402
|
+
import { promises as fs3 } from "node:fs";
|
|
1403
|
+
import { dirname as dirname5, join as join5 } from "node:path";
|
|
1259
1404
|
import { createHash as createHash2 } from "node:crypto";
|
|
1260
|
-
import { createHash as
|
|
1405
|
+
import { createHash as createHash22 } from "crypto";
|
|
1261
1406
|
import { execFile } from "child_process";
|
|
1262
1407
|
import { promises as fs } from "fs";
|
|
1263
1408
|
import os from "os";
|
|
1264
1409
|
import path from "path";
|
|
1265
1410
|
import { promisify } from "util";
|
|
1411
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
1266
1412
|
import { promises as fs2 } from "fs";
|
|
1267
1413
|
import os2 from "os";
|
|
1268
1414
|
import path2 from "path";
|
|
@@ -1280,8 +1426,130 @@ function normalizeAgentTargets(targets) {
|
|
|
1280
1426
|
codex: Boolean(targets?.codex ?? DEFAULT_AGENT_TARGETS.codex)
|
|
1281
1427
|
};
|
|
1282
1428
|
}
|
|
1429
|
+
var NATIVE_IDENTITY_FILE = ".notis-native-skill.json";
|
|
1430
|
+
var UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
1431
|
+
function checkedNativeReference(value, cloudId) {
|
|
1432
|
+
const reference = value;
|
|
1433
|
+
if (!reference || typeof reference !== "object" || Array.isArray(reference) || Object.keys(reference).sort().join(",") !== "access_revision,kind,skill_id,version" || reference.kind !== "native_standalone_skill" || !UUID.test(reference.skill_id) || cloudId !== void 0 && reference.skill_id !== cloudId || !Number.isSafeInteger(reference.access_revision) || reference.access_revision < 0 || !reference.version || Object.keys(reference.version).sort().join(",") !== "digest,revision" || !Number.isSafeInteger(reference.version.revision) || reference.version.revision < 1 || !/^[a-f0-9]{64}$/.test(reference.version.digest)) {
|
|
1434
|
+
throw new Error("Native Skill identity is unavailable. Refresh before syncing.");
|
|
1435
|
+
}
|
|
1436
|
+
return structuredClone(reference);
|
|
1437
|
+
}
|
|
1438
|
+
function nativeDirectory(reference) {
|
|
1439
|
+
return "native-" + checkedNativeReference(reference).skill_id;
|
|
1440
|
+
}
|
|
1441
|
+
function sameNativeReference(left, right) {
|
|
1442
|
+
return Boolean(left && right && left.skill_id === right.skill_id && left.access_revision === right.access_revision && left.version.revision === right.version.revision && left.version.digest === right.version.digest);
|
|
1443
|
+
}
|
|
1444
|
+
function isNativeSkill(skill) {
|
|
1445
|
+
return skill.source === "native" || skill.native_reference !== void 0;
|
|
1446
|
+
}
|
|
1447
|
+
function assertNativePull(response) {
|
|
1448
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1449
|
+
for (const skill of response.skills) {
|
|
1450
|
+
if (!isNativeSkill(skill)) continue;
|
|
1451
|
+
const reference = checkedNativeReference(skill.native_reference, skill.id);
|
|
1452
|
+
if (response.skill_sync_protocol !== 2 || skill.name !== nativeDirectory(reference) || ids.has(skill.id) || !/^[a-f0-9]{64}$/.test(response.sync_scope || "") || skill.native_scope !== response.sync_scope || !Array.isArray(skill.bundle_files) || skill.bundle_hydration_failed || typeof skill.skill_md !== "string") {
|
|
1453
|
+
throw new Error("Native Skill inventory is incomplete. Existing local files were retained.");
|
|
1454
|
+
}
|
|
1455
|
+
const paths = /* @__PURE__ */ new Set();
|
|
1456
|
+
let entrypoint = false;
|
|
1457
|
+
for (const file of skill.bundle_files) {
|
|
1458
|
+
if (typeof file.path !== "string" || typeof file.content_b64 !== "string" || file.path.startsWith("/") || file.path.includes("\\") || file.path.includes("\0") || file.path.split("/").some((part) => !part || part === "." || part === "..") || paths.has(file.path.toLowerCase()) || file.path.toLowerCase() === NATIVE_IDENTITY_FILE) {
|
|
1459
|
+
throw new Error("Native Skill bundle has a conflicting managed path.");
|
|
1460
|
+
}
|
|
1461
|
+
paths.add(file.path.toLowerCase());
|
|
1462
|
+
if (file.path === "SKILL.md") {
|
|
1463
|
+
entrypoint = Buffer.from(file.content_b64, "base64").equals(Buffer.from(skill.skill_md, "utf8"));
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
if (!entrypoint) throw new Error("Native Skill instructions and files do not match.");
|
|
1467
|
+
ids.add(skill.id);
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
function nativeFileDigest(bytes) {
|
|
1471
|
+
return createHash2("sha256").update(bytes).digest("hex");
|
|
1472
|
+
}
|
|
1473
|
+
function nativeFrontmatterName(markdown) {
|
|
1474
|
+
const header = markdown.match(/^---\s*\n([\s\S]*?)\n---/);
|
|
1475
|
+
return header?.[1].match(/^name\s*:\s*(.+)$/m)?.[1].trim().replace(/^['"]|['"]$/g, "") || "";
|
|
1476
|
+
}
|
|
1477
|
+
function checkedNativeIdentity(value) {
|
|
1478
|
+
const identity = value;
|
|
1479
|
+
if (!identity || identity.schema !== 1 || typeof identity.cloudId !== "string" || typeof identity.displayName !== "string" || typeof identity.frontmatterName !== "string" || !/^[a-f0-9]{64}$/.test(identity.scope) || !/^[a-f0-9]{64}$/.test(identity.folderHash) || !identity.files || !Object.keys(identity.files).includes("SKILL.md") || Object.entries(identity.files).some(([name, hash]) => name.startsWith("/") || name.includes("\\") || name.split("/").some((part) => !part || part === "." || part === "..") || !/^[a-f0-9]{64}$/.test(hash))) {
|
|
1480
|
+
throw new Error("Native Skill provenance is incomplete. Existing files were retained.");
|
|
1481
|
+
}
|
|
1482
|
+
return { ...identity, reference: checkedNativeReference(identity.reference, identity.cloudId) };
|
|
1483
|
+
}
|
|
1484
|
+
function nativeState(skill) {
|
|
1485
|
+
if (!isNativeSkill(skill)) return {};
|
|
1486
|
+
return {
|
|
1487
|
+
nativeReference: checkedNativeReference(skill.native_reference, skill.id),
|
|
1488
|
+
...skill.native_settings ? { nativeSettingsRevision: skill.native_settings.revision } : {},
|
|
1489
|
+
nativeDisplayName: skill.display_name || skill.name,
|
|
1490
|
+
nativeScope: skill.native_scope,
|
|
1491
|
+
nativeUnavailable: false
|
|
1492
|
+
};
|
|
1493
|
+
}
|
|
1494
|
+
function bindNativeFolders(response, locals, state) {
|
|
1495
|
+
const nativeIds = new Set(response.skills.filter(isNativeSkill).map((skill) => skill.id));
|
|
1496
|
+
for (const entry of Object.values(state.skills)) if (entry.nativeReference || entry.nativeUnavailable) nativeIds.add(entry.cloudId);
|
|
1497
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1498
|
+
for (const local of locals) {
|
|
1499
|
+
const id = local.cloudId || state.skills[local.name]?.cloudId;
|
|
1500
|
+
if (!id || !nativeIds.has(id) && !local.nativeReference) continue;
|
|
1501
|
+
if (local.nativeReference) checkedNativeReference(local.nativeReference, id);
|
|
1502
|
+
if (byId.has(id)) throw new Error("Two local folders claim the same native Skill. Keep both copies and resolve the conflict.");
|
|
1503
|
+
byId.set(id, local);
|
|
1504
|
+
}
|
|
1505
|
+
const skills = response.skills.map((skill) => isNativeSkill(skill) && byId.has(skill.id) ? { ...skill, name: byId.get(skill.id).name } : skill);
|
|
1506
|
+
for (const skill of skills.filter(isNativeSkill)) {
|
|
1507
|
+
if (skills.some((other) => other.id !== skill.id && other.name === skill.name)) {
|
|
1508
|
+
throw new Error("A native Skill and another Skill share a local folder. Existing files were retained.");
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
return { ...response, skills };
|
|
1512
|
+
}
|
|
1513
|
+
function previousNativeState(state, skill) {
|
|
1514
|
+
const named = state.skills[skill.name];
|
|
1515
|
+
return named?.cloudId === skill.id ? named : Object.values(state.skills).find((entry) => entry.cloudId === skill.id);
|
|
1516
|
+
}
|
|
1517
|
+
function nativeLocalReady(skill, local) {
|
|
1518
|
+
return Boolean(local?.nativeFilesCurrent && local.folderHash === local.nativeBaseFolderHash && local.cloudId === skill.id && local.nativeScope === skill.native_scope && sameNativeReference(local.nativeReference, skill.native_reference));
|
|
1519
|
+
}
|
|
1520
|
+
function pendingLegacyUpgrade(skill, local, state) {
|
|
1521
|
+
if (!isNativeSkill(skill) || !local || local.nativeReference || local.cloudId) return false;
|
|
1522
|
+
const previous = previousNativeState(state, skill);
|
|
1523
|
+
return Boolean(previous && !previous.nativeReference);
|
|
1524
|
+
}
|
|
1525
|
+
function nativeLinkRows(response, locals, state) {
|
|
1526
|
+
return response.skills.map((skill) => {
|
|
1527
|
+
const local = locals.find((row) => row.name === skill.name);
|
|
1528
|
+
return isNativeSkill(skill) && !nativeLocalReady(skill, local) && !(state && pendingLegacyUpgrade(skill, local, state)) ? { ...skill, status: "disabled" } : skill;
|
|
1529
|
+
});
|
|
1530
|
+
}
|
|
1531
|
+
function retainMissingNativeState(previous, next) {
|
|
1532
|
+
const present = new Set(Object.values(next.skills).map((row) => row.cloudId));
|
|
1533
|
+
const retained = Object.fromEntries(Object.entries(previous.skills).filter(([, row]) => (row.nativeReference || row.nativeUnavailable) && !present.has(row.cloudId)).map(([name, row]) => [name, { ...row, nativeUnavailable: true, verifiedAgentLinks: {} }]));
|
|
1534
|
+
const history = structuredClone(previous.nativeHistory || {});
|
|
1535
|
+
for (const [name, row] of [...Object.entries(previous.skills), ...Object.entries(next.skills)]) {
|
|
1536
|
+
if (!row.nativeReference && !row.nativeUnavailable) continue;
|
|
1537
|
+
const names = history[row.cloudId]?.names || [];
|
|
1538
|
+
history[row.cloudId] = { names: [.../* @__PURE__ */ new Set([...names, name])] };
|
|
1539
|
+
}
|
|
1540
|
+
return {
|
|
1541
|
+
...next,
|
|
1542
|
+
skills: { ...retained, ...next.skills },
|
|
1543
|
+
...Object.keys(history).length ? { nativeHistory: history } : {}
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
function hasNativeFolderHistory(state, name) {
|
|
1547
|
+
return Object.values(state.nativeHistory || {}).some((row) => row.names.includes(name));
|
|
1548
|
+
}
|
|
1283
1549
|
var HOME_DIR = os.homedir();
|
|
1284
1550
|
var execFileAsync = promisify(execFile);
|
|
1551
|
+
var NativeSkillIdentityError = class extends Error {
|
|
1552
|
+
};
|
|
1285
1553
|
var AGENTS_DIR = path.join(HOME_DIR, ".agents");
|
|
1286
1554
|
var LEGACY_AGENTS_SKILLS_DIR = path.join(AGENTS_DIR, "skills");
|
|
1287
1555
|
var NOTIS_SKILL_SYNC_ROOT = path.join(HOME_DIR, ".notis", "skills");
|
|
@@ -1341,15 +1609,18 @@ function sanitizePathSegment(value) {
|
|
|
1341
1609
|
if (sanitized === raw) {
|
|
1342
1610
|
return sanitized;
|
|
1343
1611
|
}
|
|
1344
|
-
return `${sanitized}-${
|
|
1612
|
+
return `${sanitized}-${createHash22("sha256").update(raw).digest("hex").slice(0, 12)}`;
|
|
1345
1613
|
}
|
|
1346
|
-
function getSkillSyncPathsForUser(authUserId, agentsDir = AGENTS_DIR) {
|
|
1614
|
+
function getSkillSyncPathsForUser(authUserId, agentsDir = AGENTS_DIR, namespace, syncHome) {
|
|
1347
1615
|
const safeUserId = sanitizePathSegment(authUserId);
|
|
1348
|
-
const
|
|
1349
|
-
const
|
|
1350
|
-
const
|
|
1616
|
+
const homeDir = syncHome ? path.resolve(syncHome) : void 0;
|
|
1617
|
+
const resolvedAgentsDir = homeDir ? path.join(homeDir, ".agents") : path.resolve(agentsDir);
|
|
1618
|
+
const syncRoot = homeDir ? path.join(homeDir, ".notis", "skills") : getDefaultSyncRootForAgentsDir(resolvedAgentsDir);
|
|
1619
|
+
const userRoot = namespace ? path.join(syncRoot, "environments", sanitizePathSegment(namespace), "users", safeUserId) : path.join(syncRoot, "users", safeUserId);
|
|
1351
1620
|
const legacyUserRoot = path.join(resolvedAgentsDir, "notis", "users", safeUserId);
|
|
1352
1621
|
return {
|
|
1622
|
+
...homeDir ? { homeDir } : {},
|
|
1623
|
+
...namespace ? { isolatedNamespace: sanitizePathSegment(namespace) } : {},
|
|
1353
1624
|
agentsDir: resolvedAgentsDir,
|
|
1354
1625
|
syncRoot,
|
|
1355
1626
|
legacySkillsDir: path.join(resolvedAgentsDir, "skills"),
|
|
@@ -1398,16 +1669,23 @@ async function readJsonFile2(filePath) {
|
|
|
1398
1669
|
return null;
|
|
1399
1670
|
}
|
|
1400
1671
|
}
|
|
1401
|
-
|
|
1672
|
+
var IGNORED_SKILL_DIRECTORIES = /* @__PURE__ */ new Set(["__pycache__", ".pytest_cache"]);
|
|
1673
|
+
function isIgnoredSkillEntry(entry) {
|
|
1674
|
+
if (entry.name === ".DS_Store") return true;
|
|
1675
|
+
if (entry.isDirectory()) return IGNORED_SKILL_DIRECTORIES.has(entry.name);
|
|
1676
|
+
return /\.py[co]$/i.test(entry.name);
|
|
1677
|
+
}
|
|
1678
|
+
async function listFilesRecursive(dirPath, rootPath = dirPath, strictLinks = false) {
|
|
1402
1679
|
const entries = await fs.readdir(dirPath, { withFileTypes: true });
|
|
1403
1680
|
const nested = await Promise.all(
|
|
1404
1681
|
entries.map(async (entry) => {
|
|
1405
|
-
if (entry.name ===
|
|
1682
|
+
if (isIgnoredSkillEntry(entry) || dirPath === rootPath && entry.name === NATIVE_IDENTITY_FILE) {
|
|
1406
1683
|
return [];
|
|
1407
1684
|
}
|
|
1408
1685
|
const fullPath = path.join(dirPath, entry.name);
|
|
1686
|
+
if (strictLinks && entry.isSymbolicLink()) throw new Error("Native Skill bundles cannot contain symbolic links.");
|
|
1409
1687
|
if (entry.isDirectory()) {
|
|
1410
|
-
return listFilesRecursive(fullPath);
|
|
1688
|
+
return listFilesRecursive(fullPath, rootPath, strictLinks);
|
|
1411
1689
|
}
|
|
1412
1690
|
if (entry.isFile()) {
|
|
1413
1691
|
return [fullPath];
|
|
@@ -1418,7 +1696,7 @@ async function listFilesRecursive(dirPath) {
|
|
|
1418
1696
|
return nested.flat().sort();
|
|
1419
1697
|
}
|
|
1420
1698
|
async function computeFolderHash(dirPath) {
|
|
1421
|
-
const hash =
|
|
1699
|
+
const hash = createHash22("sha256");
|
|
1422
1700
|
const filePaths = await listFilesRecursive(dirPath);
|
|
1423
1701
|
for (const filePath of filePaths) {
|
|
1424
1702
|
const relativePath = path.relative(dirPath, filePath);
|
|
@@ -1496,17 +1774,17 @@ function defaultTopLevelSkillSources(paths) {
|
|
|
1496
1774
|
{ label: "agents", root: paths.legacySkillsDir, priority: 2 },
|
|
1497
1775
|
{
|
|
1498
1776
|
label: "codex",
|
|
1499
|
-
root: path.join(HOME_DIR, ".codex", "skills"),
|
|
1777
|
+
root: path.join(paths.homeDir || HOME_DIR, ".codex", "skills"),
|
|
1500
1778
|
priority: 3
|
|
1501
1779
|
},
|
|
1502
1780
|
{
|
|
1503
1781
|
label: "cursor",
|
|
1504
|
-
root: path.join(HOME_DIR, ".cursor", "skills"),
|
|
1782
|
+
root: path.join(paths.homeDir || HOME_DIR, ".cursor", "skills"),
|
|
1505
1783
|
priority: 4
|
|
1506
1784
|
},
|
|
1507
1785
|
{
|
|
1508
1786
|
label: "claude",
|
|
1509
|
-
root: path.join(HOME_DIR, ".claude", "skills"),
|
|
1787
|
+
root: path.join(paths.homeDir || HOME_DIR, ".claude", "skills"),
|
|
1510
1788
|
priority: 5
|
|
1511
1789
|
}
|
|
1512
1790
|
);
|
|
@@ -1726,6 +2004,7 @@ async function ensureCanonicalSkillsDir(paths = DEFAULT_SYNC_PATHS) {
|
|
|
1726
2004
|
async function scanLocalSkills(paths = DEFAULT_SYNC_PATHS) {
|
|
1727
2005
|
await ensureCanonicalSkillsDir(paths);
|
|
1728
2006
|
const sourceUrls = await readSkillLock(paths);
|
|
2007
|
+
const previousState = await readSyncState(paths);
|
|
1729
2008
|
const entries = await fs.readdir(paths.skillsDir, { withFileTypes: true });
|
|
1730
2009
|
const skills = await Promise.all(
|
|
1731
2010
|
entries.map(async (entry) => {
|
|
@@ -1734,6 +2013,15 @@ async function scanLocalSkills(paths = DEFAULT_SYNC_PATHS) {
|
|
|
1734
2013
|
}
|
|
1735
2014
|
const skillDir = path.join(paths.skillsDir, entry.name);
|
|
1736
2015
|
const skillMdPath = path.join(skillDir, "SKILL.md");
|
|
2016
|
+
let marker = null;
|
|
2017
|
+
try {
|
|
2018
|
+
marker = await fs.readFile(path.join(skillDir, NATIVE_IDENTITY_FILE), "utf8");
|
|
2019
|
+
} catch (error) {
|
|
2020
|
+
if (error.code !== "ENOENT") {
|
|
2021
|
+
throw new NativeSkillIdentityError("Native Skill provenance could not be read; existing files were retained.");
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
const knownNative = marker !== null || Boolean(previousState.skills[entry.name]?.nativeReference) || Object.values(previousState.nativeHistory || {}).some((row) => row.names.includes(entry.name));
|
|
1737
2025
|
try {
|
|
1738
2026
|
const skillMd = await fs.readFile(skillMdPath, "utf8");
|
|
1739
2027
|
const { description } = parseFrontMatter(skillMd);
|
|
@@ -1745,11 +2033,38 @@ async function scanLocalSkills(paths = DEFAULT_SYNC_PATHS) {
|
|
|
1745
2033
|
folderHash,
|
|
1746
2034
|
directoryPath: skillDir
|
|
1747
2035
|
};
|
|
2036
|
+
if (marker !== null) {
|
|
2037
|
+
let identity;
|
|
2038
|
+
try {
|
|
2039
|
+
identity = checkedNativeIdentity(JSON.parse(marker));
|
|
2040
|
+
} catch {
|
|
2041
|
+
throw new NativeSkillIdentityError("Native Skill provenance is unreadable; do not upload it as a new Skill.");
|
|
2042
|
+
}
|
|
2043
|
+
let current = true;
|
|
2044
|
+
for (const [name, expected] of Object.entries(identity.files)) {
|
|
2045
|
+
try {
|
|
2046
|
+
if (nativeFileDigest(await fs.readFile(resolveSkillBundleFilePath(skillDir, name))) !== expected) current = false;
|
|
2047
|
+
} catch {
|
|
2048
|
+
current = false;
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
const editedName = nativeFrontmatterName(skillMd);
|
|
2052
|
+
Object.assign(skill, {
|
|
2053
|
+
cloudId: identity.cloudId,
|
|
2054
|
+
nativeReference: identity.reference,
|
|
2055
|
+
nativeScope: identity.scope,
|
|
2056
|
+
nativeBaseFolderHash: identity.folderHash,
|
|
2057
|
+
nativeFilesCurrent: current,
|
|
2058
|
+
displayName: editedName && editedName !== identity.frontmatterName ? editedName : identity.displayName
|
|
2059
|
+
});
|
|
2060
|
+
}
|
|
1748
2061
|
if (sourceUrls[entry.name]) {
|
|
1749
2062
|
skill.sourceUrl = sourceUrls[entry.name];
|
|
1750
2063
|
}
|
|
1751
2064
|
return skill;
|
|
1752
|
-
} catch {
|
|
2065
|
+
} catch (error) {
|
|
2066
|
+
if (error instanceof NativeSkillIdentityError) throw error;
|
|
2067
|
+
if (knownNative) throw new NativeSkillIdentityError("Native Skill files could not be read; existing files were retained.");
|
|
1753
2068
|
return null;
|
|
1754
2069
|
}
|
|
1755
2070
|
})
|
|
@@ -1760,6 +2075,9 @@ function normalizeSyncState(state) {
|
|
|
1760
2075
|
if (!state || state.version !== 1 || typeof state.skills !== "object") {
|
|
1761
2076
|
return null;
|
|
1762
2077
|
}
|
|
2078
|
+
if (state.nativeHistory && (typeof state.nativeHistory !== "object" || Array.isArray(state.nativeHistory) || Object.values(state.nativeHistory).some((row) => !row || !Array.isArray(row.names) || row.names.some((name) => typeof name !== "string")))) {
|
|
2079
|
+
throw new Error("Native Skill sync provenance is unreadable; existing files were retained.");
|
|
2080
|
+
}
|
|
1763
2081
|
const normalizeStoredAgentTargets = (targets) => ({
|
|
1764
2082
|
notis: Boolean(targets?.notis ?? true),
|
|
1765
2083
|
claude_code: Boolean(targets?.claude_code ?? true),
|
|
@@ -1768,6 +2086,7 @@ function normalizeSyncState(state) {
|
|
|
1768
2086
|
});
|
|
1769
2087
|
return {
|
|
1770
2088
|
version: 1,
|
|
2089
|
+
...state.nativeHistory ? { nativeHistory: state.nativeHistory } : {},
|
|
1771
2090
|
lastSyncedAt: typeof state.lastSyncedAt === "string" ? state.lastSyncedAt : null,
|
|
1772
2091
|
skills: Object.fromEntries(
|
|
1773
2092
|
Object.entries(state.skills || {}).map(([skillName, skillState]) => [
|
|
@@ -1842,20 +2161,49 @@ async function createZipFromDirectory(directoryPath) {
|
|
|
1842
2161
|
os.tmpdir(),
|
|
1843
2162
|
`notis-skill-${Date.now()}-${Math.random().toString(36).slice(2)}.zip`
|
|
1844
2163
|
);
|
|
1845
|
-
const parentDir = path.dirname(directoryPath);
|
|
1846
2164
|
const directoryName = path.basename(directoryPath);
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
2165
|
+
const stagingRoot = await fs.mkdtemp(path.join(os.tmpdir(), "notis-skill-bundle-"));
|
|
2166
|
+
try {
|
|
2167
|
+
const stagedDir = path.join(stagingRoot, directoryName);
|
|
2168
|
+
for (const filePath of await listFilesRecursive(directoryPath)) {
|
|
2169
|
+
const target = path.join(stagedDir, path.relative(directoryPath, filePath));
|
|
2170
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
2171
|
+
await fs.copyFile(filePath, target);
|
|
2172
|
+
}
|
|
2173
|
+
await fs.mkdir(stagedDir, { recursive: true });
|
|
2174
|
+
if (process.platform === "win32") {
|
|
2175
|
+
const systemTar = path.join(
|
|
2176
|
+
process.env.SystemRoot || "C:\\Windows",
|
|
2177
|
+
"System32",
|
|
2178
|
+
"tar.exe"
|
|
2179
|
+
);
|
|
2180
|
+
if (await pathExists(systemTar)) {
|
|
2181
|
+
await execFileAsync(systemTar, [
|
|
2182
|
+
"-c",
|
|
2183
|
+
"--format",
|
|
2184
|
+
"zip",
|
|
2185
|
+
"-f",
|
|
2186
|
+
zipPath,
|
|
2187
|
+
"-C",
|
|
2188
|
+
stagingRoot,
|
|
2189
|
+
directoryName
|
|
2190
|
+
]);
|
|
2191
|
+
return zipPath;
|
|
2192
|
+
}
|
|
2193
|
+
await execFileAsync("powershell.exe", [
|
|
2194
|
+
"-NoProfile",
|
|
2195
|
+
"-Command",
|
|
2196
|
+
`Compress-Archive -Path '${stagedDir.replace(/'/g, "''")}' -DestinationPath '${zipPath.replace(/'/g, "''")}' -Force`
|
|
2197
|
+
]);
|
|
2198
|
+
return zipPath;
|
|
2199
|
+
}
|
|
2200
|
+
await execFileAsync("zip", ["-qry", zipPath, directoryName], {
|
|
2201
|
+
cwd: stagingRoot
|
|
2202
|
+
});
|
|
1853
2203
|
return zipPath;
|
|
2204
|
+
} finally {
|
|
2205
|
+
await fs.rm(stagingRoot, { recursive: true, force: true });
|
|
1854
2206
|
}
|
|
1855
|
-
await execFileAsync("zip", ["-qry", zipPath, directoryName], {
|
|
1856
|
-
cwd: parentDir
|
|
1857
|
-
});
|
|
1858
|
-
return zipPath;
|
|
1859
2207
|
}
|
|
1860
2208
|
async function extractZipToDirectory(zipPath, destinationDir) {
|
|
1861
2209
|
const extractRoot = await fs.mkdtemp(
|
|
@@ -1898,13 +2246,18 @@ async function listRelativeFiles(dirPath) {
|
|
|
1898
2246
|
function toPosixRelativePath(rootDir, filePath) {
|
|
1899
2247
|
return path.relative(rootDir, filePath).split(path.sep).join("/");
|
|
1900
2248
|
}
|
|
1901
|
-
async function preserveUnmanagedFiles(existingDir, stagingDir, previouslyApplied) {
|
|
2249
|
+
async function preserveUnmanagedFiles(existingDir, stagingDir, previouslyApplied, strictConflicts = false) {
|
|
1902
2250
|
const managed = previouslyApplied ? new Set(previouslyApplied) : null;
|
|
1903
2251
|
for (const existingFile of await listFilesRecursive(existingDir)) {
|
|
1904
2252
|
const relativePath = toPosixRelativePath(existingDir, existingFile);
|
|
1905
2253
|
if (managed?.has(relativePath)) continue;
|
|
1906
2254
|
const stagedPath = path.join(stagingDir, ...relativePath.split("/"));
|
|
1907
|
-
if (await pathExists(stagedPath))
|
|
2255
|
+
if (await pathExists(stagedPath)) {
|
|
2256
|
+
if (strictConflicts && !(await fs.readFile(existingFile)).equals(await fs.readFile(stagedPath))) {
|
|
2257
|
+
throw new Error("An incoming native Skill file conflicts with a local file. Local files were retained.");
|
|
2258
|
+
}
|
|
2259
|
+
continue;
|
|
2260
|
+
}
|
|
1908
2261
|
await fs.mkdir(path.dirname(stagedPath), { recursive: true });
|
|
1909
2262
|
await fs.copyFile(existingFile, stagedPath);
|
|
1910
2263
|
}
|
|
@@ -1932,13 +2285,46 @@ async function replaceSkillDirectoryAtomically(skillDir, populateDir, preserve)
|
|
|
1932
2285
|
let promotedStaging = false;
|
|
1933
2286
|
let cleanupError = null;
|
|
1934
2287
|
try {
|
|
2288
|
+
if (preserve?.native && preserve.expectedFolderHash === void 0) {
|
|
2289
|
+
let existing = false;
|
|
2290
|
+
try {
|
|
2291
|
+
await fs.lstat(skillDir);
|
|
2292
|
+
existing = true;
|
|
2293
|
+
} catch (error) {
|
|
2294
|
+
if (error.code !== "ENOENT") throw error;
|
|
2295
|
+
}
|
|
2296
|
+
if (existing) throw new Error("Existing native Skill files need a readable baseline before replacement.");
|
|
2297
|
+
}
|
|
2298
|
+
if (preserve?.expectedFolderHash !== void 0 && (!await pathExists(skillDir) || await computeFolderHash(skillDir) !== preserve.expectedFolderHash)) {
|
|
2299
|
+
throw new Error("Local Skill files changed before sync; the newer local edits were retained.");
|
|
2300
|
+
}
|
|
1935
2301
|
await populateDir(stagingDir);
|
|
1936
2302
|
if (preserve && await pathExists(skillDir)) {
|
|
1937
|
-
await preserveUnmanagedFiles(
|
|
2303
|
+
await preserveUnmanagedFiles(
|
|
2304
|
+
skillDir,
|
|
2305
|
+
stagingDir,
|
|
2306
|
+
preserve.previouslyApplied,
|
|
2307
|
+
preserve.native && !preserve.legacyBaseline
|
|
2308
|
+
);
|
|
2309
|
+
}
|
|
2310
|
+
if (preserve?.native) {
|
|
2311
|
+
const markerPath = path.join(stagingDir, NATIVE_IDENTITY_FILE);
|
|
2312
|
+
const marker = checkedNativeIdentity(JSON.parse(await fs.readFile(markerPath, "utf8")));
|
|
2313
|
+
marker.folderHash = await computeFolderHash(stagingDir);
|
|
2314
|
+
await fs.writeFile(markerPath, JSON.stringify(marker), { mode: 384 });
|
|
2315
|
+
}
|
|
2316
|
+
if (preserve?.expectedFolderHash !== void 0 && (!await pathExists(skillDir) || await computeFolderHash(skillDir) !== preserve.expectedFolderHash)) {
|
|
2317
|
+
throw new Error("Local Skill files changed during sync; the newer local edits were retained.");
|
|
1938
2318
|
}
|
|
1939
2319
|
if (await pathExists(skillDir)) {
|
|
1940
2320
|
await fs.rename(skillDir, backupDir);
|
|
1941
2321
|
movedExisting = true;
|
|
2322
|
+
if (preserve?.native && preserve.expectedFolderHash === void 0) {
|
|
2323
|
+
throw new Error("Native Skill files appeared during sync; existing files were retained.");
|
|
2324
|
+
}
|
|
2325
|
+
if (preserve?.expectedFolderHash !== void 0 && await computeFolderHash(backupDir) !== preserve.expectedFolderHash) {
|
|
2326
|
+
throw new Error("Local Skill files changed before publication; the newer local edits were retained.");
|
|
2327
|
+
}
|
|
1942
2328
|
}
|
|
1943
2329
|
await fs.rename(stagingDir, skillDir);
|
|
1944
2330
|
promotedStaging = true;
|
|
@@ -1983,12 +2369,43 @@ async function createSkillBundleBase64(skill) {
|
|
|
1983
2369
|
await fs.rm(zipPath, { force: true });
|
|
1984
2370
|
}
|
|
1985
2371
|
}
|
|
2372
|
+
async function captureNativeSkillFiles(skill) {
|
|
2373
|
+
const hash = createHash22("sha256");
|
|
2374
|
+
const files = [];
|
|
2375
|
+
for (const filePath of await listFilesRecursive(skill.directoryPath, skill.directoryPath, true)) {
|
|
2376
|
+
const relative2 = path.relative(skill.directoryPath, filePath);
|
|
2377
|
+
const bytes = await fs.readFile(filePath);
|
|
2378
|
+
hash.update(relative2);
|
|
2379
|
+
hash.update("\0");
|
|
2380
|
+
hash.update(bytes);
|
|
2381
|
+
hash.update("\0");
|
|
2382
|
+
files.push({ path: relative2.split(path.sep).join("/"), content_b64: bytes.toString("base64") });
|
|
2383
|
+
}
|
|
2384
|
+
if (hash.digest("hex") !== skill.folderHash) throw new Error("Local Skill files changed before upload. Sync again with the current files.");
|
|
2385
|
+
return files;
|
|
2386
|
+
}
|
|
1986
2387
|
async function writeCloudSkillToDisk(skill, bundleBytes, paths = DEFAULT_SYNC_PATHS, options = {}) {
|
|
2388
|
+
if (isNativeSkill(skill)) {
|
|
2389
|
+
assertNativePull({
|
|
2390
|
+
skills: [{ ...skill, name: "native-" + skill.id }],
|
|
2391
|
+
skill_sync_protocol: 2,
|
|
2392
|
+
sync_scope: skill.native_scope,
|
|
2393
|
+
sync_enabled: true,
|
|
2394
|
+
last_synced_at: null
|
|
2395
|
+
});
|
|
2396
|
+
if (bundleBytes?.length) throw new Error("Native Skills require their verified complete file response.");
|
|
2397
|
+
}
|
|
1987
2398
|
const skillDir = path.join(
|
|
1988
2399
|
paths.skillsDir,
|
|
1989
2400
|
safeName(skill.name, paths.skillsDir)
|
|
1990
2401
|
);
|
|
1991
|
-
const preserve = {
|
|
2402
|
+
const preserve = {
|
|
2403
|
+
previouslyApplied: options.previouslyApplied,
|
|
2404
|
+
expectedFolderHash: options.expectedFolderHash,
|
|
2405
|
+
native: isNativeSkill(skill),
|
|
2406
|
+
// An unchanged legacy folder upgrading in place: shared files take the cloud version.
|
|
2407
|
+
legacyBaseline: isNativeSkill(skill) && options.legacyBaseline === true && options.expectedFolderHash !== void 0
|
|
2408
|
+
};
|
|
1992
2409
|
if (bundleBytes?.length) {
|
|
1993
2410
|
const bundlePath = path.join(
|
|
1994
2411
|
os.tmpdir(),
|
|
@@ -2028,6 +2445,20 @@ async function writeCloudSkillToDisk(skill, bundleBytes, paths = DEFAULT_SYNC_PA
|
|
|
2028
2445
|
);
|
|
2029
2446
|
appliedFiles.push(toPosixRelativePath(stagingDir, filePath));
|
|
2030
2447
|
}
|
|
2448
|
+
if (skill.native_reference) {
|
|
2449
|
+
const identity = {
|
|
2450
|
+
schema: 1,
|
|
2451
|
+
cloudId: skill.id,
|
|
2452
|
+
reference: skill.native_reference,
|
|
2453
|
+
displayName: skill.display_name || skill.name,
|
|
2454
|
+
frontmatterName: nativeFrontmatterName(skill.skill_md || ""),
|
|
2455
|
+
scope: skill.native_scope,
|
|
2456
|
+
folderHash: await computeFolderHash(stagingDir),
|
|
2457
|
+
files: Object.fromEntries((skill.bundle_files || []).map((file) => [file.path, nativeFileDigest(Buffer.from(file.content_b64, "base64"))]))
|
|
2458
|
+
};
|
|
2459
|
+
await fs.writeFile(path.join(stagingDir, NATIVE_IDENTITY_FILE), JSON.stringify(identity), { mode: 384 });
|
|
2460
|
+
appliedFiles.push(NATIVE_IDENTITY_FILE);
|
|
2461
|
+
}
|
|
2031
2462
|
}, preserve);
|
|
2032
2463
|
return { written: true, appliedFiles: appliedFiles.sort() };
|
|
2033
2464
|
}
|
|
@@ -2063,7 +2494,7 @@ async function fetchSyncSettings(serverUrl, jwt) {
|
|
|
2063
2494
|
}
|
|
2064
2495
|
async function pullSkills(serverUrl, jwt) {
|
|
2065
2496
|
return requestJson(`${serverUrl}/portal_skills/sync-pull`, jwt, {
|
|
2066
|
-
body: {}
|
|
2497
|
+
body: { skill_sync_protocol: 2 }
|
|
2067
2498
|
});
|
|
2068
2499
|
}
|
|
2069
2500
|
async function pushChangedSkills(serverUrl, jwt, changedSkills) {
|
|
@@ -2073,10 +2504,17 @@ async function pushChangedSkills(serverUrl, jwt, changedSkills) {
|
|
|
2073
2504
|
skill_md: skill.skillMd,
|
|
2074
2505
|
source_url: skill.sourceUrl,
|
|
2075
2506
|
folder_hash: skill.folderHash,
|
|
2076
|
-
bundle_base64: await createSkillBundleBase64(skill)
|
|
2507
|
+
...skill.nativeReference ? { bundle_files: await captureNativeSkillFiles(skill) } : { bundle_base64: await createSkillBundleBase64(skill) },
|
|
2508
|
+
...skill.cloudId ? { cloud_id: skill.cloudId } : {},
|
|
2509
|
+
...skill.nativeReference ? {
|
|
2510
|
+
native_reference: skill.nativeReference,
|
|
2511
|
+
display_name: skill.displayName,
|
|
2512
|
+
native_scope: skill.nativeScope
|
|
2513
|
+
} : {}
|
|
2077
2514
|
})));
|
|
2078
2515
|
return requestJson(`${serverUrl}/portal_skills/sync-push`, jwt, {
|
|
2079
2516
|
body: {
|
|
2517
|
+
skill_sync_protocol: 2,
|
|
2080
2518
|
skills: payloadSkills
|
|
2081
2519
|
}
|
|
2082
2520
|
});
|
|
@@ -2089,7 +2527,26 @@ async function downloadSkillBundle(bundleUrl) {
|
|
|
2089
2527
|
}
|
|
2090
2528
|
return Buffer.from(await response.arrayBuffer());
|
|
2091
2529
|
}
|
|
2092
|
-
async function updateAgentTargets(serverUrl, jwt, skillId, targets, expectedUpdatedAt) {
|
|
2530
|
+
async function updateAgentTargets(serverUrl, jwt, skillId, targets, expectedUpdatedAt, native) {
|
|
2531
|
+
if (native) {
|
|
2532
|
+
checkedNativeReference(native.reference, skillId);
|
|
2533
|
+
if (!Number.isSafeInteger(native.settingsRevision) || native.settingsRevision < 0) throw new Error("Refresh native Skill settings before changing assignments.");
|
|
2534
|
+
const payload = {
|
|
2535
|
+
operation: "update",
|
|
2536
|
+
target: { skill_id: skillId, access_revision: native.reference.access_revision },
|
|
2537
|
+
revision: native.settingsRevision,
|
|
2538
|
+
patch: { agent_targets: Object.fromEntries(Object.entries(targets).sort(([a], [b]) => a.localeCompare(b))) }
|
|
2539
|
+
};
|
|
2540
|
+
const requestId = "sync-settings-" + createHash3("sha256").update(JSON.stringify(payload)).digest("hex");
|
|
2541
|
+
const saved = await requestJson(
|
|
2542
|
+
`${serverUrl}/portal_skills/native-settings`,
|
|
2543
|
+
jwt,
|
|
2544
|
+
{ body: { ...payload, request_id: requestId } }
|
|
2545
|
+
);
|
|
2546
|
+
const current = saved.current || saved;
|
|
2547
|
+
if (saved.skill_id !== skillId || typeof saved.receipt_id !== "string" || !saved.receipt_id || current.target?.skill_id !== skillId || !current.settings) throw new Error("Native assignment update was not confirmed.");
|
|
2548
|
+
return { success: true, agent_targets: current.settings.agent_targets, updated_at: current.settings.updated_at };
|
|
2549
|
+
}
|
|
2093
2550
|
return requestJson(`${serverUrl}/portal_skills/agent-targets`, jwt, {
|
|
2094
2551
|
method: "PATCH",
|
|
2095
2552
|
body: {
|
|
@@ -2408,22 +2865,27 @@ function selectCloudSkillsToApply(skills) {
|
|
|
2408
2865
|
}
|
|
2409
2866
|
return [...winners.values()];
|
|
2410
2867
|
}
|
|
2411
|
-
function getPushCandidates(localSkills, syncState, cloudCuratedSkillNames = /* @__PURE__ */ new Set(), cloudSkillNames,
|
|
2868
|
+
function getPushCandidates(localSkills, syncState, cloudCuratedSkillNames = /* @__PURE__ */ new Set(), cloudSkillNames, cloudSkills = []) {
|
|
2412
2869
|
return localSkills.filter((skill) => {
|
|
2413
2870
|
if (cloudCuratedSkillNames.has(skill.name)) {
|
|
2414
2871
|
return false;
|
|
2415
2872
|
}
|
|
2416
|
-
|
|
2417
|
-
|
|
2873
|
+
const previous = syncState.skills[skill.name] || (skill.cloudId ? Object.values(syncState.skills).find((row) => row.cloudId === skill.cloudId) : void 0);
|
|
2874
|
+
const native = cloudSkills.find((row) => isNativeSkill(row) && row.id === (skill.cloudId || previous?.cloudId));
|
|
2875
|
+
if (native || skill.nativeReference || previous?.nativeReference || previous?.nativeUnavailable) {
|
|
2876
|
+
return Boolean(native && skill.nativeReference && skill.nativeScope === native.native_scope && (previous ? previous.folderHash !== skill.folderHash : skill.nativeBaseFolderHash !== skill.folderHash));
|
|
2418
2877
|
}
|
|
2419
|
-
const previous = syncState.skills[skill.name];
|
|
2420
2878
|
if (!previous) {
|
|
2879
|
+
if (hasNativeFolderHistory(syncState, skill.name) || /^native-[a-f0-9-]{36}$/.test(skill.name)) return false;
|
|
2421
2880
|
return true;
|
|
2422
2881
|
}
|
|
2423
2882
|
if (cloudSkillNames && !cloudSkillNames.has(skill.name)) {
|
|
2424
2883
|
return false;
|
|
2425
2884
|
}
|
|
2426
2885
|
return previous.folderHash !== skill.folderHash;
|
|
2886
|
+
}).map((skill) => {
|
|
2887
|
+
const previous = syncState.skills[skill.name] || Object.values(syncState.skills).find((row) => row.cloudId === skill.cloudId);
|
|
2888
|
+
return { ...skill, ...skill.cloudId || previous?.cloudId ? { cloudId: skill.cloudId || previous.cloudId } : {} };
|
|
2427
2889
|
});
|
|
2428
2890
|
}
|
|
2429
2891
|
async function writeCloudSkillWithBundleFallback(skill, dependencies) {
|
|
@@ -2495,6 +2957,62 @@ var DEFAULT_RUN_SKILL_SYNC_DEPS = {
|
|
|
2495
2957
|
removeForeignAccountSymlinks,
|
|
2496
2958
|
updateAgentTargets
|
|
2497
2959
|
};
|
|
2960
|
+
var MIRROR_ONLY_DEPS = {
|
|
2961
|
+
removeForeignAccountSymlinks: async () => 0,
|
|
2962
|
+
removeAllSymlinksForSkill: async () => 0,
|
|
2963
|
+
syncSymlinks: async () => ({ linked: 0, removed: 0, skipped: 0, verifiedAgentLinks: {} })
|
|
2964
|
+
};
|
|
2965
|
+
async function forgetOtherAccountsAgentLinks(paths) {
|
|
2966
|
+
const usersDir = dirname5(dirname5(paths.syncStatePath));
|
|
2967
|
+
let entries;
|
|
2968
|
+
try {
|
|
2969
|
+
entries = await fs3.readdir(usersDir, { withFileTypes: true });
|
|
2970
|
+
} catch {
|
|
2971
|
+
return;
|
|
2972
|
+
}
|
|
2973
|
+
for (const entry of entries) {
|
|
2974
|
+
if (!entry.isDirectory()) continue;
|
|
2975
|
+
const statePath = join5(usersDir, entry.name, ".notis-sync.json");
|
|
2976
|
+
if (statePath === paths.syncStatePath) continue;
|
|
2977
|
+
let state = null;
|
|
2978
|
+
try {
|
|
2979
|
+
state = JSON.parse(await fs3.readFile(statePath, "utf8"));
|
|
2980
|
+
} catch {
|
|
2981
|
+
continue;
|
|
2982
|
+
}
|
|
2983
|
+
if (!state || typeof state !== "object" || !state.skills || typeof state.skills !== "object") continue;
|
|
2984
|
+
let changed = false;
|
|
2985
|
+
for (const skill of Object.values(state.skills)) {
|
|
2986
|
+
if (skill && typeof skill === "object" && "verifiedAgentLinks" in skill) {
|
|
2987
|
+
delete skill.verifiedAgentLinks;
|
|
2988
|
+
changed = true;
|
|
2989
|
+
}
|
|
2990
|
+
}
|
|
2991
|
+
if (!changed) continue;
|
|
2992
|
+
const temporaryPath = `${statePath}.${process.pid}.${Date.now()}.tmp`;
|
|
2993
|
+
await fs3.writeFile(temporaryPath, `${JSON.stringify(state, null, 2)}
|
|
2994
|
+
`, "utf8");
|
|
2995
|
+
await fs3.rename(temporaryPath, statePath);
|
|
2996
|
+
}
|
|
2997
|
+
}
|
|
2998
|
+
function isolatedLinkOptions(paths) {
|
|
2999
|
+
if (!paths.isolatedNamespace && !paths.homeDir) return void 0;
|
|
3000
|
+
const root = paths.isolatedNamespace ? join5(paths.syncRoot, "environments", paths.isolatedNamespace, "agents") : paths.homeDir;
|
|
3001
|
+
return {
|
|
3002
|
+
agentSkillDirs: {
|
|
3003
|
+
notis: paths.skillsDir,
|
|
3004
|
+
claude_code: join5(root, ".claude", "skills"),
|
|
3005
|
+
cursor: join5(root, ".cursor", "skills"),
|
|
3006
|
+
codex: join5(root, ".codex", "skills")
|
|
3007
|
+
},
|
|
3008
|
+
legacyGlobalSkillsDir: join5(root, ".agents", "skills")
|
|
3009
|
+
};
|
|
3010
|
+
}
|
|
3011
|
+
function assertSyncEnvironment(pull, settings) {
|
|
3012
|
+
if ((pull.sync_namespace || null) !== (settings.sync_namespace || null) || settings.sync_scope !== void 0 && pull.sync_scope !== settings.sync_scope) {
|
|
3013
|
+
throw new Error("Skill sync environment changed. Existing mirrors were retained.");
|
|
3014
|
+
}
|
|
3015
|
+
}
|
|
2498
3016
|
function toSkillMap(skills) {
|
|
2499
3017
|
return new Map(skills.map((skill) => [skill.name, skill]));
|
|
2500
3018
|
}
|
|
@@ -2511,7 +3029,7 @@ function decodeJwtSubject(jwt) {
|
|
|
2511
3029
|
}
|
|
2512
3030
|
}
|
|
2513
3031
|
function cloudContentHash(skill) {
|
|
2514
|
-
return
|
|
3032
|
+
return createHash4("sha256").update(JSON.stringify({
|
|
2515
3033
|
md: skill.skill_md,
|
|
2516
3034
|
hash: skill.skill_folder_hash,
|
|
2517
3035
|
source: skill.skill_source_url,
|
|
@@ -2526,6 +3044,12 @@ function shouldWriteCloudSkill(cloudSkill, localSkills, previousState) {
|
|
|
2526
3044
|
if (!localSkill) {
|
|
2527
3045
|
return true;
|
|
2528
3046
|
}
|
|
3047
|
+
if (isNativeSkill(cloudSkill)) {
|
|
3048
|
+
if (localSkill.nativeScope && localSkill.nativeScope !== cloudSkill.native_scope) return false;
|
|
3049
|
+
if (nativeLocalReady(cloudSkill, localSkill)) return false;
|
|
3050
|
+
const nativePrevious = previousNativeState(previousState, cloudSkill);
|
|
3051
|
+
return localSkill.nativeFilesCurrent === true && localSkill.folderHash === localSkill.nativeBaseFolderHash || !localSkill.nativeReference && nativePrevious?.cloudId === cloudSkill.id && nativePrevious.folderHash === localSkill.folderHash;
|
|
3052
|
+
}
|
|
2529
3053
|
const previous = previousState.skills[skillName];
|
|
2530
3054
|
if (previous?.folderHash === localSkill.folderHash && previous.cloudContentHash === cloudContentHash(cloudSkill)) return false;
|
|
2531
3055
|
if (previous && previous.cloudContentHash === void 0 && previous.cloudId === cloudSkill.id && previous.appliedCloudFolderHash !== void 0 && previous.appliedCloudFolderHash === cloudHash && previous.cloudUpdatedAt === cloudSkill.updated_at && previous.folderHash === localSkill.folderHash) {
|
|
@@ -2551,17 +3075,32 @@ function collectAppliedFiles(pullResponse, previousState, appliedFilesByName) {
|
|
|
2551
3075
|
}
|
|
2552
3076
|
return applied;
|
|
2553
3077
|
}
|
|
2554
|
-
function buildSyncState(pullResponse, localSkills, lastSyncedAt, verifiedAgentLinks = {}, failedContentNames = /* @__PURE__ */ new Set(), appliedRevisions = {}, appliedFiles = {}) {
|
|
3078
|
+
function buildSyncState(pullResponse, localSkills, lastSyncedAt, verifiedAgentLinks = {}, failedContentNames = /* @__PURE__ */ new Set(), appliedRevisions = {}, appliedFiles = {}, previousState = { version: 1, lastSyncedAt: null, skills: {} }) {
|
|
2555
3079
|
const localSkillMap = toSkillMap(localSkills);
|
|
2556
3080
|
const skills = Object.fromEntries(
|
|
2557
3081
|
selectCloudSkillsToApply(pullResponse.skills).map((skill) => {
|
|
2558
3082
|
const localSkill = localSkillMap.get(skill.name);
|
|
2559
3083
|
const appliedCloudFolderHash = appliedRevisions[skill.name];
|
|
2560
3084
|
const appliedFileList = appliedFiles[skill.name];
|
|
3085
|
+
if (pendingLegacyUpgrade(skill, localSkill, previousState)) {
|
|
3086
|
+
const { nativeUnavailable: _unavailable, ...previous } = previousNativeState(previousState, skill);
|
|
3087
|
+
return [skill.name, { ...previous, verifiedAgentLinks: verifiedAgentLinks[skill.name] ?? {} }];
|
|
3088
|
+
}
|
|
3089
|
+
if (isNativeSkill(skill) && !nativeLocalReady(skill, localSkill)) {
|
|
3090
|
+
const previous = previousNativeState(previousState, skill);
|
|
3091
|
+
return [skill.name, { ...previous || {
|
|
3092
|
+
cloudId: skill.id,
|
|
3093
|
+
folderHash: localSkill?.nativeBaseFolderHash || "",
|
|
3094
|
+
agentTargets: normalizeAgentTargets(skill.agent_targets),
|
|
3095
|
+
syncedAt: lastSyncedAt || (/* @__PURE__ */ new Date()).toISOString(),
|
|
3096
|
+
...localSkill?.nativeReference ? { nativeReference: localSkill.nativeReference, nativeScope: localSkill.nativeScope } : {}
|
|
3097
|
+
}, nativeUnavailable: true, verifiedAgentLinks: {} }];
|
|
3098
|
+
}
|
|
2561
3099
|
return [
|
|
2562
3100
|
skill.name,
|
|
2563
3101
|
{
|
|
2564
3102
|
cloudId: skill.id,
|
|
3103
|
+
...nativeState(skill),
|
|
2565
3104
|
folderHash: localSkill?.folderHash || skill.skill_folder_hash || "",
|
|
2566
3105
|
agentTargets: normalizeAgentTargets(skill.agent_targets),
|
|
2567
3106
|
verifiedAgentLinks: skill.status === "active" ? verifiedAgentLinks[skill.name] ?? {} : {},
|
|
@@ -2574,17 +3113,30 @@ function buildSyncState(pullResponse, localSkills, lastSyncedAt, verifiedAgentLi
|
|
|
2574
3113
|
];
|
|
2575
3114
|
})
|
|
2576
3115
|
);
|
|
2577
|
-
|
|
3116
|
+
for (const local of localSkills) {
|
|
3117
|
+
if (!local.nativeReference || Object.values(skills).some((row) => row.cloudId === local.cloudId)) continue;
|
|
3118
|
+
skills[local.name] = {
|
|
3119
|
+
cloudId: local.cloudId,
|
|
3120
|
+
nativeReference: local.nativeReference,
|
|
3121
|
+
nativeScope: local.nativeScope,
|
|
3122
|
+
nativeUnavailable: true,
|
|
3123
|
+
verifiedAgentLinks: {},
|
|
3124
|
+
folderHash: local.nativeBaseFolderHash || "",
|
|
3125
|
+
agentTargets: normalizeAgentTargets(),
|
|
3126
|
+
syncedAt: lastSyncedAt || (/* @__PURE__ */ new Date()).toISOString()
|
|
3127
|
+
};
|
|
3128
|
+
}
|
|
3129
|
+
return retainMissingNativeState(previousState, {
|
|
2578
3130
|
version: 1,
|
|
2579
3131
|
lastSyncedAt,
|
|
2580
3132
|
skills
|
|
2581
|
-
};
|
|
3133
|
+
});
|
|
2582
3134
|
}
|
|
2583
3135
|
function buildLocalSymlinkCandidates(pullResponse, localSkills, previousState) {
|
|
2584
3136
|
const cloudSkillNames = new Set(
|
|
2585
3137
|
pullResponse.skills.map((skill) => skill.name)
|
|
2586
3138
|
);
|
|
2587
|
-
const localOnlySkills = localSkills.filter((skill) => !cloudSkillNames.has(skill.name)).map((skill) => {
|
|
3139
|
+
const localOnlySkills = localSkills.filter((skill) => !cloudSkillNames.has(skill.name)).filter((skill) => !skill.nativeReference && !previousState.skills[skill.name]?.nativeReference && !previousState.skills[skill.name]?.nativeUnavailable && !hasNativeFolderHistory(previousState, skill.name) && !/^native-[a-f0-9-]{36}$/.test(skill.name)).map((skill) => {
|
|
2588
3140
|
const previous = previousState.skills[skill.name];
|
|
2589
3141
|
return {
|
|
2590
3142
|
id: previous?.cloudId || `local-${skill.name}`,
|
|
@@ -2597,7 +3149,7 @@ function buildLocalSymlinkCandidates(pullResponse, localSkills, previousState) {
|
|
|
2597
3149
|
status: "active"
|
|
2598
3150
|
};
|
|
2599
3151
|
});
|
|
2600
|
-
return [...pullResponse
|
|
3152
|
+
return [...nativeLinkRows(pullResponse, localSkills, previousState), ...localOnlySkills];
|
|
2601
3153
|
}
|
|
2602
3154
|
function isEmptySyncState(state) {
|
|
2603
3155
|
return state.lastSyncedAt === null && Object.keys(state.skills).length === 0;
|
|
@@ -2624,14 +3176,20 @@ function applyLegacyFirstRunState(localSkills, scopedState, legacyState) {
|
|
|
2624
3176
|
skills: migratedSkills
|
|
2625
3177
|
};
|
|
2626
3178
|
}
|
|
2627
|
-
async function writePulledSkillsToScopedMirror(pullResponse, localSkills, previousState, syncPaths, deps, failures = [], writtenSkillNames = /* @__PURE__ */ new Set(), appliedFilesByName = {}) {
|
|
3179
|
+
async function writePulledSkillsToScopedMirror(pullResponse, localSkills, previousState, syncPaths, deps, failures = [], writtenSkillNames = /* @__PURE__ */ new Set(), appliedFilesByName = {}, acknowledgedNative = /* @__PURE__ */ new Map()) {
|
|
2628
3180
|
const localSkillMap = toSkillMap(localSkills);
|
|
2629
3181
|
const warnSkillSync = (message, error) => {
|
|
2630
3182
|
console.warn(`[Notis] ${message}`, error);
|
|
2631
3183
|
};
|
|
2632
3184
|
let downloaded = 0;
|
|
2633
3185
|
for (const cloudSkill of selectCloudSkillsToApply(pullResponse.skills)) {
|
|
2634
|
-
|
|
3186
|
+
const local = localSkillMap.get(cloudSkill.name);
|
|
3187
|
+
const acknowledged = isNativeSkill(cloudSkill) && local && acknowledgedNative.get(cloudSkill.id) === local.folderHash;
|
|
3188
|
+
const legacyBaseline = Boolean(local && pendingLegacyUpgrade(cloudSkill, local, previousState) && previousNativeState(previousState, cloudSkill)?.folderHash === local.folderHash);
|
|
3189
|
+
if (!acknowledged && !shouldWriteCloudSkill(cloudSkill, localSkillMap, previousState)) {
|
|
3190
|
+
if (isNativeSkill(cloudSkill) && !nativeLocalReady(cloudSkill, local)) {
|
|
3191
|
+
failures.push({ name: cloudSkill.name, error: "Local native Skill changes were retained; resolve the version or identity conflict before using them." });
|
|
3192
|
+
}
|
|
2635
3193
|
continue;
|
|
2636
3194
|
}
|
|
2637
3195
|
const outcome = await writeCloudSkillWithBundleFallback(cloudSkill, {
|
|
@@ -2639,7 +3197,9 @@ async function writePulledSkillsToScopedMirror(pullResponse, localSkills, previo
|
|
|
2639
3197
|
writeCloudSkillToDisk: (skill, bundleBytes) => deps.writeCloudSkillToDisk(skill, bundleBytes, syncPaths, {
|
|
2640
3198
|
// What the last write put there. Everything else in the folder was
|
|
2641
3199
|
// produced locally and survives this one.
|
|
2642
|
-
previouslyApplied: previousState
|
|
3200
|
+
previouslyApplied: previousNativeState(previousState, skill)?.appliedFiles,
|
|
3201
|
+
...isNativeSkill(skill) && local ? { expectedFolderHash: local.folderHash } : {},
|
|
3202
|
+
...legacyBaseline ? { legacyBaseline } : {}
|
|
2643
3203
|
}),
|
|
2644
3204
|
onWarning: warnSkillSync
|
|
2645
3205
|
});
|
|
@@ -2656,20 +3216,26 @@ async function writePulledSkillsToScopedMirror(pullResponse, localSkills, previo
|
|
|
2656
3216
|
return downloaded;
|
|
2657
3217
|
}
|
|
2658
3218
|
function assertSkillsPullAuthorized(pullResponse) {
|
|
3219
|
+
if (!Array.isArray(pullResponse.skills)) throw new Error("Skill inventory is unavailable; existing files were retained.");
|
|
3220
|
+
assertNativePull(pullResponse);
|
|
2659
3221
|
if (pullResponse.entitlement_access?.code === "entitlement_upgrade_required" && pullResponse.entitlement_access.entitlement === "skills") {
|
|
2660
3222
|
throw new Error(
|
|
2661
3223
|
"Skill sync access was denied; preserving existing local skills."
|
|
2662
3224
|
);
|
|
2663
3225
|
}
|
|
2664
3226
|
}
|
|
2665
|
-
async function deactivateDeletedAgentSkills(serverUrl, jwt, pullResponse, previousState, scopedState, skillsDir, deps, failures) {
|
|
3227
|
+
async function deactivateDeletedAgentSkills(serverUrl, jwt, pullResponse, previousState, scopedState, skillsDir, deps, failures, linkOptions) {
|
|
2666
3228
|
if (isEmptySyncState(scopedState)) {
|
|
2667
3229
|
return 0;
|
|
2668
3230
|
}
|
|
2669
3231
|
const deletions = await deps.detectDeletedAgentSymlinks(
|
|
2670
|
-
pullResponse.skills
|
|
3232
|
+
pullResponse.skills.map((skill) => {
|
|
3233
|
+
const previous = isNativeSkill(skill) ? Object.entries(previousState.skills).find(([, row]) => row.cloudId === skill.id) : void 0;
|
|
3234
|
+
return previous ? { ...skill, name: previous[0] } : skill;
|
|
3235
|
+
}),
|
|
2671
3236
|
previousState,
|
|
2672
|
-
skillsDir
|
|
3237
|
+
skillsDir,
|
|
3238
|
+
linkOptions
|
|
2673
3239
|
);
|
|
2674
3240
|
if (deletions.length === 0) {
|
|
2675
3241
|
return 0;
|
|
@@ -2685,21 +3251,34 @@ async function deactivateDeletedAgentSkills(serverUrl, jwt, pullResponse, previo
|
|
|
2685
3251
|
}
|
|
2686
3252
|
const fresh = withoutBaseSkills(await deps.pullSkills(serverUrl, jwt));
|
|
2687
3253
|
assertSkillsPullAuthorized(fresh);
|
|
3254
|
+
assertSyncEnvironment(fresh, pullResponse);
|
|
2688
3255
|
Object.assign(pullResponse, fresh);
|
|
2689
3256
|
let needsRefresh = false;
|
|
2690
3257
|
let deactivated = 0;
|
|
2691
3258
|
for (const [skillId, { skillName, agents }] of agentsBySkill) {
|
|
2692
3259
|
const skill = pullResponse.skills.find((item) => item.id === skillId);
|
|
2693
3260
|
const previous = previousState.skills[skillName];
|
|
2694
|
-
if (!skill
|
|
3261
|
+
if (!skill) continue;
|
|
3262
|
+
const native = isNativeSkill(skill);
|
|
3263
|
+
if (native) {
|
|
3264
|
+
if (!skill.native_settings || previous?.nativeSettingsRevision !== skill.native_settings.revision) continue;
|
|
3265
|
+
} else if (!skill.updated_at || previous?.cloudUpdatedAt !== skill.updated_at) continue;
|
|
2695
3266
|
const patch = Object.fromEntries([...agents].map((agent) => [agent, false]));
|
|
2696
3267
|
try {
|
|
2697
|
-
const saved = await deps.updateAgentTargets(
|
|
2698
|
-
|
|
3268
|
+
const saved = await deps.updateAgentTargets(
|
|
3269
|
+
serverUrl,
|
|
3270
|
+
jwt,
|
|
3271
|
+
skillId,
|
|
3272
|
+
patch,
|
|
3273
|
+
native ? void 0 : skill.updated_at,
|
|
3274
|
+
native ? { reference: skill.native_reference, settingsRevision: skill.native_settings.revision } : void 0
|
|
3275
|
+
);
|
|
3276
|
+
if (saved.success !== true || !saved.updated_at?.trim() || !native && saved.updated_at === skill.updated_at || !["notis", "claude_code", "cursor", "codex"].every((agent) => typeof saved.agent_targets?.[agent] === "boolean") || ![...agents].every((agent) => saved.agent_targets[agent] === false)) {
|
|
2699
3277
|
throw new Error("Assignment update did not return a verified saved revision");
|
|
2700
3278
|
}
|
|
2701
3279
|
skill.agent_targets = saved.agent_targets;
|
|
2702
3280
|
skill.updated_at = saved.updated_at;
|
|
3281
|
+
if (native) needsRefresh = true;
|
|
2703
3282
|
deactivated += agents.size;
|
|
2704
3283
|
} catch (error) {
|
|
2705
3284
|
needsRefresh = true;
|
|
@@ -2710,14 +3289,17 @@ async function deactivateDeletedAgentSkills(serverUrl, jwt, pullResponse, previo
|
|
|
2710
3289
|
if (needsRefresh) {
|
|
2711
3290
|
const refreshed = withoutBaseSkills(await deps.pullSkills(serverUrl, jwt));
|
|
2712
3291
|
assertSkillsPullAuthorized(refreshed);
|
|
3292
|
+
assertSyncEnvironment(refreshed, pullResponse);
|
|
2713
3293
|
Object.assign(pullResponse, refreshed);
|
|
2714
3294
|
}
|
|
2715
3295
|
return deactivated;
|
|
2716
3296
|
}
|
|
2717
3297
|
async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
|
|
3298
|
+
const linkAgentFolders = options.linkAgentFolders !== false;
|
|
2718
3299
|
const deps = {
|
|
2719
3300
|
...DEFAULT_RUN_SKILL_SYNC_DEPS,
|
|
2720
|
-
...dependencies
|
|
3301
|
+
...dependencies,
|
|
3302
|
+
...linkAgentFolders ? {} : MIRROR_ONLY_DEPS
|
|
2721
3303
|
};
|
|
2722
3304
|
const syncSettings = await deps.fetchSyncSettings(
|
|
2723
3305
|
serverUrl,
|
|
@@ -2729,11 +3311,12 @@ async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
|
|
|
2729
3311
|
"Cannot sync skills without a server-verified account identity."
|
|
2730
3312
|
);
|
|
2731
3313
|
}
|
|
2732
|
-
const syncPaths = getSkillSyncPathsForUser(syncUserId);
|
|
2733
|
-
const foreignLinksRemoved = await deps.removeForeignAccountSymlinks(
|
|
2734
|
-
syncPaths.skillsDir
|
|
2735
|
-
);
|
|
3314
|
+
const syncPaths = getSkillSyncPathsForUser(syncUserId, void 0, syncSettings.sync_namespace, options.syncHome);
|
|
2736
3315
|
if (options.honorSyncEnabled !== false && !syncSettings.sync_enabled) {
|
|
3316
|
+
const foreignLinksRemoved2 = await deps.removeForeignAccountSymlinks(
|
|
3317
|
+
syncPaths.skillsDir,
|
|
3318
|
+
isolatedLinkOptions(syncPaths)
|
|
3319
|
+
);
|
|
2737
3320
|
return {
|
|
2738
3321
|
syncEnabled: false,
|
|
2739
3322
|
pushed: 0,
|
|
@@ -2742,7 +3325,7 @@ async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
|
|
|
2742
3325
|
deleted: 0,
|
|
2743
3326
|
deactivated: 0,
|
|
2744
3327
|
linked: 0,
|
|
2745
|
-
removed:
|
|
3328
|
+
removed: foreignLinksRemoved2,
|
|
2746
3329
|
skipped: 0,
|
|
2747
3330
|
lastSyncedAt: syncSettings.last_synced_at,
|
|
2748
3331
|
failedPushes: []
|
|
@@ -2750,13 +3333,21 @@ async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
|
|
|
2750
3333
|
}
|
|
2751
3334
|
let pullResponse = withoutBaseSkills(await deps.pullSkills(serverUrl, jwt));
|
|
2752
3335
|
assertSkillsPullAuthorized(pullResponse);
|
|
3336
|
+
assertSyncEnvironment(pullResponse, syncSettings);
|
|
3337
|
+
const foreignLinksRemoved = await deps.removeForeignAccountSymlinks(
|
|
3338
|
+
syncPaths.skillsDir,
|
|
3339
|
+
isolatedLinkOptions(syncPaths)
|
|
3340
|
+
);
|
|
3341
|
+
if (linkAgentFolders && !syncPaths.isolatedNamespace) {
|
|
3342
|
+
await forgetOtherAccountsAgentLinks(syncPaths);
|
|
3343
|
+
}
|
|
2753
3344
|
const cloudCuratedSkillNames = new Set(
|
|
2754
3345
|
pullResponse.skills.filter((skill) => skill.source === "curated").map((skill) => skill.name)
|
|
2755
3346
|
);
|
|
2756
3347
|
const protectedSkillNames = /* @__PURE__ */ new Set([...cloudCuratedSkillNames, ...BASE_SKILL_NAMES]);
|
|
2757
3348
|
const scopedState = withoutBaseSkillState(await deps.readSyncState(syncPaths));
|
|
2758
3349
|
const assignmentFailures = [];
|
|
2759
|
-
const deactivated = syncSettings.agent_targets_conditional_updates === true ? await deactivateDeletedAgentSkills(
|
|
3350
|
+
const deactivated = linkAgentFolders && !syncPaths.isolatedNamespace && syncSettings.agent_targets_conditional_updates === true ? await deactivateDeletedAgentSkills(
|
|
2760
3351
|
serverUrl,
|
|
2761
3352
|
jwt,
|
|
2762
3353
|
pullResponse,
|
|
@@ -2764,41 +3355,55 @@ async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
|
|
|
2764
3355
|
scopedState,
|
|
2765
3356
|
syncPaths.skillsDir,
|
|
2766
3357
|
deps,
|
|
2767
|
-
assignmentFailures
|
|
3358
|
+
assignmentFailures,
|
|
3359
|
+
isolatedLinkOptions(syncPaths)
|
|
2768
3360
|
) : 0;
|
|
3361
|
+
assertSyncEnvironment(pullResponse, syncSettings);
|
|
2769
3362
|
const authUserId = decodeJwtSubject(jwt);
|
|
2770
3363
|
let previousAuthState = null;
|
|
2771
|
-
if (authUserId && authUserId !== syncUserId) {
|
|
2772
|
-
const previousAuthPaths = getSkillSyncPathsForUser(authUserId);
|
|
3364
|
+
if (!syncPaths.isolatedNamespace && authUserId && authUserId !== syncUserId) {
|
|
3365
|
+
const previousAuthPaths = getSkillSyncPathsForUser(authUserId, void 0, void 0, options.syncHome);
|
|
2773
3366
|
previousAuthState = await deps.readSyncState(previousAuthPaths);
|
|
2774
3367
|
await deps.gatherTopLevelLocalSkills(syncPaths, {
|
|
2775
3368
|
sourceRoots: [{ label: "previous-auth-scope", root: previousAuthPaths.skillsDir }],
|
|
2776
3369
|
protectedSkillNames
|
|
2777
3370
|
});
|
|
2778
3371
|
}
|
|
2779
|
-
|
|
2780
|
-
protectedSkillNames
|
|
2781
|
-
}
|
|
3372
|
+
if (linkAgentFolders && !syncPaths.isolatedNamespace) {
|
|
3373
|
+
await deps.gatherTopLevelLocalSkills(syncPaths, { protectedSkillNames });
|
|
3374
|
+
}
|
|
2782
3375
|
const localSkills = (await deps.scanLocalSkills(syncPaths)).filter((skill) => !BASE_SKILL_NAMES.has(skill.name));
|
|
2783
3376
|
const previousState = withoutBaseSkillState(applyLegacyFirstRunState(
|
|
2784
3377
|
localSkills,
|
|
2785
3378
|
scopedState,
|
|
2786
|
-
isEmptySyncState(scopedState) ? !previousAuthState || isEmptySyncState(previousAuthState) ? await deps.readLegacySyncState(syncPaths) : previousAuthState : null
|
|
3379
|
+
!syncPaths.isolatedNamespace && isEmptySyncState(scopedState) ? !previousAuthState || isEmptySyncState(previousAuthState) ? await deps.readLegacySyncState(syncPaths) : previousAuthState : null
|
|
2787
3380
|
));
|
|
3381
|
+
pullResponse = bindNativeFolders(pullResponse, localSkills, previousState);
|
|
2788
3382
|
const gatheredSymlinkResult = await deps.syncSymlinks(
|
|
2789
3383
|
buildLocalSymlinkCandidates(pullResponse, localSkills, previousState),
|
|
2790
|
-
syncPaths.skillsDir
|
|
3384
|
+
syncPaths.skillsDir,
|
|
3385
|
+
isolatedLinkOptions(syncPaths)
|
|
2791
3386
|
);
|
|
2792
3387
|
const pushCandidates = getPushCandidates(
|
|
2793
3388
|
localSkills,
|
|
2794
3389
|
previousState,
|
|
2795
3390
|
cloudCuratedSkillNames,
|
|
2796
3391
|
new Set(pullResponse.skills.map((skill) => skill.name)),
|
|
2797
|
-
|
|
3392
|
+
pullResponse.skills
|
|
2798
3393
|
);
|
|
2799
3394
|
const failedPushes = [];
|
|
3395
|
+
const acknowledgedNative = /* @__PURE__ */ new Map();
|
|
3396
|
+
let writeLocalSkills = localSkills;
|
|
2800
3397
|
if (pushCandidates.length > 0) {
|
|
2801
3398
|
const pushResult = await deps.pushChangedSkills(serverUrl, jwt, pushCandidates);
|
|
3399
|
+
for (const result of pushResult.skills || []) {
|
|
3400
|
+
const saved = result;
|
|
3401
|
+
const candidate = pushCandidates.find((local) => local.nativeReference && local.cloudId === saved.id);
|
|
3402
|
+
if (candidate && saved.native_reference) {
|
|
3403
|
+
checkedNativeReference(saved.native_reference, candidate.cloudId);
|
|
3404
|
+
acknowledgedNative.set(candidate.cloudId, candidate.folderHash);
|
|
3405
|
+
}
|
|
3406
|
+
}
|
|
2802
3407
|
if (Array.isArray(pushResult?.failed) && pushResult.failed.length > 0) {
|
|
2803
3408
|
failedPushes.push(...pushResult.failed);
|
|
2804
3409
|
console.warn(
|
|
@@ -2807,13 +3412,21 @@ async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
|
|
|
2807
3412
|
}
|
|
2808
3413
|
pullResponse = withoutBaseSkills(await deps.pullSkills(serverUrl, jwt));
|
|
2809
3414
|
assertSkillsPullAuthorized(pullResponse);
|
|
3415
|
+
assertSyncEnvironment(pullResponse, syncSettings);
|
|
3416
|
+
writeLocalSkills = (await deps.scanLocalSkills(syncPaths)).filter((skill) => !BASE_SKILL_NAMES.has(skill.name));
|
|
3417
|
+
pullResponse = bindNativeFolders(pullResponse, writeLocalSkills, previousState);
|
|
2810
3418
|
}
|
|
2811
3419
|
const cloudSkillNames = new Set(pullResponse.skills.map((s) => s.name));
|
|
2812
3420
|
let deleted = 0;
|
|
2813
3421
|
for (const skillName of Object.keys(previousState.skills)) {
|
|
2814
3422
|
if (!cloudSkillNames.has(skillName)) {
|
|
3423
|
+
const previous = previousState.skills[skillName];
|
|
3424
|
+
if (previous.nativeReference || previous.nativeUnavailable || pullResponse.skills.some((skill) => isNativeSkill(skill) && skill.id === previous.cloudId)) {
|
|
3425
|
+
await deps.removeAllSymlinksForSkill(skillName, syncPaths.skillsDir, isolatedLinkOptions(syncPaths));
|
|
3426
|
+
continue;
|
|
3427
|
+
}
|
|
2815
3428
|
await deps.deleteLocalSkill(skillName, syncPaths);
|
|
2816
|
-
await deps.removeAllSymlinksForSkill(skillName, syncPaths.skillsDir);
|
|
3429
|
+
await deps.removeAllSymlinksForSkill(skillName, syncPaths.skillsDir, isolatedLinkOptions(syncPaths));
|
|
2817
3430
|
deleted += 1;
|
|
2818
3431
|
}
|
|
2819
3432
|
}
|
|
@@ -2822,18 +3435,20 @@ async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
|
|
|
2822
3435
|
const appliedFilesByName = {};
|
|
2823
3436
|
const downloaded = await writePulledSkillsToScopedMirror(
|
|
2824
3437
|
pullResponse,
|
|
2825
|
-
|
|
3438
|
+
writeLocalSkills,
|
|
2826
3439
|
previousState,
|
|
2827
3440
|
syncPaths,
|
|
2828
3441
|
deps,
|
|
2829
3442
|
failedDownloads,
|
|
2830
3443
|
writtenSkillNames,
|
|
2831
|
-
appliedFilesByName
|
|
3444
|
+
appliedFilesByName,
|
|
3445
|
+
acknowledgedNative
|
|
2832
3446
|
);
|
|
2833
3447
|
const finalLocalSkills = (await deps.scanLocalSkills(syncPaths)).filter((skill) => !BASE_SKILL_NAMES.has(skill.name));
|
|
2834
3448
|
const symlinkResult = await deps.syncSymlinks(
|
|
2835
3449
|
buildLocalSymlinkCandidates(pullResponse, finalLocalSkills, previousState),
|
|
2836
|
-
syncPaths.skillsDir
|
|
3450
|
+
syncPaths.skillsDir,
|
|
3451
|
+
isolatedLinkOptions(syncPaths)
|
|
2837
3452
|
);
|
|
2838
3453
|
const verifiedLinks = { ...symlinkResult.verifiedAgentLinks ?? {} };
|
|
2839
3454
|
for (const failure of failedDownloads) delete verifiedLinks[failure.name];
|
|
@@ -2846,7 +3461,8 @@ async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
|
|
|
2846
3461
|
verifiedLinks,
|
|
2847
3462
|
new Set(failedDownloads.map((item) => item.name)),
|
|
2848
3463
|
collectAppliedCloudRevisions(pullResponse, previousState, writtenSkillNames),
|
|
2849
|
-
collectAppliedFiles(pullResponse, previousState, appliedFilesByName)
|
|
3464
|
+
collectAppliedFiles(pullResponse, previousState, appliedFilesByName),
|
|
3465
|
+
previousState
|
|
2850
3466
|
),
|
|
2851
3467
|
syncPaths
|
|
2852
3468
|
);
|
|
@@ -2869,20 +3485,20 @@ async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
|
|
|
2869
3485
|
}
|
|
2870
3486
|
|
|
2871
3487
|
// src/runtime/sync-skills.js
|
|
2872
|
-
import { createHash as
|
|
3488
|
+
import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
|
|
2873
3489
|
import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
2874
|
-
import { homedir as
|
|
2875
|
-
import { dirname as
|
|
3490
|
+
import { homedir as homedir4 } from "node:os";
|
|
3491
|
+
import { dirname as dirname7, join as join7 } from "node:path";
|
|
2876
3492
|
|
|
2877
3493
|
// src/runtime/base-skills.js
|
|
2878
|
-
import { dirname as
|
|
3494
|
+
import { dirname as dirname6, join as join6, relative, resolve as resolve3 } from "node:path";
|
|
2879
3495
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
2880
3496
|
var BASE_SKILL_NAMES2 = Object.freeze([
|
|
2881
3497
|
"notis-apps",
|
|
2882
3498
|
"notis-query",
|
|
2883
3499
|
"notis-cli"
|
|
2884
3500
|
]);
|
|
2885
|
-
var HERE =
|
|
3501
|
+
var HERE = dirname6(fileURLToPath2(import.meta.url));
|
|
2886
3502
|
|
|
2887
3503
|
// src/runtime/sync-skills.js
|
|
2888
3504
|
var DEFAULT_LOCK_TIMEOUT_MS = 3e4;
|
|
@@ -2891,7 +3507,7 @@ var DEFAULT_LOCK_POLL_MS = 50;
|
|
|
2891
3507
|
async function lockSnapshot(lockDirectory) {
|
|
2892
3508
|
try {
|
|
2893
3509
|
const [raw, metadata] = await Promise.all([
|
|
2894
|
-
readFile(
|
|
3510
|
+
readFile(join7(lockDirectory, "owner"), "utf8").catch(() => ""),
|
|
2895
3511
|
stat(lockDirectory)
|
|
2896
3512
|
]);
|
|
2897
3513
|
let owner = {};
|
|
@@ -2924,14 +3540,14 @@ function processIsAlive2(pid) {
|
|
|
2924
3540
|
}
|
|
2925
3541
|
}
|
|
2926
3542
|
function delay(milliseconds) {
|
|
2927
|
-
return new Promise((
|
|
3543
|
+
return new Promise((resolve4) => setTimeout(resolve4, milliseconds));
|
|
2928
3544
|
}
|
|
2929
3545
|
async function quarantineStaleLock(lockDirectory, snapshot) {
|
|
2930
|
-
const quarantineRoot =
|
|
2931
|
-
const snapshotToken =
|
|
3546
|
+
const quarantineRoot = join7(dirname7(lockDirectory), ".stale-operation-locks");
|
|
3547
|
+
const snapshotToken = createHash5("sha256").update(JSON.stringify(snapshot)).digest("hex");
|
|
2932
3548
|
await mkdir(quarantineRoot, { recursive: true, mode: 448 });
|
|
2933
3549
|
try {
|
|
2934
|
-
await rename(lockDirectory,
|
|
3550
|
+
await rename(lockDirectory, join7(quarantineRoot, snapshotToken));
|
|
2935
3551
|
return true;
|
|
2936
3552
|
} catch (error) {
|
|
2937
3553
|
if (["EEXIST", "ENOTEMPTY", "ENOENT"].includes(error?.code)) return false;
|
|
@@ -2939,16 +3555,16 @@ async function quarantineStaleLock(lockDirectory, snapshot) {
|
|
|
2939
3555
|
}
|
|
2940
3556
|
}
|
|
2941
3557
|
async function writeLockOwnerAtomically(lockDirectory, owner) {
|
|
2942
|
-
const temporaryOwnerPath =
|
|
2943
|
-
const ownerPath =
|
|
3558
|
+
const temporaryOwnerPath = join7(lockDirectory, `.owner.${owner.id}.tmp`);
|
|
3559
|
+
const ownerPath = join7(lockDirectory, "owner");
|
|
2944
3560
|
await writeFile(temporaryOwnerPath, JSON.stringify(owner), { mode: 384 });
|
|
2945
3561
|
await rename(temporaryOwnerPath, ownerPath);
|
|
2946
3562
|
}
|
|
2947
3563
|
async function releaseOwnedLock(lockDirectory, ownerId) {
|
|
2948
3564
|
const owner = await lockSnapshot(lockDirectory);
|
|
2949
3565
|
if (owner?.id !== ownerId) return;
|
|
2950
|
-
const quarantineRoot =
|
|
2951
|
-
const releasedDirectory =
|
|
3566
|
+
const quarantineRoot = join7(dirname7(lockDirectory), ".stale-operation-locks");
|
|
3567
|
+
const releasedDirectory = join7(quarantineRoot, `released.${ownerId}`);
|
|
2952
3568
|
await mkdir(quarantineRoot, { recursive: true, mode: 448 });
|
|
2953
3569
|
try {
|
|
2954
3570
|
await rename(lockDirectory, releasedDirectory);
|
|
@@ -2959,16 +3575,16 @@ async function releaseOwnedLock(lockDirectory, ownerId) {
|
|
|
2959
3575
|
await rm(releasedDirectory, { recursive: true, force: true });
|
|
2960
3576
|
}
|
|
2961
3577
|
async function withSkillSyncLock(callback, {
|
|
2962
|
-
home =
|
|
3578
|
+
home = homedir4(),
|
|
2963
3579
|
timeoutMs = DEFAULT_LOCK_TIMEOUT_MS,
|
|
2964
3580
|
staleMs = DEFAULT_LOCK_STALE_MS,
|
|
2965
3581
|
pollMs = DEFAULT_LOCK_POLL_MS,
|
|
2966
3582
|
now = () => Date.now()
|
|
2967
3583
|
} = {}) {
|
|
2968
|
-
const lockDirectory =
|
|
2969
|
-
const ownerId = `${process.pid}.${
|
|
3584
|
+
const lockDirectory = join7(home, ".notis", "skills", ".operation-lock");
|
|
3585
|
+
const ownerId = `${process.pid}.${randomUUID3()}`;
|
|
2970
3586
|
const deadline = now() + timeoutMs;
|
|
2971
|
-
await mkdir(
|
|
3587
|
+
await mkdir(dirname7(lockDirectory), { recursive: true, mode: 448 });
|
|
2972
3588
|
for (; ; ) {
|
|
2973
3589
|
try {
|
|
2974
3590
|
await mkdir(lockDirectory, { mode: 448 });
|
|
@@ -3004,7 +3620,7 @@ async function withSkillSyncLock(callback, {
|
|
|
3004
3620
|
let heartbeatInFlight = Promise.resolve();
|
|
3005
3621
|
const refreshHeartbeat = async () => {
|
|
3006
3622
|
if (heartbeatStopped) return;
|
|
3007
|
-
const temporaryOwnerPath =
|
|
3623
|
+
const temporaryOwnerPath = join7(lockDirectory, `.owner.${ownerId}.tmp`);
|
|
3008
3624
|
await writeFile(
|
|
3009
3625
|
temporaryOwnerPath,
|
|
3010
3626
|
JSON.stringify({ id: ownerId, pid: process.pid, at: now() }),
|
|
@@ -3015,7 +3631,7 @@ async function withSkillSyncLock(callback, {
|
|
|
3015
3631
|
await rm(temporaryOwnerPath, { force: true });
|
|
3016
3632
|
return;
|
|
3017
3633
|
}
|
|
3018
|
-
await rename(temporaryOwnerPath,
|
|
3634
|
+
await rename(temporaryOwnerPath, join7(lockDirectory, "owner"));
|
|
3019
3635
|
};
|
|
3020
3636
|
const heartbeat = setInterval(() => {
|
|
3021
3637
|
heartbeatInFlight = heartbeatInFlight.then(refreshHeartbeat).catch(() => void 0);
|
|
@@ -3032,12 +3648,20 @@ async function withSkillSyncLock(callback, {
|
|
|
3032
3648
|
}
|
|
3033
3649
|
|
|
3034
3650
|
// src/skill-sync-worker.js
|
|
3651
|
+
function currentCliProfile() {
|
|
3652
|
+
try {
|
|
3653
|
+
return getCurrentProfileName(loadConfig());
|
|
3654
|
+
} catch {
|
|
3655
|
+
return null;
|
|
3656
|
+
}
|
|
3657
|
+
}
|
|
3035
3658
|
async function runAutomaticSkillSync({ profile, apiBase, userId }, {
|
|
3036
3659
|
resolveRuntime = resolveRuntimeProfile,
|
|
3037
3660
|
refresh = ensureFreshOAuthCredential,
|
|
3038
3661
|
settings = fetchSyncSettings,
|
|
3039
3662
|
sync = runSkillSync,
|
|
3040
|
-
lock = withSkillSyncLock
|
|
3663
|
+
lock = withSkillSyncLock,
|
|
3664
|
+
currentProfile = currentCliProfile
|
|
3041
3665
|
} = {}) {
|
|
3042
3666
|
const runtime = resolveRuntime({ profile }, { requireAuth: true });
|
|
3043
3667
|
if (runtime.credentialKind !== "oauth" || runtime.apiBase !== apiBase || runtime.oauthUserId !== userId) throw new Error("Automatic skill sync account changed; run notis skills sync to rebind");
|
|
@@ -3045,20 +3669,21 @@ async function runAutomaticSkillSync({ profile, apiBase, userId }, {
|
|
|
3045
3669
|
const saved = await settings(runtime.apiBase, runtime.jwt);
|
|
3046
3670
|
if (saved.user_id !== userId) throw new Error("Automatic skill sync identity mismatch");
|
|
3047
3671
|
if (!saved.sync_enabled) return { status: "disabled" };
|
|
3672
|
+
const linkAgentFolders = (currentProfile() ?? profile) === profile;
|
|
3048
3673
|
const result = await lock(() => sync(runtime.apiBase, runtime.jwt, {
|
|
3049
3674
|
fetchSyncSettings: async () => saved
|
|
3050
|
-
}, { honorSyncEnabled: true }));
|
|
3675
|
+
}, { honorSyncEnabled: true, ...linkAgentFolders ? {} : { linkAgentFolders: false } }));
|
|
3051
3676
|
return { status: result.failedLinks?.length || result.failedPushes?.length ? "partial" : "synced", ...result };
|
|
3052
3677
|
}
|
|
3053
3678
|
async function main(args = process.argv.slice(2)) {
|
|
3054
3679
|
const [profile, apiBase, userId] = args;
|
|
3055
|
-
const root =
|
|
3680
|
+
const root = join8(homedir5(), ".notis", "skills", "service");
|
|
3056
3681
|
const record = (value) => {
|
|
3057
|
-
|
|
3058
|
-
const target =
|
|
3682
|
+
mkdirSync5(root, { recursive: true, mode: 448 });
|
|
3683
|
+
const target = join8(root, "status.json");
|
|
3059
3684
|
const temporary = `${target}.${process.pid}.tmp`;
|
|
3060
|
-
|
|
3061
|
-
|
|
3685
|
+
writeFileSync5(temporary, JSON.stringify({ ...value, profile, at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2), { mode: 384 });
|
|
3686
|
+
renameSync5(temporary, target);
|
|
3062
3687
|
};
|
|
3063
3688
|
const deadline = setTimeout(() => {
|
|
3064
3689
|
record({ status: "error", code: "sync_timeout" });
|