@tpsdev-ai/flair 0.58.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +1030 -343
  10. package/dist/commands/agent.js +384 -45
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +601 -163
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +146 -53
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +120 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +27 -2
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1775 -338
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +103 -7
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +227 -64
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -1,8 +1,13 @@
1
1
  import nacl from "tweetnacl";
2
- import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync } from "node:fs";
2
+ import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync, unlinkSync, realpathSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import * as render from "../render.js";
5
5
  import { resolveAdminPassFromSources, defaultKeysDir, resolveLocalAdminPass, resolveAdminUser, resolveKeyPath, authFetch, } from "../lib/auth-resolve.js";
6
+ import { encodeRecordId } from "../lib/record-id-path.js";
7
+ import { resolveLocalDeleteInstance } from "../lib/local-delete-instance.js";
8
+ import { invalidAgentIdMessage, isValidAgentId } from "../lib/agent-id-rule.js";
9
+ import { agentHomeEndpoint, resolveTargetInstanceId, runAgentHomeStamp, stampLeftoverLines, } from "../lib/agent-home.js";
10
+ import { confirmedPurgeIds } from "../lib/memory-purge-response.js";
6
11
  let cli;
7
12
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
8
13
  export function bindCli(fns) {
@@ -12,19 +17,198 @@ const api = (method, path, body, options) => cli.api(method, path, body, options
12
17
  const b64url = (bytes) => cli.b64url(bytes);
13
18
  const privKeyPath = (agentId, keysDir) => cli.privKeyPath(agentId, keysDir);
14
19
  const pubKeyPath = (agentId, keysDir) => cli.pubKeyPath(agentId, keysDir);
20
+ /**
21
+ * flair#2479 — check each key's canonical target before unlinking.
22
+ * Return successful unlinks; invalid ids require manual cleanup.
23
+ */
24
+ export function removeAgentKeyFiles(agentId, keysDir) {
25
+ if (!isValidAgentId(agentId))
26
+ return { removed: [], manual: true };
27
+ let root;
28
+ try {
29
+ root = realpathSync(keysDir);
30
+ }
31
+ catch {
32
+ return { removed: [], manual: false }; // directory resolution failed
33
+ }
34
+ const removed = [];
35
+ for (const name of [`${agentId}.key`, `${agentId}.pub`, `${agentId}.key.bak`]) {
36
+ let real;
37
+ try {
38
+ real = realpathSync(join(keysDir, name));
39
+ }
40
+ catch {
41
+ continue; // candidate resolution failed
42
+ }
43
+ if (real !== join(root, name))
44
+ continue; // unexpected canonical target; skip
45
+ try {
46
+ unlinkSync(real);
47
+ removed.push(real);
48
+ }
49
+ catch { /* best effort */ }
50
+ }
51
+ return { removed, manual: false };
52
+ }
15
53
  const shouldShowInlineSecretWarning = (optValue, fromEnv, secretFlagNames, flagName) => cli.shouldShowInlineSecretWarning(optValue, fromEnv, secretFlagNames, flagName);
16
54
  const resolveHttpPort = (opts, mode) => cli.resolveHttpPort(opts, mode);
17
55
  const resolveOpsPort = (opts) => cli.resolveOpsPort(opts);
56
+ const resolveAgentHomeTarget = (opts) => cli.resolveAgentHomeTarget(opts);
18
57
  const resolveEffectiveOpsUrl = (opts) => cli.resolveEffectiveOpsUrl(opts);
19
- const seedAgentViaOpsApi = (opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass) => cli.seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass);
58
+ const seedAgentWithLocalHome = (opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass) => cli.seedAgentWithLocalHome(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass);
20
59
  const agentRecordIsAdmin = (record) => cli.agentRecordIsAdmin(record);
60
+ const INLINE_ADMIN_PASS_WARNING = "warning: --admin-pass passed inline. Use FLAIR_ADMIN_PASS without typing its value into a recorded " +
61
+ "shell line (for example, read it from the admin-pass file).";
62
+ /** Operations API URL, same shape as `seedAgentViaOpsApi` (trailing slash). */
63
+ function opsApiUrl(opsPortOrUrl) {
64
+ return typeof opsPortOrUrl === "number"
65
+ ? `http://127.0.0.1:${opsPortOrUrl}/`
66
+ : `${opsPortOrUrl.replace(/\/$/, "")}/`;
67
+ }
68
+ /**
69
+ * Parse an operations `search_by_value` body for one id.
70
+ * `[]` is the only absence. One row with this id and a string `name` is that
71
+ * agent even when `publicKey` is missing or empty: a missing public key is
72
+ * still an existing row and fails the later success check. It is not a
73
+ * missing row. Unreadable, and never treated as absence: a non-array, more
74
+ * than one row, a non-object element, a missing or empty id, a different id,
75
+ * a non-string `publicKey`, or a missing or non-string `name`.
76
+ */
77
+ function parseAgentRows(body, id) {
78
+ if (!Array.isArray(body)) {
79
+ return { ok: false, reason: "operations API returned an unexpected body." };
80
+ }
81
+ if (body.length === 0)
82
+ return { ok: true, row: null };
83
+ if (body.length !== 1) {
84
+ return { ok: false, reason: `operations API returned ${body.length} rows for Agent '${id}'.` };
85
+ }
86
+ const row = body[0];
87
+ if (!row || typeof row !== "object" || Array.isArray(row)) {
88
+ return { ok: false, reason: "operations API returned a malformed Agent row." };
89
+ }
90
+ const rec = row;
91
+ if (typeof rec.id !== "string" || rec.id.length === 0) {
92
+ return { ok: false, reason: "operations API returned a malformed Agent row." };
93
+ }
94
+ if (rec.id !== id) {
95
+ return {
96
+ ok: false,
97
+ reason: `operations API returned Agent '${rec.id}' while looking up '${id}'.`,
98
+ };
99
+ }
100
+ if (rec.publicKey !== undefined && typeof rec.publicKey !== "string") {
101
+ return { ok: false, reason: "operations API returned a malformed Agent row." };
102
+ }
103
+ if (typeof rec.name !== "string") {
104
+ return { ok: false, reason: "operations API returned an Agent row whose name is missing or not a string." };
105
+ }
106
+ const publicKey = typeof rec.publicKey === "string" && rec.publicKey.length > 0 ? rec.publicKey : undefined;
107
+ return {
108
+ ok: true,
109
+ row: {
110
+ id: rec.id,
111
+ name: rec.name,
112
+ ...(publicKey !== undefined ? { publicKey } : {}),
113
+ },
114
+ };
115
+ }
116
+ function agentAlreadyExistsMessage(id) {
117
+ return (`Error: Agent '${id}' already exists; its stored public key was left unchanged. ` +
118
+ `Run \`flair agent rotate-key ${id}\` on the Flair host to replace the key, ` +
119
+ `or \`flair agent remove ${id}\` first and then \`flair agent add ${id}\`. ` +
120
+ `\`flair agent remove\` tries to delete that agent's Memory and Soul rows.`);
121
+ }
122
+ function agentKeyNotStoredMessage(id, stored) {
123
+ let found;
124
+ if (!stored) {
125
+ found = `Reading the record back found no Agent row for '${id}'.`;
126
+ }
127
+ else if (typeof stored.publicKey !== "string" || stored.publicKey.length === 0) {
128
+ found = `An Agent row for '${id}' was found, but it has no usable public key.`;
129
+ }
130
+ else {
131
+ found = `The stored public key is '${stored.publicKey}', which is not the key generated or reused by this command.`;
132
+ }
133
+ return (`Error: Agent '${id}' was not stored with the public key generated or reused by this command. ${found} ` +
134
+ `Run \`flair agent rotate-key ${id}\` on the Flair host to replace the key, ` +
135
+ `or \`flair agent remove ${id}\` first and then \`flair agent add ${id}\`. ` +
136
+ `\`flair agent remove\` tries to delete that agent's Memory and Soul rows.`);
137
+ }
138
+ /**
139
+ * Read one Agent row by id through the operations API.
140
+ * Exits on a failed body read, an empty body, non-JSON, a row whose id is
141
+ * not the one searched, or a row that is unreadable: non-object, missing or
142
+ * empty id, non-string `publicKey`, or missing or non-string `name`.
143
+ * Those results are not "no such agent". A row with this id and a string
144
+ * `name` is returned even when `publicKey` is missing or empty; that is an
145
+ * existing row, and the add success check refuses it. Returns null only
146
+ * when the body is a JSON `[]`.
147
+ */
148
+ async function readStoredAgent(opsPortOrUrl, id, adminUser, adminPass) {
149
+ const auth = Buffer.from(`${adminUser}:${adminPass}`).toString("base64");
150
+ let res;
151
+ try {
152
+ res = await fetch(opsApiUrl(opsPortOrUrl), {
153
+ method: "POST",
154
+ headers: { "Content-Type": "application/json", Authorization: `Basic ${auth}` },
155
+ body: JSON.stringify({
156
+ operation: "search_by_value",
157
+ database: "flair",
158
+ table: "Agent",
159
+ search_attribute: "id",
160
+ search_value: id,
161
+ get_attributes: ["id", "name", "publicKey"],
162
+ }),
163
+ signal: AbortSignal.timeout(10_000),
164
+ });
165
+ }
166
+ catch (err) {
167
+ const message = err instanceof Error ? err.message : String(err);
168
+ console.error(`Error: could not read Agent '${id}': ${message}`);
169
+ process.exit(1);
170
+ }
171
+ let text;
172
+ try {
173
+ text = await res.text();
174
+ }
175
+ catch (err) {
176
+ const message = err instanceof Error ? err.message : String(err);
177
+ console.error(`Error: could not read Agent '${id}': ${message}`);
178
+ process.exit(1);
179
+ }
180
+ if (!res.ok) {
181
+ console.error(`Error: could not read Agent '${id}' (${res.status}): ${text}`);
182
+ process.exit(1);
183
+ }
184
+ if (text.trim().length === 0) {
185
+ console.error(`Error: could not read Agent '${id}': operations API returned an empty body.`);
186
+ process.exit(1);
187
+ }
188
+ let body;
189
+ try {
190
+ body = JSON.parse(text);
191
+ }
192
+ catch {
193
+ console.error(`Error: could not read Agent '${id}': operations API returned a body that is not JSON.`);
194
+ process.exit(1);
195
+ }
196
+ const parsed = parseAgentRows(body, id);
197
+ // `=== false`, not `!parsed.ok`: tsconfig.cli.json is not strict, and `!`
198
+ // does not narrow this union there.
199
+ if (parsed.ok === false) {
200
+ console.error(`Error: could not read Agent '${id}': ${parsed.reason}`);
201
+ process.exit(1);
202
+ }
203
+ return parsed.row;
204
+ }
21
205
  /** Register the `flair agent` command group (flair#1630). */
22
206
  export function register(program) {
23
207
  // ─── flair agent ─────────────────────────────────────────────────────────────
24
208
  const agent = program.command("agent").description("Manage Flair agents");
25
209
  agent
26
210
  .command("add <id>")
27
- .description("Register a new agent in a running Flair instance")
211
+ .description("Register a new agent. Refuses an id whose Agent record already exists")
28
212
  .option("--name <name>", "Display name (defaults to id)")
29
213
  .option("--port <port>", "Harper HTTP port")
30
214
  .option("--admin-pass <pass>", "Admin password for registration")
@@ -32,9 +216,15 @@ export function register(program) {
32
216
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
33
217
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
34
218
  .option("--ops-port <port>", "Harper operations API port")
35
- .option("--target <url>", "Remote Flair REST URL; derives the ops API URL (port-1) to seed the Agent there (env: FLAIR_TARGET)")
219
+ .option("--target <url>", "Remote Flair REST URL; derives ops URL (HTTPS no port/:443 → Fabric ops :9925; HTTP no port/:80 → :19925; other ports 2–65535 → port-1; port 1 refused; env: FLAIR_TARGET)")
36
220
  .option("--ops-target <url>", "Explicit ops API URL to seed the Agent on (env: FLAIR_OPS_TARGET; bypasses port derivation)")
37
221
  .action(async (id, opts) => {
222
+ // flair#2359 — the ONE agent-ID rule, before any key file is written or
223
+ // any insert is attempted. Refuse a non-matching id by name.
224
+ if (!isValidAgentId(id)) {
225
+ console.error(`Error: ${invalidAgentIdMessage(id)}`);
226
+ process.exit(1);
227
+ }
38
228
  const httpPort = resolveHttpPort(opts);
39
229
  const opsPort = resolveOpsPort(opts);
40
230
  const keysDir = opts.keysDir ?? defaultKeysDir();
@@ -92,6 +282,16 @@ export function register(program) {
92
282
  }
93
283
  process.exit(1);
94
284
  }
285
+ // flair#2126 — Harper 5.2.8 skips an insert whose id already exists and
286
+ // still returns OK, so the seed helper's 409/"already exists" path never
287
+ // fires and the old public key stays. Look the id up first and refuse
288
+ // before any key file or insert. A later read-back covers a row that
289
+ // appears in the gap, or an insert that does not store this key.
290
+ const existing = await readStoredAgent(seedOpsTarget, id, adminUser, adminPass);
291
+ if (existing) {
292
+ console.error(agentAlreadyExistsMessage(id));
293
+ process.exit(1);
294
+ }
95
295
  mkdirSync(keysDir, { recursive: true });
96
296
  const privPath = privKeyPath(id, keysDir);
97
297
  const pubPath = pubKeyPath(id, keysDir);
@@ -111,12 +311,17 @@ export function register(program) {
111
311
  pubKeyB64url = b64url(kp.publicKey);
112
312
  console.log(`Keypair written: ${privPath}`);
113
313
  }
114
- await seedAgentViaOpsApi(seedOpsTarget, id, pubKeyB64url, adminUser, adminPass);
314
+ await seedAgentWithLocalHome(seedOpsTarget, id, pubKeyB64url, adminUser, adminPass);
315
+ const stored = await readStoredAgent(seedOpsTarget, id, adminUser, adminPass);
316
+ if (!stored || stored.publicKey !== pubKeyB64url) {
317
+ console.error(agentKeyNotStoredMessage(id, stored));
318
+ process.exit(1);
319
+ }
115
320
  console.log(typeof seedOpsTarget === "string"
116
321
  ? `✅ Agent '${id}' (${name}) registered (ops: ${seedOpsTarget})`
117
322
  : `✅ Agent '${id}' (${name}) registered`);
118
323
  console.log(` Private key: ${privPath}`);
119
- console.log(` Public key: ${pubKeyB64url}`);
324
+ console.log(` Public key: ${stored.publicKey}`);
120
325
  // flair#1280 — connector legibility at provisioning time: an OAuth /mcp
121
326
  // connector resolves its own token subject to an Agent via
122
327
  // Credential(kind:idp), NOT via this key, and the two identities are
@@ -139,8 +344,7 @@ export function register(program) {
139
344
  // fromEnv is true ONLY when the resolved value came from env (no inline override).
140
345
  const adminPassFromEnv = !opts.adminPass && (!!process.env.FLAIR_ADMIN_PASS || !!process.env.HDB_ADMIN_PASSWORD);
141
346
  if (shouldShowInlineSecretWarning(opts.adminPass, adminPassFromEnv, new Set(["--admin-pass"]), "--admin-pass")) {
142
- console.error("warning: --admin-pass passed inline. Consider --admin-pass-from <file> or FLAIR_ADMIN_PASS env " +
143
- "to keep secrets out of shell history.");
347
+ console.error(INLINE_ADMIN_PASS_WARNING);
144
348
  }
145
349
  const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD ?? "";
146
350
  const mode = render.resolveOutputMode(opts);
@@ -227,7 +431,7 @@ export function register(program) {
227
431
  .description("Show agent details")
228
432
  .option("--json", "Emit raw JSON response (also: pipe + FLAIR_OUTPUT=json)")
229
433
  .action(async (id, opts) => {
230
- const out = await api("GET", `/Agent/${id}`);
434
+ const out = await api("GET", `/Agent/${encodeRecordId(id)}`);
231
435
  const mode = render.resolveOutputMode(opts);
232
436
  if (mode === "json") {
233
437
  console.log(render.asJSON(out));
@@ -275,8 +479,7 @@ export function register(program) {
275
479
  // fromEnv is true ONLY when the resolved value came from env (no inline override).
276
480
  const adminPassFromEnv = !opts.adminPass && !!process.env.FLAIR_ADMIN_PASS;
277
481
  if (shouldShowInlineSecretWarning(opts.adminPass, adminPassFromEnv, new Set(["--admin-pass"]), "--admin-pass")) {
278
- console.error("warning: --admin-pass passed inline. Consider --admin-pass-from <file> or FLAIR_ADMIN_PASS env " +
279
- "to keep secrets out of shell history.");
482
+ console.error(INLINE_ADMIN_PASS_WARNING);
280
483
  }
281
484
  const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
282
485
  const adminUser = resolveAdminUser(opts.adminUser);
@@ -333,7 +536,7 @@ export function register(program) {
333
536
  // Verify new key works
334
537
  console.log(`Verifying new Ed25519 auth...`);
335
538
  const httpUrl = `http://127.0.0.1:${httpPort}`;
336
- const verifyRes = await authFetch(httpUrl, id, currentPrivPath, "GET", `/Agent/${id}`);
539
+ const verifyRes = await authFetch(httpUrl, id, currentPrivPath, "GET", `/Agent/${encodeRecordId(id)}`);
337
540
  if (!verifyRes.ok) {
338
541
  console.error(`⚠️ Auth verification failed (${verifyRes.status}). Old key is backed up at: ${backupPrivPath}`);
339
542
  process.exit(1);
@@ -356,7 +559,6 @@ export function register(program) {
356
559
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
357
560
  .option("--force", "Skip interactive confirmation (required when stdin is not a TTY)")
358
561
  .action(async (id, opts) => {
359
- const opsPort = resolveOpsPort(opts);
360
562
  const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
361
563
  const adminUser = resolveAdminUser(opts.adminUser);
362
564
  const keysDir = opts.keysDir ?? defaultKeysDir();
@@ -365,9 +567,11 @@ export function register(program) {
365
567
  process.exit(1);
366
568
  }
367
569
  const auth = `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
570
+ const instance = await resolveLocalDeleteInstance(opts, resolveOpsPort, auth);
368
571
  async function opsPost(body) {
369
- return fetch(`http://127.0.0.1:${opsPort}/`, {
572
+ return fetch(instance.opsUrl, {
370
573
  method: "POST",
574
+ redirect: "error",
371
575
  headers: { "Content-Type": "application/json", Authorization: auth },
372
576
  body: JSON.stringify(body),
373
577
  signal: AbortSignal.timeout(10_000),
@@ -377,9 +581,41 @@ export function register(program) {
377
581
  const agentRes = await opsPost({ operation: "search_by_value", database: "flair", table: "Agent", search_attribute: "id", search_value: id, get_attributes: ["id", "name"] });
378
582
  const agentData = agentRes.ok ? await agentRes.json().catch(() => null) : null;
379
583
  const agentName = agentData?.[0]?.name ?? id;
380
- const memRes = await opsPost({ operation: "search_by_value", database: "flair", table: "Memory", search_attribute: "agentId", search_value: id, get_attributes: ["id"] });
381
- const memories = memRes.ok ? await memRes.json().catch(() => []) : [];
382
- const memoryCount = Array.isArray(memories) ? memories.length : 0;
584
+ async function scanOwnedIds(table) {
585
+ const res = await opsPost({
586
+ operation: "search_by_conditions", database: "flair", table, operator: "and",
587
+ conditions: [{ search_attribute: "agentId", search_type: "equals", search_value: id }],
588
+ get_attributes: ["id", "agentId"],
589
+ });
590
+ if (!res.ok)
591
+ throw new Error(`operations API returned ${res.status}`);
592
+ const rows = await res.json();
593
+ if (!Array.isArray(rows) || !rows.every((row) => typeof row?.id === "string" && row.id.length > 0)) {
594
+ throw new Error("returned an unexpected response");
595
+ }
596
+ for (const row of rows) {
597
+ if (row.agentId !== id) {
598
+ const error = new Error(`${table} row '${row.id}' does not belong to agent '${id}'`);
599
+ error.name = "AgentRemoveOwnerMismatchError";
600
+ throw error;
601
+ }
602
+ }
603
+ return rows.map((row) => row.id);
604
+ }
605
+ async function initialScan(table) {
606
+ try {
607
+ return await scanOwnedIds(table);
608
+ }
609
+ catch (error) {
610
+ const failure = new Error(`The ${table} scan for agent '${id}' failed: ${error instanceof Error ? error.message : String(error)}; nothing was removed.`, { cause: error });
611
+ if (error instanceof Error)
612
+ failure.name = error.name;
613
+ throw failure;
614
+ }
615
+ }
616
+ const memoryIds = await initialScan("Memory");
617
+ const memoryCount = memoryIds.length;
618
+ const soulIds = await initialScan("Soul");
383
619
  // Confirmation
384
620
  const isInteractive = process.stdin.isTTY;
385
621
  if (!opts.force) {
@@ -410,26 +646,49 @@ export function register(program) {
410
646
  else {
411
647
  console.log(`Removing agent '${agentName}' (${id}) with ${memoryCount} memories...`);
412
648
  }
413
- // Delete all memories
649
+ // Delete the scanned memories through the server's physical-removal
650
+ // path. A skill-tagged row expands to its whole lineage there, so
651
+ // superseded version rows go too. An accepted DELETE of a non-reserved
652
+ // skill closes its head; the reserved `using-flair` seed is physically
653
+ // deleted. A response that does not list every scanned id as
654
+ // removed stops the command before the Agent record is deleted.
414
655
  if (memoryCount > 0) {
415
656
  console.log(`Deleting ${memoryCount} memories...`);
416
- for (const mem of (Array.isArray(memories) ? memories : [])) {
417
- if (!mem?.id)
418
- continue;
419
- await opsPost({ operation: "delete", database: "flair", table: "Memory", ids: [mem.id] }).catch(() => { });
420
- }
657
+ const purge = await api("POST", "/MemoryPurge", { ids: memoryIds }, {
658
+ baseUrl: instance.baseUrl,
659
+ explicitAdminPass: adminPass, adminUser, agentId: null,
660
+ });
661
+ confirmedPurgeIds(purge, memoryIds);
421
662
  }
422
- // Delete all souls
423
- const soulRes = await opsPost({ operation: "search_by_value", database: "flair", table: "Soul", search_attribute: "agentId", search_value: id, get_attributes: ["id"] });
424
- const souls = soulRes.ok ? await soulRes.json().catch(() => []) : [];
425
- if (Array.isArray(souls) && souls.length > 0) {
426
- console.log(`Deleting ${souls.length} soul entries...`);
427
- for (const soul of souls) {
428
- if (!soul?.id)
429
- continue;
430
- await opsPost({ operation: "delete", database: "flair", table: "Soul", ids: [soul.id] }).catch(() => { });
663
+ if (soulIds.length > 0) {
664
+ console.log(`Deleting ${soulIds.length} soul entries...`);
665
+ for (const soulId of soulIds) {
666
+ try {
667
+ const soulDel = await opsPost({ operation: "delete", database: "flair", table: "Soul", ids: [soulId] });
668
+ if (!soulDel.ok) {
669
+ const text = await soulDel.text().catch(() => "");
670
+ throw new Error(`operations API returned ${soulDel.status}: ${text}`);
671
+ }
672
+ }
673
+ catch (error) {
674
+ throw new Error(`Failed to delete Soul '${soulId}': ${error instanceof Error ? error.message : String(error)}`, { cause: error });
675
+ }
431
676
  }
432
677
  }
678
+ let remainingIds;
679
+ try {
680
+ remainingIds = await scanOwnedIds("Soul");
681
+ }
682
+ catch (error) {
683
+ const failure = new Error(`The Soul deletion for agent '${id}' could not be confirmed: ${error instanceof Error ? error.message : String(error)}; ` +
684
+ `these scanned Soul rows may remain and the Agent record was not deleted: ${soulIds.join(", ") || "(none scanned)"}.`, { cause: error });
685
+ if (error instanceof Error)
686
+ failure.name = error.name;
687
+ throw failure;
688
+ }
689
+ if (remainingIds.length > 0) {
690
+ throw new Error(`The Soul deletion for agent '${id}' was not confirmed; these Soul rows remain and the Agent record was not deleted: ${remainingIds.join(", ")}.`);
691
+ }
433
692
  // Delete agent record
434
693
  const delRes = await opsPost({ operation: "delete", database: "flair", table: "Agent", ids: [id] });
435
694
  if (!delRes.ok) {
@@ -438,23 +697,103 @@ export function register(program) {
438
697
  }
439
698
  // Delete key files (unless --keep-keys)
440
699
  if (!opts.keepKeys) {
441
- const privPath = privKeyPath(id, keysDir);
442
- const pubPath = pubKeyPath(id, keysDir);
443
- const backupPath = privPath + ".bak";
444
- for (const p of [privPath, pubPath, backupPath]) {
445
- if (existsSync(p)) {
446
- try {
447
- const { unlinkSync: ul } = await import("node:fs");
448
- ul(p);
449
- }
450
- catch { /* best effort */ }
451
- }
452
- }
453
- console.log("Key files deleted.");
700
+ const keys = removeAgentKeyFiles(id, keysDir);
701
+ console.log(keys.manual
702
+ ? `Key files for '${id}' are not deleted by this command (the id is outside the agent-ID rule); clean them up manually.`
703
+ : `Removed ${keys.removed.length} key file(s).`);
454
704
  }
455
705
  else {
456
706
  console.log("Key files preserved (--keep-keys).");
457
707
  }
458
708
  console.log(`\n✅ Agent '${id}' removed successfully`);
459
709
  });
710
+ agent
711
+ .command("stamp-home")
712
+ .description("Back-fill the home instance (originatorInstanceId) on home-less Agent rows with no federation-sync provenance")
713
+ .option("--port <port>", "Harper HTTP port")
714
+ .option("--ops-port <port>", "Harper operations API port")
715
+ .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS)")
716
+ .option("--admin-pass-file <path>", "Read the admin password from a file (chmod 600 enforced)")
717
+ .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
718
+ .option("--apply", "Write the home; without it the command is a dry run and writes nothing")
719
+ .action(async (opts) => {
720
+ let target;
721
+ try {
722
+ // flair#2474 — pair the ops port (the roster read) with the HTTP port (the
723
+ // guarded PATCH). A target the configured pair contradicts, or one with a
724
+ // single port named and no complete configured pair, is refused by name
725
+ // (see resolveAgentHomeTarget).
726
+ target = resolveAgentHomeTarget(opts);
727
+ }
728
+ catch (err) {
729
+ console.error(`Error: ${err.message}`);
730
+ process.exit(1);
731
+ }
732
+ const opsPort = target.opsPort;
733
+ const adminUser = resolveAdminUser(opts.adminUser);
734
+ let explicitPass;
735
+ try {
736
+ explicitPass =
737
+ resolveAdminPassFromSources({
738
+ adminPassFile: opts.adminPassFile,
739
+ adminPass: opts.adminPass,
740
+ envPass: undefined,
741
+ }) || undefined;
742
+ }
743
+ catch (err) {
744
+ console.error(`Error: ${err.message}`);
745
+ process.exit(1);
746
+ }
747
+ let adminPass;
748
+ try {
749
+ adminPass = resolveLocalAdminPass(explicitPass);
750
+ }
751
+ catch (err) {
752
+ console.error(`Error: ${err.message}`);
753
+ process.exit(1);
754
+ }
755
+ if (!adminPass) {
756
+ console.error("Error: --admin-pass or FLAIR_ADMIN_PASS required (or ensure ~/.flair/admin-pass exists, created by `flair init`)");
757
+ process.exit(1);
758
+ }
759
+ const opsUrl = `http://127.0.0.1:${opsPort}/`;
760
+ const httpUrl = `http://127.0.0.1:${target.httpPort}/`;
761
+ const auth = `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
762
+ const localInstanceId = await resolveTargetInstanceId(agentHomeEndpoint(opsUrl, adminUser, adminPass));
763
+ const result = await runAgentHomeStamp({
764
+ opsUrl,
765
+ httpUrl,
766
+ authHeader: auth,
767
+ localInstanceId,
768
+ apply: Boolean(opts.apply),
769
+ });
770
+ if (result.reason === "roster-unreadable") {
771
+ console.error("Error: could not read the stored Agent roster; nothing was changed.");
772
+ process.exit(1);
773
+ }
774
+ const plan = result.plan;
775
+ if (plan.homeLess.length === 0) {
776
+ console.log(`${render.icons.ok} Every stored agent row names a home instance.`);
777
+ return;
778
+ }
779
+ console.log(`${plan.homeLess.length} agent row(s) have no home instance` +
780
+ (localInstanceId ? ` (this instance is ${localInstanceId})` : ""));
781
+ for (const id of plan.homeLess) {
782
+ const inSync = plan.sync.includes(id);
783
+ console.log(` ${inSync ? "list only (sync-originated):" : "stamp:"} ${id}`);
784
+ }
785
+ if (result.reason === "no-canonical-id") {
786
+ console.error("Error: could not confirm a single canonical Instance row to stamp as the home; nothing was written.");
787
+ process.exitCode = 1;
788
+ return;
789
+ }
790
+ if (!opts.apply) {
791
+ console.log(`Dry run — nothing written. Re-run with --apply to stamp ${plan.stampable.length} row(s); ` +
792
+ `${plan.sync.length} sync-originated row(s) are never stamped.`);
793
+ return;
794
+ }
795
+ for (const line of stampLeftoverLines(result))
796
+ console.log(line);
797
+ console.log(`${render.icons.ok} Stamped the home instance on ${result.stamped.length} row(s).`);
798
+ });
460
799
  }
@@ -1,4 +1,4 @@
1
- import { buildEd25519Auth, resolveKeyPath } from "../lib/auth-resolve.js";
1
+ import { buildEd25519Auth, requestTarget, requestUrl, resolveKeyPath } from "../lib/auth-resolve.js";
2
2
  import * as render from "../render.js";
3
3
  let cli;
4
4
  /** Bind the cli-locals this module depends on. */
@@ -67,12 +67,13 @@ export function register(program) {
67
67
  payload.days = n;
68
68
  }
69
69
  const baseUrl = resolveBaseUrl(opts);
70
+ const url = requestUrl(baseUrl, "/AttentionQuery");
70
71
  const headers = { "content-type": "application/json" };
71
72
  const keyPath = opts.key || resolveKeyPath(agentId);
72
73
  if (keyPath) {
73
- headers["authorization"] = buildEd25519Auth(agentId, "POST", "/AttentionQuery", keyPath);
74
+ headers["authorization"] = buildEd25519Auth(agentId, "POST", requestTarget(url), keyPath);
74
75
  }
75
- const res = await fetch(`${baseUrl}/AttentionQuery`, {
76
+ const res = await fetch(url, {
76
77
  method: "POST",
77
78
  headers,
78
79
  body: JSON.stringify(payload),