@notis_ai/cli 0.2.32 → 0.2.33

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.
Files changed (81) hide show
  1. package/README.md +74 -9
  2. package/dist/agent-hooks/notis-agent-hook.mjs +4330 -891
  3. package/dist/base-skills/notis-cli/.notis-base-skill.json +1 -1
  4. package/dist/base-skills/notis-cli/SKILL.md +7 -3
  5. package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
  6. package/dist/base-skills/notis-spaces/SKILL.md +5 -3
  7. package/dist/base-skills/notis-spaces/references/comments.md +94 -0
  8. package/dist/base-skills/notis-spaces/references/context.md +20 -19
  9. package/dist/base-skills/notis-spaces/references/design.md +3 -2
  10. package/dist/base-skills/notis-spaces/references/sdk.md +135 -83
  11. package/dist/base-skills/notis-spaces/references/store.md +24 -1
  12. package/dist/sdk/src/components/SelectionActionBar.tsx +42 -7
  13. package/dist/sdk/src/components/SpaceTextComments.tsx +284 -0
  14. package/dist/sdk/src/config.ts +3 -1
  15. package/dist/sdk/src/functions.ts +203 -0
  16. package/dist/sdk/src/hooks/useAgentQueue.ts +17 -28
  17. package/dist/sdk/src/hooks/useCollectionInteractions.ts +7 -2
  18. package/dist/sdk/src/hooks/useConnection.ts +102 -0
  19. package/dist/sdk/src/hooks/useFunction.ts +42 -0
  20. package/dist/sdk/src/hooks/useNotisSettings.ts +101 -0
  21. package/dist/sdk/src/index.ts +15 -4
  22. package/dist/sdk/src/runtime.ts +16 -1
  23. package/dist/sdk/src/space.ts +333 -33
  24. package/dist/sdk/src/ui/comments/passageModel.ts +99 -0
  25. package/dist/sdk/src/ui/comments/textHighlights.ts +33 -0
  26. package/dist/skill-sync/index.js +239 -30
  27. package/dist/skill-sync-worker.mjs +453 -124
  28. package/dist/space-harness/host.js +213 -92
  29. package/dist/space-sdk/dist/chunk-4GWS2IFO.js +3 -0
  30. package/dist/space-sdk/dist/index.js +3 -3
  31. package/dist/space-sdk/dist/ui.js +8 -7
  32. package/dist/space-sdk/src/config.ts +3 -1
  33. package/dist/space-sdk/src/functions.ts +203 -0
  34. package/dist/space-sdk/src/hooks/useAgentQueue.d.ts +2 -13
  35. package/dist/space-sdk/src/hooks/useCollectionInteractions.d.ts +2 -0
  36. package/dist/space-sdk/src/hooks/useConnection.d.ts +42 -0
  37. package/dist/space-sdk/src/hooks/useFunction.d.ts +20 -0
  38. package/dist/space-sdk/src/hooks/useNotisSettings.d.ts +48 -0
  39. package/dist/space-sdk/src/index.d.ts +10 -4
  40. package/dist/space-sdk/src/runtime.d.ts +14 -1
  41. package/dist/space-sdk/src/space.ts +333 -33
  42. package/dist/space-sdk/src/tailwind-candidates.d.ts +185 -152
  43. package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +7 -4
  44. package/dist/space-sdk/src/ui/comments/agentRuntime.d.ts +10 -2
  45. package/dist/space-sdk/src/ui/comments/commentModel.d.ts +55 -88
  46. package/dist/space-sdk/src/ui/comments/commentWords.d.ts +9 -0
  47. package/dist/space-sdk/src/ui/comments/hostComments.d.ts +13 -9
  48. package/dist/space-sdk/src/ui/comments/index.d.ts +1 -1
  49. package/dist/space-sdk/src/ui/comments/paneParts.d.ts +27 -5
  50. package/dist/space-sdk/src/ui/comments/passageModel.d.ts +12 -36
  51. package/dist/space-sdk/src/ui/comments/useCommentRouting.d.ts +26 -4
  52. package/dist/space-sdk/src/ui/comments/useComments.d.ts +64 -74
  53. package/dist/space-sdk/src/ui/comments/usePassageComments.d.ts +8 -4
  54. package/dist/space-sdk/src/ui/index.d.ts +1 -1
  55. package/dist/space-sdk/src/ui/layout/SidePane.d.ts +3 -4
  56. package/dist/space-sdk/src/ui/period/dateFormat.d.ts +27 -8
  57. package/dist/view-renderer/dist/host.js +280 -159
  58. package/package.json +3 -3
  59. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +2 -2
  60. package/skills/notis-spaces/cli.md +3 -3
  61. package/src/cli.js +2 -1
  62. package/src/command-specs/index.js +3 -0
  63. package/src/command-specs/repository-secrets.js +171 -0
  64. package/src/command-specs/spaces.js +3 -3
  65. package/src/runtime/agent-credential.js +175 -0
  66. package/src/runtime/agent-identity.js +92 -15
  67. package/src/runtime/app-platform.js +8 -0
  68. package/src/runtime/auth-recovery.js +14 -0
  69. package/src/runtime/profiles.js +15 -0
  70. package/src/runtime/skill-sync/index.ts +3 -2
  71. package/src/runtime/skill-sync/symlink-manager.ts +354 -35
  72. package/src/runtime/skill-sync/types.ts +10 -1
  73. package/src/runtime/space-functions.js +211 -0
  74. package/src/runtime/space-platform.js +12 -3
  75. package/src/runtime/space-source.js +116 -13
  76. package/src/runtime/space-test-server.js +22 -4
  77. package/src/runtime/space-verification.js +3 -1
  78. package/src/runtime/transport.js +15 -0
  79. package/dist/sdk/src/components/NotisCommentBoundary.tsx +0 -132
  80. package/dist/space-sdk/dist/chunk-I4Z4UFGB.js +0 -3
  81. package/dist/space-sdk/src/components/NotisCommentBoundary.d.ts +0 -26
@@ -1,20 +1,20 @@
1
1
  // src/skill-sync-worker.js
2
- import { createHash as createHash6 } from "node:crypto";
3
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync5, renameSync as renameSync5, writeFileSync as writeFileSync5 } from "node:fs";
2
+ import { createHash as createHash7 } from "node:crypto";
3
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync6, renameSync as renameSync6, writeFileSync as writeFileSync6 } from "node:fs";
4
4
  import { homedir as homedir5 } from "node:os";
5
- import { join as join8 } from "node:path";
5
+ import { join as join9 } from "node:path";
6
6
 
7
7
  // src/runtime/profiles.js
8
- import { createHash } from "node:crypto";
8
+ import { createHash as createHash2 } from "node:crypto";
9
9
  import {
10
10
  existsSync as existsSync3,
11
- mkdirSync as mkdirSync2,
12
- readFileSync as readFileSync2,
13
- renameSync as renameSync2,
14
- writeFileSync as writeFileSync2
11
+ mkdirSync as mkdirSync3,
12
+ readFileSync as readFileSync3,
13
+ renameSync as renameSync3,
14
+ writeFileSync as writeFileSync3
15
15
  } from "node:fs";
16
16
  import { homedir as homedir2 } from "node:os";
17
- import { dirname as dirname2, join as join2, parse, resolve as resolve2 } from "node:path";
17
+ import { dirname as dirname3, join as join3, parse, resolve as resolve2 } from "node:path";
18
18
 
19
19
  // src/runtime/errors.js
20
20
  var EXIT_CODES = {
@@ -343,12 +343,45 @@ function resolveRetryEnabled(globalOptions = {}, env = process.env) {
343
343
  var AGENT_IDENTITY_ENV = {
344
344
  name: "NOTIS_AGENT_NAME",
345
345
  id: "NOTIS_AGENT_ID",
346
- thread: "NOTIS_AGENT_THREAD"
346
+ thread: "NOTIS_AGENT_THREAD",
347
+ threadName: "NOTIS_AGENT_THREAD_NAME",
348
+ harness: "NOTIS_AGENT_HARNESS"
347
349
  };
348
350
  var AGENT_NAME_MIN = 3;
349
351
  var AGENT_NAME_LIMIT = 60;
350
352
  var BAND_NAME_EXAMPLE = "fred-and-the-machine";
351
353
  var BAND_NAME_RULE = `a fresh lowercase imaginary rock-band name: lowercase letters and digits in at least two words joined by hyphens, ${AGENT_NAME_MIN} to ${AGENT_NAME_LIMIT} characters, such as ${BAND_NAME_EXAMPLE}`;
354
+ var RESERVED_BASES = [
355
+ "claude",
356
+ "claude-code",
357
+ "codex",
358
+ "cursor",
359
+ "cursor-agent",
360
+ "gemini",
361
+ "notis",
362
+ "t3",
363
+ "t3-code",
364
+ "opencode",
365
+ "agent",
366
+ "assistant",
367
+ "bot"
368
+ ];
369
+ var RESERVED_AGENT_NAMES = Object.freeze(new Set(
370
+ RESERVED_BASES.flatMap((base) => [base, `${base}-cli`, `${base}-agent`])
371
+ ));
372
+ function detectAgentHarness(env = process.env) {
373
+ const set = (name) => typeof env[name] === "string" && env[name].trim() !== "";
374
+ if (set("CLAUDECODE") || set("CLAUDE_CODE_ENTRYPOINT") || set("CLAUDE_CODE_SESSION_ID")) return "claude_code";
375
+ if (Object.keys(env).some((key) => key.startsWith("CODEX_") && key !== "CODEX_HOME" && set(key))) return "codex";
376
+ if (set("CURSOR_AGENT")) return "cursor_agent";
377
+ if (set("GEMINI_CLI")) return "gemini";
378
+ if (set("OPENCODE")) return "opencode";
379
+ const named = String(env.AI_AGENT ?? "").toLowerCase();
380
+ if (named.startsWith("claude")) return "claude_code";
381
+ if (named.startsWith("codex")) return "codex";
382
+ if (named.startsWith("cursor")) return "cursor_agent";
383
+ return null;
384
+ }
352
385
  function pick(flag, variable) {
353
386
  if (typeof flag === "string") return flag;
354
387
  return typeof variable === "string" ? variable : void 0;
@@ -359,13 +392,89 @@ function readAgentIdentity(globalOptions = {}, env = process.env) {
359
392
  id: pick(globalOptions.agentId, env[AGENT_IDENTITY_ENV.id]),
360
393
  thread: pick(globalOptions.agentThread, env[AGENT_IDENTITY_ENV.thread])
361
394
  };
362
- return Object.values(raw).some((value) => typeof value === "string" && value.trim()) ? raw : null;
395
+ const threadName = pick(globalOptions.agentThreadName, env[AGENT_IDENTITY_ENV.threadName]);
396
+ if (threadName !== void 0) raw.threadName = threadName;
397
+ if (!Object.values(raw).some((value) => typeof value === "string" && value.trim())) return null;
398
+ const harness = pick(void 0, env[AGENT_IDENTITY_ENV.harness]) ?? detectAgentHarness(env);
399
+ return harness ? { ...raw, harness } : raw;
400
+ }
401
+
402
+ // src/runtime/agent-credential.js
403
+ import { createHash } from "node:crypto";
404
+ import {
405
+ chmodSync,
406
+ mkdirSync as mkdirSync2,
407
+ readdirSync,
408
+ readFileSync as readFileSync2,
409
+ renameSync as renameSync2,
410
+ unlinkSync,
411
+ writeFileSync as writeFileSync2
412
+ } from "node:fs";
413
+ import { dirname as dirname2, join as join2 } from "node:path";
414
+ var MANAGED_AGENT_TYPE = "notis_managed_agent";
415
+ var AGENT_CLAIM = "notis_agent";
416
+ var CACHE_DIRNAME = "agent-credentials";
417
+ var AGENT_RENEW_WINDOW_SECONDS = 60 * 60;
418
+ var RENEW_TIMEOUT_MS = 15e3;
419
+ function nowSeconds() {
420
+ return Math.floor(Date.now() / 1e3);
421
+ }
422
+ function unverifiedPayload(jwt) {
423
+ if (typeof jwt !== "string" || !jwt) return null;
424
+ try {
425
+ const parts = jwt.split(".");
426
+ if (parts.length !== 3) return null;
427
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
428
+ return payload && typeof payload === "object" ? payload : null;
429
+ } catch {
430
+ return null;
431
+ }
432
+ }
433
+ function agentCredentialExpiry(jwt) {
434
+ const payload = unverifiedPayload(jwt);
435
+ if (!payload || payload.type !== MANAGED_AGENT_TYPE || !payload[AGENT_CLAIM] || typeof payload[AGENT_CLAIM] !== "object" || typeof payload.exp !== "number") {
436
+ return null;
437
+ }
438
+ return payload.exp;
439
+ }
440
+ function cacheDirectory(configFile) {
441
+ return join2(dirname2(configFile), CACHE_DIRNAME);
442
+ }
443
+ function agentCredentialCacheFile(configFile, envJwt) {
444
+ return join2(cacheDirectory(configFile), `${createHash("sha256").update(envJwt).digest("hex")}.json`);
445
+ }
446
+ function readCachedToken(configFile, envJwt) {
447
+ try {
448
+ const cached = JSON.parse(readFileSync2(agentCredentialCacheFile(configFile, envJwt), "utf-8"));
449
+ const token = typeof cached?.token === "string" ? cached.token : null;
450
+ if (!token || agentCredentialExpiry(token) === null || unverifiedPayload(token).sub !== unverifiedPayload(envJwt).sub) {
451
+ return null;
452
+ }
453
+ return token;
454
+ } catch {
455
+ return null;
456
+ }
457
+ }
458
+ function selectAgentCredential(envJwt, { configFile, now = nowSeconds() } = {}) {
459
+ const envExpiry = agentCredentialExpiry(envJwt);
460
+ if (envExpiry === null) return null;
461
+ const cached = configFile ? readCachedToken(configFile, envJwt) : null;
462
+ const cachedExpiry = cached ? agentCredentialExpiry(cached) : null;
463
+ if (cached && cachedExpiry > now && cachedExpiry > envExpiry) {
464
+ return { jwt: cached };
465
+ }
466
+ return { jwt: envJwt };
363
467
  }
468
+ var AGENT_RENEW_REQUEST = Object.freeze({
469
+ path: "/cli_tools",
470
+ body: Object.freeze({ operation: "renew_agent_credential" }),
471
+ timeoutMs: RENEW_TIMEOUT_MS
472
+ });
364
473
 
365
474
  // src/runtime/profiles.js
366
- var CONFIG_DIR = join2(homedir2(), ".notis");
367
- var CONFIG_FILE = join2(CONFIG_DIR, "config.json");
368
- var WORKSPACE_DIR = join2(CONFIG_DIR, "workspace");
475
+ var CONFIG_DIR = join3(homedir2(), ".notis");
476
+ var CONFIG_FILE = join3(CONFIG_DIR, "config.json");
477
+ var WORKSPACE_DIR = join3(CONFIG_DIR, "workspace");
369
478
  var DEFAULT_API_BASE = currentApiOrigin("stable");
370
479
  var NIGHTLY_API_BASE = currentApiOrigin("nightly");
371
480
  var DEFAULT_PROFILE = "default";
@@ -379,8 +488,8 @@ var LEGACY_DESKTOP_PROFILE_KEYS = [
379
488
  "desktop_app_name",
380
489
  "desktop_pid"
381
490
  ];
382
- var WORKTREE_RUNTIME_FILENAME = join2(".context", "notis-runtime.json");
383
- var WORKTREE_ROUTING_FILENAME = join2(".context", "notis-routing.json");
491
+ var WORKTREE_RUNTIME_FILENAME = join3(".context", "notis-runtime.json");
492
+ var WORKTREE_ROUTING_FILENAME = join3(".context", "notis-routing.json");
384
493
  var LOCAL_API_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
385
494
  function clone(value) {
386
495
  return JSON.parse(JSON.stringify(value));
@@ -460,7 +569,7 @@ function normalizeConfig(rawConfig = {}) {
460
569
  }
461
570
  function readJsonFile(path3) {
462
571
  try {
463
- return JSON.parse(readFileSync2(path3, "utf-8"));
572
+ return JSON.parse(readFileSync3(path3, "utf-8"));
464
573
  } catch {
465
574
  return null;
466
575
  }
@@ -469,14 +578,14 @@ function findUp(filename, startDir = process.cwd(), boundary = null) {
469
578
  let current = resolve2(startDir);
470
579
  const root = parse(current).root;
471
580
  while (true) {
472
- const candidate = join2(current, filename);
581
+ const candidate = join3(current, filename);
473
582
  if (existsSync3(candidate)) {
474
583
  return candidate;
475
584
  }
476
585
  if (current === root || current === boundary) {
477
586
  return null;
478
587
  }
479
- current = dirname2(current);
588
+ current = dirname3(current);
480
589
  }
481
590
  }
482
591
  function processIsAlive(pid) {
@@ -495,7 +604,7 @@ function resolveWorktreeRuntime(startDir = process.cwd()) {
495
604
  return null;
496
605
  }
497
606
  const routingPath = findUp(WORKTREE_ROUTING_FILENAME, startDir);
498
- const boundary = routingPath ? dirname2(dirname2(routingPath)) : null;
607
+ const boundary = routingPath ? dirname3(dirname3(routingPath)) : null;
499
608
  const runtimePath = findUp(WORKTREE_RUNTIME_FILENAME, startDir, boundary);
500
609
  const routing = routingPath ? readJsonFile(routingPath) : null;
501
610
  if (!runtimePath) {
@@ -558,7 +667,7 @@ function loadConfig() {
558
667
  return normalizeConfig({});
559
668
  }
560
669
  try {
561
- return normalizeConfig(JSON.parse(readFileSync2(configFile, "utf-8")));
670
+ return normalizeConfig(JSON.parse(readFileSync3(configFile, "utf-8")));
562
671
  } catch {
563
672
  return normalizeConfig({});
564
673
  }
@@ -566,7 +675,7 @@ function loadConfig() {
566
675
  function writeConfig(configFile, config) {
567
676
  let rawConfig = null;
568
677
  try {
569
- rawConfig = JSON.parse(readFileSync2(configFile, "utf-8"));
678
+ rawConfig = JSON.parse(readFileSync3(configFile, "utf-8"));
570
679
  } catch {
571
680
  }
572
681
  const normalized = normalizeConfig(config);
@@ -584,10 +693,10 @@ function writeConfig(configFile, config) {
584
693
  writeRawConfig(configFile, persisted);
585
694
  }
586
695
  function writeRawConfig(configFile, config) {
587
- mkdirSync2(dirname2(configFile), { recursive: true });
696
+ mkdirSync3(dirname3(configFile), { recursive: true });
588
697
  const temporaryFile = `${configFile}.${process.pid}.${Date.now()}.tmp`;
589
- writeFileSync2(temporaryFile, JSON.stringify(config, null, 2), { mode: 384 });
590
- renameSync2(temporaryFile, configFile);
698
+ writeFileSync3(temporaryFile, JSON.stringify(config, null, 2), { mode: 384 });
699
+ renameSync3(temporaryFile, configFile);
591
700
  }
592
701
  function withConfigWriteLock(callback) {
593
702
  return withConfigFileWriteLock(resolveConfigFile(), callback);
@@ -692,9 +801,9 @@ function oauthGrantOnRetiredAddress(profile = {}) {
692
801
  return isOnRetiredApiHost(profile.oauth_issuer) || isOnRetiredApiHost(getOAuthResource(profile));
693
802
  }
694
803
  function refreshTokenFingerprint(refreshToken) {
695
- return createHash("sha256").update(String(refreshToken)).digest("hex").slice(0, 32);
804
+ return createHash2("sha256").update(String(refreshToken)).digest("hex").slice(0, 32);
696
805
  }
697
- function oauthGrantIsDead(profile = {}, nowSeconds = Math.floor(Date.now() / 1e3)) {
806
+ function oauthGrantIsDead(profile = {}, nowSeconds2 = Math.floor(Date.now() / 1e3)) {
698
807
  if (oauthGrantOnRetiredAddress(profile)) return true;
699
808
  const refreshToken = profile.oauth_refresh_token;
700
809
  if (!refreshToken) return false;
@@ -704,7 +813,7 @@ function oauthGrantIsDead(profile = {}, nowSeconds = Math.floor(Date.now() / 1e3
704
813
  if (profile.oauth_refresh_expiry_from_server !== true) return false;
705
814
  const refreshExpiry = Number(profile.oauth_refresh_expires_at);
706
815
  const accessExpiry = Number(profile.oauth_access_expires_at);
707
- return Number.isFinite(refreshExpiry) && refreshExpiry <= nowSeconds && Number.isFinite(accessExpiry) && accessExpiry <= nowSeconds;
816
+ return Number.isFinite(refreshExpiry) && refreshExpiry <= nowSeconds2 && Number.isFinite(accessExpiry) && accessExpiry <= nowSeconds2;
708
817
  }
709
818
  function resolveDefaultLiveApiBase(profile = {}) {
710
819
  const channel = pinnedReleaseChannel(profile) || (isLiveApiBase(profile.api_base) ? channelFromProfile({ api_base: profile.api_base }) : null);
@@ -850,6 +959,7 @@ function resolveRuntimeProfile(globalOptions = {}, {
850
959
  const oauthJwt = profile.oauth_access_token;
851
960
  let jwt;
852
961
  let credentialKind;
962
+ let agentEnvJwt = null;
853
963
  if (requireAuth && !devRuntime && devJwt && !oauthJwt && !process.env.NOTIS_JWT) {
854
964
  throw new CliError({
855
965
  code: "dev_runtime_unavailable",
@@ -868,6 +978,14 @@ function resolveRuntimeProfile(globalOptions = {}, {
868
978
  } else if (envJwt) {
869
979
  jwt = envJwt;
870
980
  credentialKind = "env";
981
+ try {
982
+ const selected = selectAgentCredential(envJwt, { configFile: resolveConfigFile() });
983
+ if (selected) {
984
+ jwt = selected.jwt;
985
+ agentEnvJwt = envJwt;
986
+ }
987
+ } catch {
988
+ }
871
989
  } else if (oauthJwt && !credentialIsExpired({ credentialKind: "oauth", jwt: oauthJwt }, profile)) {
872
990
  jwt = oauthJwt;
873
991
  credentialKind = "oauth";
@@ -936,6 +1054,8 @@ function resolveRuntimeProfile(globalOptions = {}, {
936
1054
  jwt,
937
1055
  credentialKind,
938
1056
  credentialSource: credentialKind,
1057
+ // The NOTIS_JWT of a managed agent credential, set only when `jwt` may be renewed (agent-credential.js).
1058
+ agentEnvJwt,
939
1059
  oauthAccessToken: profile.oauth_access_token,
940
1060
  oauthRefreshToken: profile.oauth_refresh_token,
941
1061
  oauthAccessExpiresAt: profile.oauth_access_expires_at,
@@ -986,16 +1106,16 @@ function getJwtSubject(jwt) {
986
1106
  return null;
987
1107
  }
988
1108
  }
989
- function credentialIsExpired(runtime, profile = {}, nowSeconds = Math.floor(Date.now() / 1e3)) {
1109
+ function credentialIsExpired(runtime, profile = {}, nowSeconds2 = Math.floor(Date.now() / 1e3)) {
990
1110
  const credentialKind = runtime?.credentialKind || (runtime?.credentialSource === "env" ? "env" : null);
991
1111
  switch (credentialKind) {
992
1112
  case "oauth": {
993
1113
  const expiration = Number(profile.oauth_access_expires_at);
994
- return !Number.isFinite(expiration) || expiration <= nowSeconds || oauthGrantIsDead(profile, nowSeconds);
1114
+ return !Number.isFinite(expiration) || expiration <= nowSeconds2 || oauthGrantIsDead(profile, nowSeconds2);
995
1115
  }
996
1116
  case "env": {
997
1117
  const expiration = getJwtExpiration(runtime?.jwt);
998
- return expiration !== null && expiration <= nowSeconds;
1118
+ return expiration !== null && expiration <= nowSeconds2;
999
1119
  }
1000
1120
  case "worktree": {
1001
1121
  const rawExpiration = profile.dev_access_expires_at ?? getJwtExpiration(runtime?.jwt);
@@ -1003,7 +1123,7 @@ function credentialIsExpired(runtime, profile = {}, nowSeconds = Math.floor(Date
1003
1123
  return true;
1004
1124
  }
1005
1125
  const expiration = Number(rawExpiration);
1006
- return !Number.isFinite(expiration) || expiration <= nowSeconds;
1126
+ return !Number.isFinite(expiration) || expiration <= nowSeconds2;
1007
1127
  }
1008
1128
  default:
1009
1129
  return true;
@@ -1012,39 +1132,39 @@ function credentialIsExpired(runtime, profile = {}, nowSeconds = Math.floor(Date
1012
1132
 
1013
1133
  // src/runtime/oauth.js
1014
1134
  import {
1015
- createHash as createHash2,
1135
+ createHash as createHash3,
1016
1136
  randomBytes,
1017
1137
  timingSafeEqual
1018
1138
  } from "node:crypto";
1019
1139
  import { subscribe, unsubscribe } from "node:diagnostics_channel";
1020
1140
  import {
1021
- mkdirSync as mkdirSync4,
1022
- readdirSync,
1023
- readFileSync as readFileSync4,
1024
- renameSync as renameSync4,
1141
+ mkdirSync as mkdirSync5,
1142
+ readdirSync as readdirSync2,
1143
+ readFileSync as readFileSync5,
1144
+ renameSync as renameSync5,
1025
1145
  rmdirSync,
1026
1146
  rmSync as rmSync2,
1027
1147
  statSync as statSync2,
1028
1148
  utimesSync,
1029
- writeFileSync as writeFileSync4
1149
+ writeFileSync as writeFileSync5
1030
1150
  } from "node:fs";
1031
1151
  import { homedir as homedir3 } from "node:os";
1032
- import { basename, dirname as dirname4, join as join4 } from "node:path";
1152
+ import { basename, dirname as dirname5, join as join5 } from "node:path";
1033
1153
  import { fileURLToPath } from "node:url";
1034
1154
  import { createInterface } from "node:readline/promises";
1035
1155
 
1036
1156
  // src/runtime/computer-identity.js
1037
1157
  import { randomUUID as randomUUID2 } from "node:crypto";
1038
1158
  import { execFileSync } from "node:child_process";
1039
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
1159
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync4, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
1040
1160
  import { hostname as osHostname } from "node:os";
1041
- import { dirname as dirname3, join as join3 } from "node:path";
1161
+ import { dirname as dirname4, join as join4 } from "node:path";
1042
1162
  var COMPUTER_IDENTITY_VERSION = 1;
1043
1163
  var COMPUTER_NAME_MAX_LENGTH = 64;
1044
1164
  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;
1045
1165
  var FALLBACK_COMPUTER_NAME = "Computer";
1046
1166
  function computerIdentityFile(configFile = resolveCliConfigFile()) {
1047
- return join3(dirname3(configFile), "computer.json");
1167
+ return join4(dirname4(configFile), "computer.json");
1048
1168
  }
1049
1169
  function normalizeComputerName(value) {
1050
1170
  if (typeof value !== "string") return null;
@@ -1082,7 +1202,7 @@ function defaultComputerName(options = {}) {
1082
1202
  function parseIdentityFile(file) {
1083
1203
  let raw;
1084
1204
  try {
1085
- raw = JSON.parse(readFileSync3(file, "utf8"));
1205
+ raw = JSON.parse(readFileSync4(file, "utf8"));
1086
1206
  } catch {
1087
1207
  return null;
1088
1208
  }
@@ -1098,16 +1218,16 @@ function validStored(raw) {
1098
1218
  };
1099
1219
  }
1100
1220
  function writeIdentityFile(file, stored) {
1101
- mkdirSync3(dirname3(file), { recursive: true });
1221
+ mkdirSync4(dirname4(file), { recursive: true });
1102
1222
  const contents = {
1103
1223
  version: COMPUTER_IDENTITY_VERSION,
1104
1224
  computer_id: stored.computerId,
1105
1225
  ...stored.name ? { name: stored.name } : {}
1106
1226
  };
1107
1227
  const temporaryFile = `${file}.${process.pid}.${Date.now()}.tmp`;
1108
- writeFileSync3(temporaryFile, `${JSON.stringify(contents, null, 2)}
1228
+ writeFileSync4(temporaryFile, `${JSON.stringify(contents, null, 2)}
1109
1229
  `, { mode: 384 });
1110
- renameSync3(temporaryFile, file);
1230
+ renameSync4(temporaryFile, file);
1111
1231
  }
1112
1232
  function withIdentity(stored, options) {
1113
1233
  const defaultName = defaultComputerName(options);
@@ -1139,7 +1259,7 @@ function readComputerIdentity(options = {}) {
1139
1259
 
1140
1260
  // src/runtime/oauth.js
1141
1261
  function oauthLockDir() {
1142
- return join4(homedir3(), ".notis", "oauth.lock");
1262
+ return join5(homedir3(), ".notis", "oauth.lock");
1143
1263
  }
1144
1264
  var DEFAULT_REFRESH_EXPIRES_IN = 30 * 24 * 60 * 60;
1145
1265
  var PENDING_LOGIN_TTL_SECONDS = 30 * 60;
@@ -1446,7 +1566,7 @@ var LISTENER_HANDSHAKE_TIMEOUT_MS = 1e4;
1446
1566
  var LISTENER_START_LOCK_STALE_MS = LISTENER_HANDSHAKE_TIMEOUT_MS * 2;
1447
1567
  var LISTENER_GLOBAL_LOCK_HEARTBEAT_MS = 5e3;
1448
1568
  function listenerStateFile(runtime) {
1449
- const profileKey = createHash2("sha256").update(String(runtime.profileName || "default")).digest("hex").slice(0, 16);
1569
+ const profileKey = createHash3("sha256").update(String(runtime.profileName || "default")).digest("hex").slice(0, 16);
1450
1570
  return `${resolveConfigFile()}.login-listener.${profileKey}`;
1451
1571
  }
1452
1572
  function listenerStartLockDir(runtime) {
@@ -1456,11 +1576,11 @@ function listenerGlobalLockDir() {
1456
1576
  return `${resolveConfigFile()}.oauth-listener-global.lock`;
1457
1577
  }
1458
1578
  function listenerGlobalLockOwnerFile(lockDir) {
1459
- return join4(lockDir, "owner.json");
1579
+ return join5(lockDir, "owner.json");
1460
1580
  }
1461
1581
  function readListenerGlobalLockOwner(lockDir) {
1462
1582
  try {
1463
- return JSON.parse(readFileSync4(listenerGlobalLockOwnerFile(lockDir), "utf-8"));
1583
+ return JSON.parse(readFileSync5(listenerGlobalLockOwnerFile(lockDir), "utf-8"));
1464
1584
  } catch {
1465
1585
  return null;
1466
1586
  }
@@ -1468,7 +1588,7 @@ function readListenerGlobalLockOwner(lockDir) {
1468
1588
  function writeListenerGlobalLockOwner(lock) {
1469
1589
  const current = readListenerGlobalLockOwner(lock.lockDir);
1470
1590
  if (current && current.owner_token !== lock.ownerToken) return false;
1471
- writeFileSync4(listenerGlobalLockOwnerFile(lock.lockDir), JSON.stringify({
1591
+ writeFileSync5(listenerGlobalLockOwnerFile(lock.lockDir), JSON.stringify({
1472
1592
  owner_token: lock.ownerToken,
1473
1593
  owner_pid: process.pid,
1474
1594
  updated_at: Date.now()
@@ -1489,7 +1609,7 @@ function listenerGlobalLockIsStale(lockDir, staleMs) {
1489
1609
  function retireStaleListenerGlobalLock(lockDir) {
1490
1610
  const retiredDir = `${lockDir}.stale-${process.pid}-${base64url(randomBytes(8))}`;
1491
1611
  try {
1492
- renameSync4(lockDir, retiredDir);
1612
+ renameSync5(lockDir, retiredDir);
1493
1613
  } catch {
1494
1614
  return false;
1495
1615
  }
@@ -1498,11 +1618,11 @@ function retireStaleListenerGlobalLock(lockDir) {
1498
1618
  }
1499
1619
  async function acquireListenerStartLock(runtime) {
1500
1620
  const lockDir = listenerStartLockDir(runtime);
1501
- mkdirSync4(dirname4(lockDir), { recursive: true });
1621
+ mkdirSync5(dirname5(lockDir), { recursive: true });
1502
1622
  const deadline = Date.now() + LISTENER_START_LOCK_STALE_MS * 2;
1503
1623
  for (; ; ) {
1504
1624
  try {
1505
- mkdirSync4(lockDir);
1625
+ mkdirSync5(lockDir);
1506
1626
  return lockDir;
1507
1627
  } catch (error) {
1508
1628
  if (error?.code !== "EEXIST") throw error;
@@ -1536,11 +1656,11 @@ async function acquireListenerGlobalLock({
1536
1656
  heartbeatMs = LISTENER_GLOBAL_LOCK_HEARTBEAT_MS
1537
1657
  } = {}) {
1538
1658
  const lockDir = listenerGlobalLockDir();
1539
- mkdirSync4(dirname4(lockDir), { recursive: true });
1659
+ mkdirSync5(dirname5(lockDir), { recursive: true });
1540
1660
  const deadline = Date.now() + waitMs;
1541
1661
  for (; ; ) {
1542
1662
  try {
1543
- mkdirSync4(lockDir);
1663
+ mkdirSync5(lockDir);
1544
1664
  const lock = {
1545
1665
  lockDir,
1546
1666
  ownerToken: base64url(randomBytes(24)),
@@ -1577,14 +1697,14 @@ function releaseListenerGlobalLock(lock) {
1577
1697
  if (owner?.owner_token !== lock.ownerToken) return;
1578
1698
  const releasedDir = `${lock.lockDir}.released-${process.pid}-${lock.ownerToken}`;
1579
1699
  try {
1580
- renameSync4(lock.lockDir, releasedDir);
1700
+ renameSync5(lock.lockDir, releasedDir);
1581
1701
  } catch {
1582
1702
  return;
1583
1703
  }
1584
1704
  const movedOwner = readListenerGlobalLockOwner(releasedDir);
1585
1705
  if (movedOwner?.owner_token !== lock.ownerToken) {
1586
1706
  try {
1587
- renameSync4(releasedDir, lock.lockDir);
1707
+ renameSync5(releasedDir, lock.lockDir);
1588
1708
  } catch {
1589
1709
  }
1590
1710
  return;
@@ -1651,11 +1771,11 @@ function lockIsStale() {
1651
1771
  }
1652
1772
  }
1653
1773
  async function acquireRefreshLock(runtime, staleAccessToken, waitMs = OAUTH_REFRESH_LOCK_WAIT_MS) {
1654
- mkdirSync4(join4(homedir3(), ".notis"), { recursive: true });
1774
+ mkdirSync5(join5(homedir3(), ".notis"), { recursive: true });
1655
1775
  const deadline = Date.now() + waitMs;
1656
1776
  for (; ; ) {
1657
1777
  try {
1658
- mkdirSync4(oauthLockDir());
1778
+ mkdirSync5(oauthLockDir());
1659
1779
  return true;
1660
1780
  } catch (error) {
1661
1781
  if (error?.code !== "EEXIST") throw error;
@@ -1789,8 +1909,8 @@ async function refreshOAuthCredential(runtime, fetchImpl = fetch, tokenRequestOp
1789
1909
  // dist/skill-sync/index.js
1790
1910
  import { createHash as createHash4 } from "node:crypto";
1791
1911
  import { promises as fs3 } from "node:fs";
1792
- import { dirname as dirname5, join as join5 } from "node:path";
1793
- import { createHash as createHash3 } from "node:crypto";
1912
+ import { dirname as dirname6, join as join6 } from "node:path";
1913
+ import { createHash as createHash5 } from "node:crypto";
1794
1914
  import { createHash as createHash22 } from "crypto";
1795
1915
  import { execFile } from "child_process";
1796
1916
  import { promises as fs } from "fs";
@@ -1857,7 +1977,7 @@ function assertNativePull(response) {
1857
1977
  }
1858
1978
  }
1859
1979
  function nativeFileDigest(bytes) {
1860
- return createHash3("sha256").update(bytes).digest("hex");
1980
+ return createHash5("sha256").update(bytes).digest("hex");
1861
1981
  }
1862
1982
  function nativeFrontmatterName(markdown) {
1863
1983
  const header = markdown.match(/^---\s*\n([\s\S]*?)\n---/);
@@ -2999,6 +3119,9 @@ async function removeForeignAccountSymlinks(skillsDir, options = {}) {
2999
3119
  }
3000
3120
  return removed;
3001
3121
  }
3122
+ var BASE_SKILL_LINK_NAMES = /* @__PURE__ */ new Set(["notis-spaces", "notis-query", "notis-cli"]);
3123
+ var NATIVE_FOLDER_NAME = /^native-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
3124
+ var READABLE_SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3002
3125
  function managedSkillRoots(skillsDir, legacyGlobalSkillsDir = LEGACY_AGENTS_SKILLS_DIR) {
3003
3126
  const resolvedSkillsDir = path2.resolve(skillsDir);
3004
3127
  const scopedUsersRoot = path2.dirname(path2.dirname(resolvedSkillsDir));
@@ -3013,6 +3136,9 @@ function managedSkillRoots(skillsDir, legacyGlobalSkillsDir = LEGACY_AGENTS_SKIL
3013
3136
  }
3014
3137
  return roots;
3015
3138
  }
3139
+ function isUnderManagedRoot(resolvedTarget, managedRoots) {
3140
+ return managedRoots.some((root) => resolvedTarget === root || resolvedTarget.startsWith(`${root}${path2.sep}`));
3141
+ }
3016
3142
  async function isManagedSymlink(linkPath, managedRoots) {
3017
3143
  try {
3018
3144
  const stats = await fs2.lstat(linkPath);
@@ -3021,7 +3147,7 @@ async function isManagedSymlink(linkPath, managedRoots) {
3021
3147
  }
3022
3148
  const target = await fs2.readlink(linkPath);
3023
3149
  const resolvedTarget = path2.resolve(path2.dirname(linkPath), target);
3024
- return managedRoots.some((root) => resolvedTarget === root || resolvedTarget.startsWith(`${root}${path2.sep}`));
3150
+ return isUnderManagedRoot(resolvedTarget, managedRoots);
3025
3151
  } catch (error) {
3026
3152
  if (error?.code === "ENOENT") return false;
3027
3153
  throw error;
@@ -3053,7 +3179,7 @@ function defaultAgentSkillDirs(skillsDir) {
3053
3179
  ...EXTERNAL_AGENT_SKILL_DIRS
3054
3180
  };
3055
3181
  }
3056
- async function removeUndesiredManagedSymlinks(agentDir, desiredSkills, managedRoots, failures, agent) {
3182
+ async function removeUndesiredManagedSymlinks(agentDir, desiredSkills, managedRoots, failures, agent, movedTargets = /* @__PURE__ */ new Set()) {
3057
3183
  let removed = 0;
3058
3184
  try {
3059
3185
  await fs2.mkdir(agentDir, { recursive: true });
@@ -3061,7 +3187,7 @@ async function removeUndesiredManagedSymlinks(agentDir, desiredSkills, managedRo
3061
3187
  for (const entry of existingEntries) {
3062
3188
  const entryPath = path2.join(agentDir, entry.name);
3063
3189
  try {
3064
- if (!desiredSkills.has(entry.name) && await isManagedSymlink(entryPath, managedRoots)) {
3190
+ if (!desiredSkills.has(entry.name) && await isManagedSymlink(entryPath, managedRoots) && !(movedTargets.size > 0 && movedTargets.has(path2.resolve(agentDir, await fs2.readlink(entryPath))))) {
3065
3191
  await fs2.unlink(entryPath);
3066
3192
  removed += 1;
3067
3193
  }
@@ -3084,15 +3210,174 @@ async function removeAllSymlinksForSkill(skillName, skillsDir = LEGACY_AGENTS_SK
3084
3210
  const agentDirs = /* @__PURE__ */ new Set([...Object.values(agentSkillDirs), legacyGlobalSkillsDir]);
3085
3211
  const expectedTarget = path2.resolve(skillsDir, safeName(skillName, skillsDir));
3086
3212
  for (const agentDir of agentDirs) {
3087
- const linkPath = path2.join(agentDir, safeName(skillName, agentDir));
3088
- const owned = options.ownership === "exact-skill-dir" ? await isManagedSymlink(linkPath, [expectedTarget]) : await isManagedSymlink(linkPath, managedRoots);
3213
+ const linkName = safeName(skillName, agentDir);
3214
+ const linkPath = path2.join(agentDir, linkName);
3215
+ const owned = options.ownership === "exact-skill-dir" ? await isManagedSymlink(linkPath, [expectedTarget]) : await isManagedSymlink(linkPath, managedRoots) && !await linksToOtherSkillFolder(linkPath, expectedTarget, skillsDir);
3089
3216
  if (owned) {
3090
3217
  await fs2.unlink(linkPath);
3091
3218
  removed += 1;
3092
3219
  }
3220
+ if (path2.resolve(agentDir) !== path2.resolve(skillsDir)) {
3221
+ try {
3222
+ removed += await removeLinksToTarget(agentDir, expectedTarget, /* @__PURE__ */ new Set([linkName]));
3223
+ } catch (error) {
3224
+ console.warn(`[skill-sync] Could not list ${agentDir} to remove the links to "${skillName}": ${error.message}`);
3225
+ }
3226
+ }
3227
+ }
3228
+ return removed;
3229
+ }
3230
+ async function linksToOtherSkillFolder(linkPath, expectedTarget, skillsDir) {
3231
+ try {
3232
+ const resolved = path2.resolve(path2.dirname(linkPath), await fs2.readlink(linkPath));
3233
+ if (resolved === expectedTarget || path2.dirname(resolved) !== path2.resolve(skillsDir)) return false;
3234
+ return (await fs2.stat(resolved)).isDirectory();
3235
+ } catch {
3236
+ return false;
3237
+ }
3238
+ }
3239
+ async function hasLinkToTarget(agentDir, targetPath) {
3240
+ let entries;
3241
+ try {
3242
+ entries = await fs2.readdir(agentDir, { withFileTypes: true });
3243
+ } catch {
3244
+ return true;
3245
+ }
3246
+ for (const entry of entries) {
3247
+ if (!entry.isSymbolicLink()) continue;
3248
+ try {
3249
+ if (path2.resolve(agentDir, await fs2.readlink(path2.join(agentDir, entry.name))) === targetPath) return true;
3250
+ } catch {
3251
+ }
3252
+ }
3253
+ return false;
3254
+ }
3255
+ async function linkNamesByTarget(agentDir, targets) {
3256
+ const names = /* @__PURE__ */ new Map();
3257
+ let entries;
3258
+ try {
3259
+ entries = await fs2.readdir(agentDir, { withFileTypes: true });
3260
+ } catch (error) {
3261
+ if (error?.code === "ENOENT") return names;
3262
+ throw error;
3263
+ }
3264
+ for (const entry of entries) {
3265
+ if (!entry.isSymbolicLink()) continue;
3266
+ try {
3267
+ const resolved = path2.resolve(agentDir, await fs2.readlink(path2.join(agentDir, entry.name)));
3268
+ if (targets.has(resolved)) names.set(resolved, [...names.get(resolved) ?? [], entry.name]);
3269
+ } catch (error) {
3270
+ if (error?.code !== "ENOENT") throw error;
3271
+ }
3272
+ }
3273
+ return names;
3274
+ }
3275
+ async function unlinkIfTarget(agentDir, names, targetPath) {
3276
+ let removed = 0;
3277
+ for (const name of names) {
3278
+ const entryPath = path2.join(agentDir, name);
3279
+ try {
3280
+ if ((await fs2.lstat(entryPath)).isSymbolicLink() && path2.resolve(agentDir, await fs2.readlink(entryPath)) === targetPath) {
3281
+ await fs2.unlink(entryPath);
3282
+ removed += 1;
3283
+ }
3284
+ } catch (error) {
3285
+ if (error?.code !== "ENOENT") throw error;
3286
+ }
3287
+ }
3288
+ return removed;
3289
+ }
3290
+ async function removeLinksToTarget(agentDir, targetPath, keepNames) {
3291
+ let entries;
3292
+ try {
3293
+ entries = await fs2.readdir(agentDir, { withFileTypes: true });
3294
+ } catch (error) {
3295
+ if (error?.code === "ENOENT") return 0;
3296
+ throw error;
3297
+ }
3298
+ const keep = new Set([...keepNames].map((name) => name.toLowerCase()));
3299
+ let removed = 0;
3300
+ for (const entry of entries) {
3301
+ if (!entry.isSymbolicLink() || keep.has(entry.name.toLowerCase())) continue;
3302
+ const entryPath = path2.join(agentDir, entry.name);
3303
+ try {
3304
+ const resolved = path2.resolve(agentDir, await fs2.readlink(entryPath));
3305
+ if (resolved !== targetPath) continue;
3306
+ await fs2.unlink(entryPath);
3307
+ removed += 1;
3308
+ } catch (error) {
3309
+ if (error?.code !== "ENOENT") throw error;
3310
+ }
3093
3311
  }
3094
3312
  return removed;
3095
3313
  }
3314
+ async function readableNativeLinkName(skill, folderName, skillsDir) {
3315
+ if (!isNativeSkill(skill)) return null;
3316
+ let markdown = "";
3317
+ try {
3318
+ markdown = await fs2.readFile(path2.join(skillsDir, folderName, "SKILL.md"), "utf8");
3319
+ } catch {
3320
+ }
3321
+ const name = [nativeFrontmatterName(markdown), nativeFrontmatterName(skill.skill_md || ""), skill.display_name || ""].map((value) => value.trim()).find(Boolean);
3322
+ if (!name || name === folderName || name.length > 64 || !READABLE_SKILL_NAME.test(name) || NATIVE_FOLDER_NAME.test(name) || BASE_SKILL_LINK_NAMES.has(name)) {
3323
+ return null;
3324
+ }
3325
+ return name;
3326
+ }
3327
+ async function readableLinkAvailable(linkPath, targetPath, managedRoots, ownsWholeFolder) {
3328
+ let stats;
3329
+ try {
3330
+ stats = await fs2.lstat(linkPath);
3331
+ } catch (error) {
3332
+ return error?.code === "ENOENT";
3333
+ }
3334
+ if (!stats.isSymbolicLink()) return false;
3335
+ try {
3336
+ const resolved = path2.resolve(path2.dirname(linkPath), await fs2.readlink(linkPath));
3337
+ if (resolved === path2.resolve(targetPath)) return true;
3338
+ return ownsWholeFolder && isUnderManagedRoot(resolved, managedRoots);
3339
+ } catch {
3340
+ return false;
3341
+ }
3342
+ }
3343
+ async function planAgentLinkNames(candidates, agentDir, skillsDir, managedRoots, ownsWholeFolder) {
3344
+ const reserved = new Set(
3345
+ candidates.filter((candidate) => !candidate.readableName).map((candidate) => candidate.folderName.toLowerCase())
3346
+ );
3347
+ const readableCounts = /* @__PURE__ */ new Map();
3348
+ for (const { readableName } of candidates) {
3349
+ if (!readableName) continue;
3350
+ const key = readableName.toLowerCase();
3351
+ readableCounts.set(key, (readableCounts.get(key) ?? 0) + 1);
3352
+ }
3353
+ const available = /* @__PURE__ */ new Map();
3354
+ for (; ; ) {
3355
+ const plan = /* @__PURE__ */ new Map();
3356
+ const owners = /* @__PURE__ */ new Map();
3357
+ for (const { folderName, readableName } of candidates) {
3358
+ let linkName = folderName;
3359
+ if (readableName) {
3360
+ const key = readableName.toLowerCase();
3361
+ if (!reserved.has(key) && readableCounts.get(key) === 1) {
3362
+ if (!available.has(folderName)) {
3363
+ available.set(folderName, await readableLinkAvailable(
3364
+ path2.join(agentDir, readableName),
3365
+ path2.join(skillsDir, folderName),
3366
+ managedRoots,
3367
+ ownsWholeFolder
3368
+ ));
3369
+ }
3370
+ if (available.get(folderName)) linkName = readableName;
3371
+ }
3372
+ }
3373
+ plan.set(linkName, folderName);
3374
+ owners.set(linkName.toLowerCase(), (owners.get(linkName.toLowerCase()) ?? 0) + 1);
3375
+ }
3376
+ const collisions = [...owners].filter(([name, count]) => count > 1 && !reserved.has(name)).map(([name]) => name);
3377
+ if (collisions.length === 0) return plan;
3378
+ for (const name of collisions) reserved.add(name);
3379
+ }
3380
+ }
3096
3381
  async function detectDeletedAgentSymlinks(cloudSkills, previousState, skillsDir = LEGACY_AGENTS_SKILLS_DIR, options = {}) {
3097
3382
  const agentSkillDirs = { ...defaultAgentSkillDirs(skillsDir), ...options.agentSkillDirs };
3098
3383
  const deletions = [];
@@ -3117,7 +3402,8 @@ async function detectDeletedAgentSymlinks(cloudSkills, previousState, skillsDir
3117
3402
  continue;
3118
3403
  }
3119
3404
  const previous = previousState.skills[skill.name];
3120
- if (!previous || previous.cloudId !== skill.id || previous.verifiedAgentLinks?.[agent] !== true || !skill.updated_at || previous.cloudUpdatedAt !== skill.updated_at) {
3405
+ const verified = previous?.verifiedAgentLinks?.[agent];
3406
+ if (!previous || previous.cloudId !== skill.id || !verified || !skill.updated_at || previous.cloudUpdatedAt !== skill.updated_at) {
3121
3407
  continue;
3122
3408
  }
3123
3409
  const cloudTargets = normalizeAgentTargets(skill.agent_targets);
@@ -3125,17 +3411,19 @@ async function detectDeletedAgentSymlinks(cloudSkills, previousState, skillsDir
3125
3411
  if (!cloudTargets[agent] || !previousTargets[agent]) {
3126
3412
  continue;
3127
3413
  }
3128
- let safeSkillName;
3414
+ let linkName;
3415
+ let folderName;
3129
3416
  try {
3130
- safeSkillName = safeName(skill.name, skillsDir);
3417
+ folderName = safeName(skill.name, skillsDir);
3418
+ linkName = safeName(typeof verified === "string" ? verified : folderName, agentDir);
3131
3419
  } catch {
3132
3420
  continue;
3133
3421
  }
3134
- const linkPath = path2.join(agentDir, safeName(safeSkillName, agentDir));
3422
+ const linkPath = path2.join(agentDir, linkName);
3135
3423
  try {
3136
3424
  await fs2.lstat(linkPath);
3137
3425
  } catch (error) {
3138
- if (error?.code === "ENOENT") {
3426
+ if (error?.code === "ENOENT" && !await hasLinkToTarget(agentDir, path2.resolve(skillsDir, folderName))) {
3139
3427
  deletions.push({ skillId: skill.id, skillName: skill.name, agent });
3140
3428
  }
3141
3429
  }
@@ -3155,11 +3443,12 @@ async function syncSymlinks(skills, skillsDir = LEGACY_AGENTS_SKILLS_DIR, option
3155
3443
  const agentSkillDirs = { ...defaultAgentSkillDirs(skillsDir), ...options.agentSkillDirs };
3156
3444
  const legacyGlobalSkillsDir = options.legacyGlobalSkillsDir || LEGACY_AGENTS_SKILLS_DIR;
3157
3445
  const managedRoots = managedSkillRoots(skillsDir, legacyGlobalSkillsDir);
3446
+ const ownsWholeFolder = options.removeUndesired !== false;
3158
3447
  const desiredByAgent = {
3159
- notis: /* @__PURE__ */ new Set(),
3160
- claude_code: /* @__PURE__ */ new Set(),
3161
- cursor: /* @__PURE__ */ new Set(),
3162
- codex: /* @__PURE__ */ new Set()
3448
+ notis: /* @__PURE__ */ new Map(),
3449
+ claude_code: /* @__PURE__ */ new Map(),
3450
+ cursor: /* @__PURE__ */ new Map(),
3451
+ codex: /* @__PURE__ */ new Map()
3163
3452
  };
3164
3453
  for (const skill of skills) {
3165
3454
  if (skill.status !== "active") {
@@ -3167,17 +3456,20 @@ async function syncSymlinks(skills, skillsDir = LEGACY_AGENTS_SKILLS_DIR, option
3167
3456
  }
3168
3457
  const safeSkillName = safeName(skill.name, skillsDir);
3169
3458
  const targets = normalizeAgentTargets(skill.agent_targets);
3170
- if (targets.notis) {
3171
- desiredByAgent.notis.add(safeSkillName);
3172
- }
3173
- if (targets.claude_code) {
3174
- desiredByAgent.claude_code.add(safeSkillName);
3175
- }
3176
- if (targets.cursor) {
3177
- desiredByAgent.cursor.add(safeSkillName);
3459
+ for (const agent of Object.keys(desiredByAgent)) {
3460
+ if (targets[agent] && !desiredByAgent[agent].has(safeSkillName)) {
3461
+ desiredByAgent[agent].set(safeSkillName, skill);
3462
+ }
3178
3463
  }
3179
- if (targets.codex) {
3180
- desiredByAgent.codex.add(safeSkillName);
3464
+ }
3465
+ const readableNames = /* @__PURE__ */ new Map();
3466
+ for (const [folderName, skill] of [
3467
+ ...desiredByAgent.claude_code,
3468
+ ...desiredByAgent.cursor,
3469
+ ...desiredByAgent.codex
3470
+ ]) {
3471
+ if (!readableNames.has(folderName)) {
3472
+ readableNames.set(folderName, await readableNativeLinkName(skill, folderName, skillsDir));
3181
3473
  }
3182
3474
  }
3183
3475
  for (const [agent, agentDir] of Object.entries(agentSkillDirs)) {
@@ -3191,13 +3483,39 @@ async function syncSymlinks(skills, skillsDir = LEGACY_AGENTS_SKILLS_DIR, option
3191
3483
  result.failures.push({ name: agentFolderFailureName(agent), error: `Could not create agent skills directory (${error.message})` });
3192
3484
  continue;
3193
3485
  }
3194
- const desiredSkills = desiredByAgent[agent];
3195
- if (options.removeUndesired !== false) {
3196
- result.removed += await removeUndesiredManagedSymlinks(agentDir, desiredSkills, managedRoots, result.failures, agent);
3486
+ const external = EXTERNAL_AGENTS.includes(agent);
3487
+ const linkPlan = await planAgentLinkNames(
3488
+ [...desiredByAgent[agent].keys()].map((folderName) => ({
3489
+ folderName,
3490
+ readableName: external ? readableNames.get(folderName) ?? null : null
3491
+ })),
3492
+ agentDir,
3493
+ skillsDir,
3494
+ managedRoots,
3495
+ ownsWholeFolder
3496
+ );
3497
+ const movedTargets = new Set(external ? [...linkPlan.values()].filter((name) => isNativeSkill(desiredByAgent[agent].get(name))).map((name) => path2.resolve(skillsDir, name)) : []);
3498
+ if (ownsWholeFolder) {
3499
+ result.removed += await removeUndesiredManagedSymlinks(
3500
+ agentDir,
3501
+ new Set(linkPlan.keys()),
3502
+ managedRoots,
3503
+ result.failures,
3504
+ agent,
3505
+ movedTargets
3506
+ );
3197
3507
  }
3198
- for (const skillName of desiredSkills) {
3508
+ let namesByTarget = /* @__PURE__ */ new Map();
3509
+ if (movedTargets.size > 0) {
3510
+ try {
3511
+ namesByTarget = await linkNamesByTarget(agentDir, movedTargets);
3512
+ } catch (error) {
3513
+ result.failures.push({ name: agentFolderFailureName(agent), error: `Could not read agent skills directory (${error.message})` });
3514
+ }
3515
+ }
3516
+ for (const [linkName, skillName] of linkPlan) {
3199
3517
  const targetPath = path2.join(skillsDir, skillName);
3200
- const linkPath = path2.join(agentDir, safeName(skillName, agentDir));
3518
+ const linkPath = path2.join(agentDir, safeName(linkName, agentDir));
3201
3519
  try {
3202
3520
  if (!(await fs2.stat(path2.join(targetPath, "SKILL.md"))).isFile()) throw new Error("Missing SKILL.md");
3203
3521
  } catch {
@@ -3225,7 +3543,18 @@ async function syncSymlinks(skills, skillsDir = LEGACY_AGENTS_SKILLS_DIR, option
3225
3543
  result.skipped += 1;
3226
3544
  }
3227
3545
  if (syncOutcome !== "blocked") {
3228
- result.verifiedAgentLinks[skillName] = { ...result.verifiedAgentLinks[skillName], [agent]: true };
3546
+ result.verifiedAgentLinks[skillName] = {
3547
+ ...result.verifiedAgentLinks[skillName],
3548
+ [agent]: linkName === skillName ? true : linkName
3549
+ };
3550
+ const otherNames = (namesByTarget.get(path2.resolve(targetPath)) ?? []).filter((name) => name.toLowerCase() !== linkName.toLowerCase());
3551
+ if (otherNames.length > 0) {
3552
+ try {
3553
+ result.removed += await unlinkIfTarget(agentDir, otherNames, path2.resolve(targetPath));
3554
+ } catch (error) {
3555
+ result.failures.push({ name: skillName, error: `${agentFailureLabel(agent)}: could not remove skill link (${error.message})` });
3556
+ }
3557
+ }
3229
3558
  }
3230
3559
  }
3231
3560
  }
@@ -3331,7 +3660,7 @@ var MIRROR_ONLY_DEPS = {
3331
3660
  syncSymlinks: async () => ({ linked: 0, removed: 0, skipped: 0, verifiedAgentLinks: {} })
3332
3661
  };
3333
3662
  async function forgetOtherAccountsAgentLinks(paths) {
3334
- const usersDir = dirname5(dirname5(paths.syncStatePath));
3663
+ const usersDir = dirname6(dirname6(paths.syncStatePath));
3335
3664
  let entries;
3336
3665
  try {
3337
3666
  entries = await fs3.readdir(usersDir, { withFileTypes: true });
@@ -3340,7 +3669,7 @@ async function forgetOtherAccountsAgentLinks(paths) {
3340
3669
  }
3341
3670
  for (const entry of entries) {
3342
3671
  if (!entry.isDirectory()) continue;
3343
- const statePath = join5(usersDir, entry.name, ".notis-sync.json");
3672
+ const statePath = join6(usersDir, entry.name, ".notis-sync.json");
3344
3673
  if (statePath === paths.syncStatePath) continue;
3345
3674
  let state = null;
3346
3675
  try {
@@ -3365,15 +3694,15 @@ async function forgetOtherAccountsAgentLinks(paths) {
3365
3694
  }
3366
3695
  function isolatedLinkOptions(paths) {
3367
3696
  if (!paths.isolatedNamespace && !paths.homeDir) return void 0;
3368
- const root = paths.isolatedNamespace ? join5(paths.syncRoot, "environments", paths.isolatedNamespace, "agents") : paths.homeDir;
3697
+ const root = paths.isolatedNamespace ? join6(paths.syncRoot, "environments", paths.isolatedNamespace, "agents") : paths.homeDir;
3369
3698
  return {
3370
3699
  agentSkillDirs: {
3371
3700
  notis: paths.skillsDir,
3372
- claude_code: join5(root, ".claude", "skills"),
3373
- cursor: join5(root, ".cursor", "skills"),
3374
- codex: join5(root, ".codex", "skills")
3701
+ claude_code: join6(root, ".claude", "skills"),
3702
+ cursor: join6(root, ".cursor", "skills"),
3703
+ codex: join6(root, ".codex", "skills")
3375
3704
  },
3376
- legacyGlobalSkillsDir: join5(root, ".agents", "skills")
3705
+ legacyGlobalSkillsDir: join6(root, ".agents", "skills")
3377
3706
  };
3378
3707
  }
3379
3708
  function assertSyncEnvironment(pull, settings) {
@@ -3869,13 +4198,13 @@ async function runSkillSync(serverUrl, jwt, dependencies = {}, options = {}) {
3869
4198
  }
3870
4199
 
3871
4200
  // src/runtime/sync-skills.js
3872
- import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
4201
+ import { createHash as createHash6, randomUUID as randomUUID3 } from "node:crypto";
3873
4202
  import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
3874
4203
  import { homedir as homedir4 } from "node:os";
3875
- import { dirname as dirname7, join as join7 } from "node:path";
4204
+ import { dirname as dirname8, join as join8 } from "node:path";
3876
4205
 
3877
4206
  // src/runtime/base-skills.js
3878
- import { dirname as dirname6, join as join6, relative, resolve as resolve3 } from "node:path";
4207
+ import { dirname as dirname7, join as join7, relative, resolve as resolve3 } from "node:path";
3879
4208
  import { fileURLToPath as fileURLToPath2 } from "node:url";
3880
4209
  var BASE_SKILL_NAMES2 = Object.freeze([
3881
4210
  "notis-spaces",
@@ -3883,7 +4212,7 @@ var BASE_SKILL_NAMES2 = Object.freeze([
3883
4212
  "notis-cli"
3884
4213
  ]);
3885
4214
  var RETIRED_BASE_SKILL_NAMES = Object.freeze(["notis-apps", "notis-reports"]);
3886
- var HERE = dirname6(fileURLToPath2(import.meta.url));
4215
+ var HERE = dirname7(fileURLToPath2(import.meta.url));
3887
4216
 
3888
4217
  // src/runtime/sync-skills.js
3889
4218
  var DEFAULT_LOCK_TIMEOUT_MS = 3e4;
@@ -3892,7 +4221,7 @@ var DEFAULT_LOCK_POLL_MS = 50;
3892
4221
  async function lockSnapshot(lockDirectory) {
3893
4222
  try {
3894
4223
  const [raw, metadata] = await Promise.all([
3895
- readFile(join7(lockDirectory, "owner"), "utf8").catch(() => ""),
4224
+ readFile(join8(lockDirectory, "owner"), "utf8").catch(() => ""),
3896
4225
  stat(lockDirectory)
3897
4226
  ]);
3898
4227
  let owner = {};
@@ -3928,11 +4257,11 @@ function delay(milliseconds) {
3928
4257
  return new Promise((resolve4) => setTimeout(resolve4, milliseconds));
3929
4258
  }
3930
4259
  async function quarantineStaleLock(lockDirectory, snapshot) {
3931
- const quarantineRoot = join7(dirname7(lockDirectory), ".stale-operation-locks");
3932
- const snapshotToken = createHash5("sha256").update(JSON.stringify(snapshot)).digest("hex");
4260
+ const quarantineRoot = join8(dirname8(lockDirectory), ".stale-operation-locks");
4261
+ const snapshotToken = createHash6("sha256").update(JSON.stringify(snapshot)).digest("hex");
3933
4262
  await mkdir(quarantineRoot, { recursive: true, mode: 448 });
3934
4263
  try {
3935
- await rename(lockDirectory, join7(quarantineRoot, snapshotToken));
4264
+ await rename(lockDirectory, join8(quarantineRoot, snapshotToken));
3936
4265
  return true;
3937
4266
  } catch (error) {
3938
4267
  if (["EEXIST", "ENOTEMPTY", "ENOENT"].includes(error?.code)) return false;
@@ -3940,12 +4269,12 @@ async function quarantineStaleLock(lockDirectory, snapshot) {
3940
4269
  }
3941
4270
  }
3942
4271
  async function publishOwnedLock(lockDirectory, owner) {
3943
- const quarantineRoot = join7(dirname7(lockDirectory), ".stale-operation-locks");
3944
- const staging = join7(quarantineRoot, `staging.${owner.id}`);
4272
+ const quarantineRoot = join8(dirname8(lockDirectory), ".stale-operation-locks");
4273
+ const staging = join8(quarantineRoot, `staging.${owner.id}`);
3945
4274
  await mkdir(quarantineRoot, { recursive: true, mode: 448 });
3946
4275
  await mkdir(staging, { mode: 448 });
3947
4276
  try {
3948
- await writeFile(join7(staging, "owner"), JSON.stringify(owner), { mode: 384 });
4277
+ await writeFile(join8(staging, "owner"), JSON.stringify(owner), { mode: 384 });
3949
4278
  await rename(staging, lockDirectory);
3950
4279
  } catch (error) {
3951
4280
  await rm(staging, { recursive: true, force: true });
@@ -3957,8 +4286,8 @@ async function publishOwnedLock(lockDirectory, owner) {
3957
4286
  async function releaseOwnedLock(lockDirectory, ownerId) {
3958
4287
  const owner = await lockSnapshot(lockDirectory);
3959
4288
  if (owner?.id !== ownerId) return;
3960
- const quarantineRoot = join7(dirname7(lockDirectory), ".stale-operation-locks");
3961
- const releasedDirectory = join7(quarantineRoot, `released.${ownerId}`);
4289
+ const quarantineRoot = join8(dirname8(lockDirectory), ".stale-operation-locks");
4290
+ const releasedDirectory = join8(quarantineRoot, `released.${ownerId}`);
3962
4291
  await mkdir(quarantineRoot, { recursive: true, mode: 448 });
3963
4292
  try {
3964
4293
  await rename(lockDirectory, releasedDirectory);
@@ -3975,10 +4304,10 @@ async function withSkillSyncLock(callback, {
3975
4304
  pollMs = DEFAULT_LOCK_POLL_MS,
3976
4305
  now = () => Date.now()
3977
4306
  } = {}) {
3978
- const lockDirectory = join7(home, ".notis", "skills", ".operation-lock");
4307
+ const lockDirectory = join8(home, ".notis", "skills", ".operation-lock");
3979
4308
  const ownerId = `${process.pid}.${randomUUID3()}`;
3980
4309
  const deadline = now() + timeoutMs;
3981
- await mkdir(dirname7(lockDirectory), { recursive: true, mode: 448 });
4310
+ await mkdir(dirname8(lockDirectory), { recursive: true, mode: 448 });
3982
4311
  for (; ; ) {
3983
4312
  try {
3984
4313
  await publishOwnedLock(lockDirectory, { id: ownerId, pid: process.pid, at: now() });
@@ -4004,7 +4333,7 @@ async function withSkillSyncLock(callback, {
4004
4333
  let heartbeatInFlight = Promise.resolve();
4005
4334
  const refreshHeartbeat = async () => {
4006
4335
  if (heartbeatStopped) return;
4007
- const temporaryOwnerPath = join7(lockDirectory, `.owner.${ownerId}.tmp`);
4336
+ const temporaryOwnerPath = join8(lockDirectory, `.owner.${ownerId}.tmp`);
4008
4337
  await writeFile(
4009
4338
  temporaryOwnerPath,
4010
4339
  JSON.stringify({ id: ownerId, pid: process.pid, at: now() }),
@@ -4015,7 +4344,7 @@ async function withSkillSyncLock(callback, {
4015
4344
  await rm(temporaryOwnerPath, { force: true });
4016
4345
  return;
4017
4346
  }
4018
- await rename(temporaryOwnerPath, join7(lockDirectory, "owner"));
4347
+ await rename(temporaryOwnerPath, join8(lockDirectory, "owner"));
4019
4348
  };
4020
4349
  const heartbeat = setInterval(() => {
4021
4350
  heartbeatInFlight = heartbeatInFlight.then(refreshHeartbeat).catch(() => void 0);
@@ -4048,7 +4377,7 @@ function currentCliProfile() {
4048
4377
  function signInFingerprint(profileName, config = loadConfig()) {
4049
4378
  const profile = getProfile(config, profileName);
4050
4379
  if (!profile.oauth_client_id && !profile.oauth_access_expires_at) return null;
4051
- return createHash6("sha256").update(JSON.stringify([
4380
+ return createHash7("sha256").update(JSON.stringify([
4052
4381
  profile.oauth_issuer ?? null,
4053
4382
  profile.oauth_client_id ?? null,
4054
4383
  profile.oauth_user_id ?? null,
@@ -4080,7 +4409,7 @@ async function runAutomaticSkillSync({ profile, apiBase, userId }, {
4080
4409
  }
4081
4410
  function readStatus(target) {
4082
4411
  try {
4083
- return JSON.parse(readFileSync5(target, "utf8"));
4412
+ return JSON.parse(readFileSync6(target, "utf8"));
4084
4413
  } catch {
4085
4414
  return null;
4086
4415
  }
@@ -4092,13 +4421,13 @@ async function main(args = process.argv.slice(2), {
4092
4421
  deadlineMs = 24e4
4093
4422
  } = {}) {
4094
4423
  const [profile, apiBase, userId] = args;
4095
- const root = join8(home, ".notis", "skills", "service");
4096
- const target = join8(root, "status.json");
4424
+ const root = join9(home, ".notis", "skills", "service");
4425
+ const target = join9(root, "status.json");
4097
4426
  const record = (value) => {
4098
- mkdirSync5(root, { recursive: true, mode: 448 });
4427
+ mkdirSync6(root, { recursive: true, mode: 448 });
4099
4428
  const temporary = `${target}.${process.pid}.tmp`;
4100
- writeFileSync5(temporary, JSON.stringify({ ...value, profile, at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2), { mode: 384 });
4101
- renameSync5(temporary, target);
4429
+ writeFileSync6(temporary, JSON.stringify({ ...value, profile, at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2), { mode: 384 });
4430
+ renameSync6(temporary, target);
4102
4431
  };
4103
4432
  let signIn = null;
4104
4433
  try {