@tpsdev-ai/flair 0.63.0 → 0.63.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.
Files changed (63) hide show
  1. package/README.md +8 -7
  2. package/SECURITY.md +55 -33
  3. package/dist/bridges/runtime/import-runner.js +4 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +243 -83
  6. package/dist/commands/agent.js +298 -72
  7. package/dist/commands/attention.js +2 -0
  8. package/dist/commands/bootstrap.js +2 -0
  9. package/dist/commands/bridge.js +10 -0
  10. package/dist/commands/doctor.js +87 -42
  11. package/dist/commands/export.js +141 -11
  12. package/dist/commands/import.js +36 -15
  13. package/dist/commands/init.js +373 -157
  14. package/dist/commands/keys.js +12 -8
  15. package/dist/commands/mcp.js +146 -62
  16. package/dist/commands/memory.js +5 -2
  17. package/dist/commands/migrate-harness-memory.js +9 -3
  18. package/dist/commands/principal.js +19 -14
  19. package/dist/commands/quality.js +23 -3
  20. package/dist/commands/reembed.js +468 -111
  21. package/dist/commands/search.js +2 -0
  22. package/dist/commands/service.js +25 -0
  23. package/dist/commands/status.js +130 -107
  24. package/dist/doctor-client.js +2 -23
  25. package/dist/federation/scheduler.js +148 -12
  26. package/dist/keystore.js +77 -10
  27. package/dist/lib/agent-key-file.js +509 -0
  28. package/dist/lib/agent-rotation-lock.js +249 -0
  29. package/dist/lib/atomic-write.js +2 -2
  30. package/dist/lib/auth-resolve.js +14 -14
  31. package/dist/lib/key-dir.js +203 -0
  32. package/dist/lib/launchd-management.js +7 -3
  33. package/dist/lib/local-instance-pair.js +8 -1
  34. package/dist/lib/node-alias-path.js +50 -2
  35. package/dist/lib/remote-admin-pass.js +157 -0
  36. package/dist/lib/scheduler-platform.js +13 -0
  37. package/dist/lib/service-repoint.js +13 -4
  38. package/dist/lib/skill-seed.js +35 -3
  39. package/dist/lib/terminal-text.js +32 -0
  40. package/dist/mcp-client-assertion.js +5 -4
  41. package/dist/resources/Memory.js +47 -3
  42. package/dist/resources/health.js +39 -22
  43. package/dist/resources/in-process-api.js +74 -11
  44. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  45. package/dist/resources/mcp-handler.js +40 -1
  46. package/dist/resources/mcp-oauth.js +17 -1
  47. package/dist/resources/mcp-tool-scopes.js +69 -0
  48. package/dist/resources/mcp-tools.js +10 -0
  49. package/dist/resources/skill-version-write.js +16 -0
  50. package/dist/src/keystore.js +77 -10
  51. package/dist/src/lib/atomic-write.js +2 -2
  52. package/dist/src/lib/key-dir.js +203 -0
  53. package/dist/src/lib/scheduler-platform.js +13 -0
  54. package/docs/access-control.md +21 -12
  55. package/docs/api-reference.md +35 -24
  56. package/docs/auth.md +31 -22
  57. package/docs/deploying-on-fabric.md +10 -2
  58. package/docs/embedding-in-a-harper-app.md +7 -7
  59. package/docs/entity-vocabulary.md +4 -5
  60. package/docs/hosted-on-fabric.md +1 -1
  61. package/docs/secrets-and-keys.md +8 -13
  62. package/docs/upgrade.md +15 -5
  63. package/package.json +1 -1
@@ -57,14 +57,15 @@
57
57
  * `flair federation sync --admin-pass-file`, which reads it through
58
58
  * readAdminPassFileSecure() and refuses a file that is not owner-only.
59
59
  */
60
- import { existsSync, chmodSync, rmSync, readFileSync, mkdirSync, realpathSync } from "node:fs";
60
+ import { existsSync, chmodSync, rmSync, readFileSync, mkdirSync, realpathSync, openSync, fstatSync, readSync, closeSync, statSync, constants as fsConstants, } from "node:fs";
61
61
  import { resolve, dirname, isAbsolute } from "node:path";
62
62
  import { fileURLToPath } from "node:url";
63
- import { escapeXml, unescapeXml } from "../lib/xml-escape.js";
63
+ import { escapeXml } from "../lib/xml-escape.js";
64
64
  import { snapshotRegularFile, writeFilesAtomically } from "../lib/atomic-write.js";
65
- import { preferVersionManagerAlias } from "../lib/node-alias-path.js";
65
+ import { homebrewOptAlias, preferVersionManagerAlias } from "../lib/node-alias-path.js";
66
66
  import { compareVersions, isNpmGlobalFlairTree } from "../lib/tree-divergence.js";
67
67
  import { findFlairPackageDir } from "../lib/upgrade-exec-path.js";
68
+ import { readPlistStructure } from "../lib/service-repoint.js";
68
69
  import { detectPlatform as detectPlatformFor, spawnReport, readTemplate, renderTemplateWith, writeFileWithDir, interpretActiveResult, describeLoadFailure as describeLoadFailureFor, describeExitCode, resolveNodeBin, resolveFlairBin, formatFlairBinWarning, verifyFirstRun, probeUserLingerEnabled, STATUS_CHECK_TIMEOUT_MS, } from "../lib/scheduler-platform.js";
69
70
  import { resolveHome } from "../lib/home.js";
70
71
  export const LAUNCHD_LABEL = "dev.flair.federation.sync";
@@ -666,15 +667,136 @@ export function federationShimShapeProblem(shimText, templateText) {
666
667
  }
667
668
  return null;
668
669
  }
669
- /** Does the federation-sync unit exec `shimPath`? Returns the reason it does not, or null. */
670
+ /** The largest unit or shim file inspectFederationShimNode reads; the generated files are a few KiB. */
671
+ const INSPECT_MAX_BYTES = 64 * 1024;
672
+ /**
673
+ * `path`'s text when it is a regular file of at most INSPECT_MAX_BYTES. It is
674
+ * opened with O_NOFOLLOW, so a symlink at `path` itself is not followed. null
675
+ * otherwise, and when it cannot be read.
676
+ */
677
+ function readBoundedRegularFile(path) {
678
+ let fd;
679
+ try {
680
+ fd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
681
+ }
682
+ catch {
683
+ return null;
684
+ }
685
+ try {
686
+ if (!fstatSync(fd).isFile())
687
+ return null;
688
+ const buf = Buffer.alloc(INSPECT_MAX_BYTES + 1);
689
+ let n = 0;
690
+ while (n < buf.length) {
691
+ const got = readSync(fd, buf, n, buf.length - n, null);
692
+ if (got === 0)
693
+ break;
694
+ n += got;
695
+ }
696
+ return n > INSPECT_MAX_BYTES ? null : buf.subarray(0, n).toString("utf-8");
697
+ }
698
+ catch {
699
+ return null;
700
+ }
701
+ finally {
702
+ closeSync(fd);
703
+ }
704
+ }
705
+ /**
706
+ * For `flair doctor` (flair#3056): the node path on the federation-sync shim's
707
+ * exec line when that path does not exist (stat fails with ENOENT or ENOTDIR).
708
+ * Returned only when the scheduler unit file names `shimPath` as its program
709
+ * (federationUnitExecsShim) and the shim runs exactly the commands `flair
710
+ * federation sync enable` writes. null otherwise, including when either file
711
+ * cannot be read through readBoundedRegularFile or the stat fails another way.
712
+ */
713
+ export function inspectFederationShimNode(opts = {}) {
714
+ const plat = detectPlatform(opts.platformOverride);
715
+ const shimPath = opts.shimPathOverride ?? SHIM_PATH_DEFAULT;
716
+ const unitPath = plat === "darwin"
717
+ ? (opts.launchdPlistOverride ?? LAUNCHD_PLIST_PATH)
718
+ : (opts.systemdServiceOverride ?? SYSTEMD_SERVICE_PATH);
719
+ const unitText = readBoundedRegularFile(unitPath);
720
+ if (unitText === null || federationUnitExecsShim(plat, unitText, shimPath) !== null)
721
+ return null;
722
+ const shimText = readBoundedRegularFile(shimPath);
723
+ if (shimText === null || !shimText.includes(SHIM_MARKER))
724
+ return null;
725
+ const exec = [...shimText.matchAll(SHIM_EXEC_LINE_RE)];
726
+ if (exec.length !== 1)
727
+ return null;
728
+ let templateText;
729
+ try {
730
+ templateText = readTemplate(opts.templateRootOverride ?? defaultTemplateRoot(), "bin/flair-federation-sync.sh.tmpl");
731
+ }
732
+ catch {
733
+ return null;
734
+ }
735
+ if (federationShimShapeProblem(shimText, templateText) !== null)
736
+ return null;
737
+ const nodeBin = exec[0][1];
738
+ if (!isAbsolute(nodeBin))
739
+ return null;
740
+ try {
741
+ statSync(nodeBin);
742
+ return null;
743
+ }
744
+ catch (err) {
745
+ return err?.code === "ENOENT" || err?.code === "ENOTDIR" ? { unitPath, shimPath, nodeBin } : null;
746
+ }
747
+ }
748
+ const XML_COMMENT_RE = /<!--[\s\S]*?-->/g;
749
+ /**
750
+ * `text` with its XML comments removed, or null when they cannot be removed
751
+ * cleanly: removing them is repeated until the text stops changing, and a
752
+ * second pass that removes anything (a removal formed a new `<!--`) or a `<!--`
753
+ * left at the end (an unclosed comment) gives null.
754
+ */
755
+ function stripXmlComments(text) {
756
+ let out = text;
757
+ let changed = 0;
758
+ for (;;) {
759
+ const next = out.replace(XML_COMMENT_RE, "");
760
+ if (next === out)
761
+ break;
762
+ if (++changed > 1)
763
+ return null;
764
+ out = next;
765
+ }
766
+ return out.includes("<!--") ? null : out;
767
+ }
768
+ /**
769
+ * Does the federation-sync unit file name `shimPath` as its program? Returns
770
+ * the reason it does not, or null. A plist is read as XML structure after its
771
+ * comments are removed (stripXmlComments), so a key inside a comment or a
772
+ * nested dict is not read.
773
+ */
670
774
  function federationUnitExecsShim(plat, text, shimPath) {
671
775
  if (plat === "darwin") {
672
- const label = /<key>Label<\/key>\s*<string>([^<]*)<\/string>/.exec(text);
673
- if (!label || unescapeXml(label[1]) !== LAUNCHD_LABEL)
776
+ const stripped = stripXmlComments(text);
777
+ if (stripped === null)
778
+ return "its XML comments overlap or one is not closed";
779
+ const doc = readPlistStructure(stripped);
780
+ if ("problem" in doc)
781
+ return `it is not a plist flair can read (it has ${doc.problem})`;
782
+ const label = doc.top.get("Label");
783
+ if (label?.t !== "string" || label.v !== LAUNCHD_LABEL)
674
784
  return `its Label is not ${LAUNCHD_LABEL}`;
675
- const block = /<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(text);
676
- const args = block ? [...block[1].matchAll(/<string>([^<]*)<\/string>/g)].map((m) => unescapeXml(m[1])) : [];
677
- if (args.length !== 1 || resolve(args[0]) !== resolve(shimPath)) {
785
+ if (doc.top.has("Program"))
786
+ return "it declares a Program key, which launchd runs instead of ProgramArguments[0]";
787
+ const block = doc.top.get("ProgramArguments");
788
+ const items = block?.t === "array" ? block.items : [];
789
+ const args = items.map((v) => (v.t === "string" ? v.v : `<${v.t}>`));
790
+ if (items.length !== 1 || items[0].t !== "string") {
791
+ return `its ProgramArguments are ${JSON.stringify(args)}, not [${JSON.stringify(shimPath)}]`;
792
+ }
793
+ // launchd resolves a relative ProgramArguments[0] against the unit's own
794
+ // WorkingDirectory, not this process's cwd, so only an absolute program
795
+ // path can be attributed to the shim.
796
+ if (!isAbsolute(args[0])) {
797
+ return `its ProgramArguments program ${JSON.stringify(args[0])} is not an absolute path`;
798
+ }
799
+ if (resolve(args[0]) !== resolve(shimPath)) {
678
800
  return `its ProgramArguments are ${JSON.stringify(args)}, not [${JSON.stringify(shimPath)}]`;
679
801
  }
680
802
  return null;
@@ -692,7 +814,15 @@ function federationUnitExecsShim(plat, text, shimPath) {
692
814
  if (section === "service" && /^ExecStart\s*=/.test(line))
693
815
  execs.push(line.replace(/^ExecStart\s*=\s*/, "").replace(/^[-@:+!]+/, ""));
694
816
  }
695
- if (execs.length !== 1 || resolve(execs[0]) !== resolve(shimPath)) {
817
+ if (execs.length !== 1) {
818
+ return `its ExecStart is ${JSON.stringify(execs)}, not ${JSON.stringify(shimPath)}`;
819
+ }
820
+ // systemd does not resolve a relative ExecStart against this process's cwd,
821
+ // so only an absolute program path can be attributed to the shim.
822
+ if (!isAbsolute(execs[0])) {
823
+ return `its ExecStart program ${JSON.stringify(execs[0])} is not an absolute path`;
824
+ }
825
+ if (resolve(execs[0]) !== resolve(shimPath)) {
696
826
  return `its ExecStart is ${JSON.stringify(execs)}, not ${JSON.stringify(shimPath)}`;
697
827
  }
698
828
  return null;
@@ -748,7 +878,7 @@ export function rewriteFederationSchedulerRuntime(opts = {}) {
748
878
  }
749
879
  const notOurs = federationUnitExecsShim(plat, unitText, shimPath);
750
880
  if (notOurs)
751
- return refused(`${unitPath} does not exec the flair-generated shim: ${notOurs}.`);
881
+ return refused(`flair could not confirm that ${unitPath} execs the flair-generated shim: ${notOurs}.`);
752
882
  if (!exists(shimPath))
753
883
  return refused(`${unitPath} execs ${shimPath}, which does not exist.`);
754
884
  // A regular file (never followed through a symlink), read once: the plan and
@@ -794,10 +924,16 @@ export function rewriteFederationSchedulerRuntime(opts = {}) {
794
924
  let nextNode = oldNode;
795
925
  let nextFlair = oldFlair;
796
926
  if (oldPkg && canonical(oldPkg.dir) === canonical(cliTree)) {
797
- // Same install tree as this CLI.
927
+ // Same install tree as this CLI. An existing Homebrew Cellar node is
928
+ // replaced by its opt alias when that alias resolves to the same binary
929
+ // (flair#3056).
930
+ const brewAlias = oldNodeMissing ? null : homebrewOptAlias(oldNode, { exists, realpath });
798
931
  if (oldNodeMissing) {
799
932
  nextNode = newNode;
800
933
  }
934
+ else if (brewAlias !== null) {
935
+ nextNode = brewAlias;
936
+ }
801
937
  else if (canonical(oldNode) === canonical(newNode)) {
802
938
  return { ...base, status: "current", detail: `${shimPath} already runs this CLI's tree (${cliTree}).` };
803
939
  }
package/dist/keystore.js CHANGED
@@ -8,9 +8,10 @@
8
8
  * or an auto-generated random passphrase stored at ~/.flair/keys/.passphrase
9
9
  * (mode 0600). Never falls back to guessable data.
10
10
  */
11
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
11
+ import { closeSync, constants, existsSync, fstatSync, linkSync, mkdirSync, openSync, readFileSync, unlinkSync } from "node:fs";
12
12
  import { join } from "node:path";
13
13
  import { resolveHome } from "./lib/home.js";
14
+ import { agentKeyPath } from "./lib/key-dir.js";
14
15
  import { writeFilesAtomically } from "./lib/atomic-write.js";
15
16
  import { randomBytes, createCipheriv, createDecipheriv, hkdfSync, } from "node:crypto";
16
17
  // ─── Helpers ────────────────────────────────────────────────────────────────
@@ -28,7 +29,7 @@ function keysDir() {
28
29
  function keyPath(instanceId) {
29
30
  // Sanitize instanceId to prevent directory traversal
30
31
  const safe = instanceId.replace(/[^a-zA-Z0-9_-]/g, "_");
31
- return join(keysDir(), `${safe}.key`);
32
+ return agentKeyPath(keysDir(), safe);
32
33
  }
33
34
  /**
34
35
  * Path to the auto-generated passphrase file.
@@ -37,20 +38,54 @@ function keyPath(instanceId) {
37
38
  function passphrasePath() {
38
39
  return join(keysDir(), ".passphrase");
39
40
  }
41
+ /**
42
+ * Read the auto-generated passphrase through one no-follow descriptor, after
43
+ * refusing a file wider than owner-only. On Windows the mode check is skipped
44
+ * and the file is read by path.
45
+ */
46
+ function readPassphraseFile(pp, hooks) {
47
+ const read = hooks.read ?? ((source) => readFileSync(source, "utf-8"));
48
+ const checked = (source) => {
49
+ const passphrase = read(source).trim();
50
+ if (!passphrase)
51
+ throw new Error(`passphrase file ${pp} is empty`);
52
+ return passphrase;
53
+ };
54
+ if ((hooks.platform ?? process.platform) === "win32") {
55
+ return checked(pp);
56
+ }
57
+ const fd = openSync(pp, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
58
+ try {
59
+ const st = (hooks.fstat ?? fstatSync)(fd);
60
+ if ((st.mode & 0o077) !== 0) {
61
+ throw new Error(`passphrase file ${pp} is accessible to other users (mode ${(st.mode & 0o777).toString(8).padStart(3, "0")}); ` +
62
+ `run chmod 600 ${pp} to make it owner-only`);
63
+ }
64
+ return checked(fd);
65
+ }
66
+ finally {
67
+ closeSync(fd);
68
+ }
69
+ }
40
70
  /**
41
71
  * Get or create the keystore passphrase.
42
72
  * Priority: FLAIR_KEY_PASSPHRASE env var > auto-generated file.
43
73
  * Never falls back to guessable data (hostname, username, etc.).
44
74
  */
45
- function getPassphrase() {
75
+ function getPassphrase(hooks = {}) {
46
76
  // Explicit env var takes priority
47
77
  if (process.env.FLAIR_KEY_PASSPHRASE) {
48
78
  return process.env.FLAIR_KEY_PASSPHRASE;
49
79
  }
50
80
  const pp = passphrasePath();
51
- // Read existing auto-generated passphrase
52
- if (existsSync(pp)) {
53
- return readFileSync(pp, "utf-8").trim();
81
+ // Read existing auto-generated passphrase; a missing file falls through to
82
+ // generation, and any other open/read failure propagates.
83
+ try {
84
+ return readPassphraseFile(pp, hooks);
85
+ }
86
+ catch (error) {
87
+ if (error?.code !== "ENOENT")
88
+ throw error;
54
89
  }
55
90
  // Generate a cryptographically random passphrase and persist it
56
91
  const dir = keysDir();
@@ -58,8 +93,40 @@ function getPassphrase() {
58
93
  mkdirSync(dir, { recursive: true, mode: 0o700 });
59
94
  }
60
95
  const generated = randomBytes(32).toString("base64url");
61
- writeFileSync(pp, generated, { mode: 0o600 });
62
- return generated;
96
+ const staged = join(dir, `.passphrase.${process.pid}.${randomBytes(8).toString("hex")}.tmp`);
97
+ writeFilesAtomically([{ path: staged, content: generated, mode: 0o600 }]);
98
+ let passphrase = generated;
99
+ let failure;
100
+ try {
101
+ hooks.beforePublish?.();
102
+ // Link the complete file without replacing a competing passphrase; reread on conflict.
103
+ try {
104
+ (hooks.link ?? linkSync)(staged, pp);
105
+ }
106
+ catch (error) {
107
+ const code = error?.code;
108
+ if (code !== "EEXIST") {
109
+ throw new Error(`could not publish the generated passphrase at ${pp} (${code}: ${error.message}); ` +
110
+ "if the keys dir's volume does not support hard links, set FLAIR_KEY_PASSPHRASE or use a keys dir on a volume that does");
111
+ }
112
+ passphrase = readPassphraseFile(pp, hooks);
113
+ }
114
+ }
115
+ catch (error) {
116
+ failure = { error };
117
+ }
118
+ try {
119
+ unlinkSync(staged);
120
+ }
121
+ catch (error) {
122
+ if (error?.code !== "ENOENT") {
123
+ const cleanup = `could not remove staged passphrase ${staged} (${error?.code}: ${error.message})`;
124
+ throw new Error(`${failure ? failure.error.message : `passphrase at ${pp}`}; ${cleanup}`, { cause: failure ? failure.error : error });
125
+ }
126
+ }
127
+ if (failure)
128
+ throw failure.error;
129
+ return passphrase;
63
130
  }
64
131
  /**
65
132
  * Derive a 256-bit encryption key using HKDF.
@@ -116,7 +183,7 @@ class FileKeyStore {
116
183
  }
117
184
  const p = keyPath(instanceId);
118
185
  const encrypted = encryptSeed(seed);
119
- writeFileSync(p, encrypted, { mode: 0o600 });
186
+ writeFilesAtomically([{ path: p, content: encrypted, mode: 0o600 }]);
120
187
  }
121
188
  }
122
189
  /** Singleton keystore instance. */
@@ -193,4 +260,4 @@ export function recordSeedOwner(instanceId, dataDir) {
193
260
  ]);
194
261
  }
195
262
  // Export helpers for testing
196
- export { encryptSeed, decryptSeed, deriveKey, keyPath, keysDir };
263
+ export { encryptSeed, decryptSeed, deriveKey, getPassphrase, keyPath, keysDir };