@tpsdev-ai/flair 0.62.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 (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -1,3 +1,4 @@
1
+ import { addAdminPassOptions } from "../lib/auth-resolve.js";
1
2
  let cli;
2
3
  /** Bind the cli-locals this module depends on. */
3
4
  export function bindCli(fns) {
@@ -14,13 +15,12 @@ function resolveAdminUser(...args) {
14
15
  }
15
16
  export function register(program) {
16
17
  // ─── flair grant / revoke ─────────────────────────────────────────────────────
17
- program
18
+ addAdminPassOptions(program
18
19
  .command("grant <from-agent> <to-agent>")
19
20
  .description("Grant an agent read access to another agent's memories")
20
21
  .option("--scope <scope>", "Grant scope: read or search", "read")
21
22
  .option("--port <port>", "Harper HTTP port")
22
- .option("--ops-port <port>", "Harper operations API port")
23
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS env)")
23
+ .option("--ops-port <port>", "Harper operations API port"), "Admin password (or set FLAIR_ADMIN_PASS env)")
24
24
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
25
25
  .option("--keys-dir <dir>", "Directory for Ed25519 keys (for from-agent Ed25519 auth)")
26
26
  .action(async (fromAgent, toAgent, opts) => {
@@ -65,12 +65,11 @@ export function register(program) {
65
65
  console.log(` ID: ${grantId}`);
66
66
  console.log(` Scope: ${scope}`);
67
67
  });
68
- program
68
+ addAdminPassOptions(program
69
69
  .command("revoke <from-agent> <to-agent>")
70
70
  .description("Revoke a memory grant between two agents")
71
71
  .option("--port <port>", "Harper HTTP port")
72
- .option("--ops-port <port>", "Harper operations API port")
73
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS env)")
72
+ .option("--ops-port <port>", "Harper operations API port"), "Admin password (or set FLAIR_ADMIN_PASS env)")
74
73
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
75
74
  .action(async (fromAgent, toAgent, opts) => {
76
75
  const httpPort = resolveHttpPort(opts);
@@ -0,0 +1,25 @@
1
+ /** Register `flair help`. Called last, so the root listing keeps the help entry at the bottom. */
2
+ export function registerHelp(program) {
3
+ program
4
+ .command("help")
5
+ .argument("[command...]")
6
+ .description("display help for command")
7
+ .action((path) => {
8
+ let target = program;
9
+ let unknown;
10
+ for (const name of path) {
11
+ const next = target.commands.find((candidate) => candidate.name() === name || candidate.aliases().includes(name));
12
+ if (!next) {
13
+ unknown = name;
14
+ break;
15
+ }
16
+ target = next;
17
+ }
18
+ target.outputHelp();
19
+ if (unknown !== undefined) {
20
+ // Same wording as commander's own unknown-command error, on stderr.
21
+ process.stderr.write(`error: unknown command '${unknown}'\n`);
22
+ process.exitCode = 1;
23
+ }
24
+ });
25
+ }
@@ -13,7 +13,7 @@
13
13
  import { encodeRecordId } from "../lib/record-id-path.js";
14
14
  import { randomUUID } from "node:crypto";
15
15
  import * as render from "../render.js";
16
- import { resolveAdminUser } from "../lib/auth-resolve.js";
16
+ import { resolveAdminUser, addAdminPassOptions, ApiHttpError } from "../lib/auth-resolve.js";
17
17
  let cli;
18
18
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
19
19
  export function bindCli(fns) {
@@ -30,7 +30,7 @@ export function register(program) {
30
30
  // ─── flair idp ───────────────────────────────────────────────────────────────
31
31
  // XAA Enterprise IdP configuration (per FLAIR-XAA spec § 4).
32
32
  const idp = program.command("idp").description("Manage enterprise IdP configurations (XAA)");
33
- idp
33
+ addAdminPassOptions(idp
34
34
  .command("add")
35
35
  .description("Register a trusted enterprise IdP")
36
36
  .requiredOption("--name <name>", "Display name (e.g., 'Harper Corporate')")
@@ -39,8 +39,7 @@ export function register(program) {
39
39
  .requiredOption("--client-id <id>", "Flair's client_id at this IdP")
40
40
  .option("--required-domain <domain>", "Reject tokens without this domain (hd/tid claim)")
41
41
  .option("--no-jit-provision", "Disable auto-creation of principals for new IdP users")
42
- .option("--default-trust <tier>", "Trust tier for JIT principals", "unverified")
43
- .option("--admin-pass <pass>", "Admin password")
42
+ .option("--default-trust <tier>", "Trust tier for JIT principals", "unverified"), "Admin password")
44
43
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
45
44
  .option("--ops-port <port>", "Harper operations API port")
46
45
  .action(async (opts) => {
@@ -84,10 +83,7 @@ export function register(program) {
84
83
  console.log(` Domain: ${opts.requiredDomain}`);
85
84
  console.log(` JIT: ${opts.jitProvision !== false}`);
86
85
  });
87
- idp
88
- .command("list")
89
- .description("List configured IdPs")
90
- .option("--admin-pass <pass>", "Admin password")
86
+ addAdminPassOptions(idp.command("list").description("List configured IdPs"), "Admin password")
91
87
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
92
88
  .option("--ops-port <port>", "Harper operations API port")
93
89
  .option("--json", "Emit raw JSON array (also: pipe + FLAIR_OUTPUT=json)")
@@ -139,10 +135,7 @@ export function register(program) {
139
135
  console.log();
140
136
  }
141
137
  });
142
- idp
143
- .command("remove <id>")
144
- .description("Remove an IdP configuration")
145
- .option("--admin-pass <pass>", "Admin password")
138
+ addAdminPassOptions(idp.command("remove <id>").description("Remove an IdP configuration"), "Admin password")
146
139
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
147
140
  .option("--ops-port <port>", "Harper operations API port")
148
141
  .action(async (id, opts) => {
@@ -165,10 +158,8 @@ export function register(program) {
165
158
  }
166
159
  console.log(`✅ IdP '${id}' removed`);
167
160
  });
168
- idp
169
- .command("test <id>")
170
- .description("Test IdP connectivity (fetches JWKS)")
171
- .option("--admin-pass <pass>", "Admin password")
161
+ addAdminPassOptions(idp.command("test <id>").description("Test IdP connectivity (fetches JWKS)"), "Admin password")
162
+ .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
172
163
  .option("--ops-port <port>", "Harper operations API port")
173
164
  .action(async (id, opts) => {
174
165
  const opsPort = resolveOpsPort(opts);
@@ -179,10 +170,14 @@ export function register(program) {
179
170
  }
180
171
  let cfg;
181
172
  try {
182
- cfg = await api("GET", `/IdpConfig/${encodeRecordId(id)}`);
173
+ cfg = await api("GET", `/IdpConfig/${encodeRecordId(id)}`, undefined, {
174
+ explicitAdminPass: adminPass, adminUser: opts.adminUser, agentId: null,
175
+ });
183
176
  }
184
- catch {
185
- console.error(`IdP '${id}' not found`);
177
+ catch (err) {
178
+ console.error(err instanceof ApiHttpError && err.status === 404
179
+ ? `IdP '${id}' not found`
180
+ : `Error: ${err instanceof Error ? err.message : String(err)}`);
186
181
  process.exit(1);
187
182
  }
188
183
  console.log(`Testing IdP: ${cfg.name} (${cfg.issuer})`);
@@ -1,8 +1,94 @@
1
- import { defaultKeysDir, resolveAdminUser } from "../lib/auth-resolve.js";
1
+ import { addAdminPassOptions, ApiHttpError, ApiRequestOutcomeUnknown, apiErrorRawBody, defaultKeysDir, isLocalBase, resolveAdminUser, sendJsonRequest, } from "../lib/auth-resolve.js";
2
2
  import { encodeRecordId } from "../lib/record-id-path.js";
3
+ import { invalidAgentIdMessage, isValidAgentId } from "../lib/agent-id-rule.js";
4
+ import { SOUL_SCOPE_FIELDS_REFUSAL, suppliesSoulScopeFields } from "../lib/soul-scope-fields.js";
3
5
  import * as render from "../render.js";
4
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { existsSync, readFileSync } from "node:fs";
7
+ import { ensureAgentKeysDir, readOrCreateAgentKey } from "../lib/agent-key-file.js";
5
8
  import nacl from "tweetnacl";
9
+ /** The fixed error names Flair's write guards return for a Soul or Memory
10
+ * write. A response body's `error` is displayed only when it is one of these;
11
+ * any other server-supplied text is not displayed by the import report. The
12
+ * writes also withhold the response body from the FLAIR_DEBUG HTTP-error
13
+ * line. */
14
+ const WRITE_GUARD_ERROR_NAMES = new Set([
15
+ // Soul write guards (resources/Soul.ts, resources/soul-write-policy.ts).
16
+ "soul_owner_required",
17
+ "soul_scope_fields_not_writable",
18
+ "soul_value_is_learned_content",
19
+ "soul_write_requires_one_record",
20
+ // Memory write guards (resources/Memory.ts and the guards it runs).
21
+ "content_safety_violation",
22
+ "derived_from_self",
23
+ "embedding_unavailable",
24
+ "id_target_mismatch",
25
+ "invalid_durability",
26
+ "invalid_expiry",
27
+ "invalid_visibility",
28
+ "invalid_visibility_for_durability",
29
+ "memory_id_required",
30
+ "owner_lookup_failed",
31
+ "reembed_no_text",
32
+ "reembed_row_changed",
33
+ "skill_durability",
34
+ "skill_lineage_tag_removed",
35
+ "skill_metadata_duplicate_key",
36
+ "skill_opt_out_not_boolean",
37
+ "skill_source_not_durable",
38
+ "skill_state_requires_delete",
39
+ "skill_update_compensation_failed",
40
+ "skill_update_not_closed",
41
+ "skill_update_not_confirmed",
42
+ "skill_update_unconfirmed",
43
+ "skill_write_path",
44
+ "storage_quota_exceeded",
45
+ "stored_row_changed",
46
+ "stored_row_lookup_failed",
47
+ "stored_row_read_failed",
48
+ "unresolved_request_target",
49
+ "write_body_unreadable",
50
+ "write_id_not_addressed",
51
+ ]);
52
+ /** A recognised error name from a refused response body; undefined for any
53
+ * other server-supplied text, which the import report does not display. */
54
+ function responseErrorName(raw) {
55
+ if (!raw)
56
+ return undefined;
57
+ try {
58
+ const body = JSON.parse(raw);
59
+ return typeof body?.error === "string" && WRITE_GUARD_ERROR_NAMES.has(body.error) ? body.error : undefined;
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ }
65
+ /** Write one imported row. Only a 2xx response counts as imported. */
66
+ async function writeRow(baseUrl, table, row, auth) {
67
+ try {
68
+ await sendJsonRequest(new URL(`${baseUrl}/${table}/${encodeRecordId(row.id)}`), "PUT", row, auth, isLocalBase(baseUrl), { withholdResponseBodyDebug: true });
69
+ return { kind: "imported" };
70
+ }
71
+ catch (err) {
72
+ if (err instanceof ApiRequestOutcomeUnknown) {
73
+ return { kind: "unknown", status: err.status, message: err.message };
74
+ }
75
+ if (err instanceof ApiHttpError) {
76
+ return { kind: "failed", status: err.status, error: responseErrorName(apiErrorRawBody(err)) };
77
+ }
78
+ // The shared sender parses a 2xx body as JSON; a 2xx body that is not JSON
79
+ // still arrived as a successful write.
80
+ if (err instanceof SyntaxError)
81
+ return { kind: "imported" };
82
+ return { kind: "failed", status: undefined, error: err instanceof Error ? err.message : String(err) };
83
+ }
84
+ }
85
+ /** The per-row failure text: an HTTP status and a recognised error name, or
86
+ * the thrown error. Never the row's content. */
87
+ function failureText(row) {
88
+ if (row.status === undefined)
89
+ return row.error ?? "no response";
90
+ return `HTTP ${row.status}${row.error ? ` ${row.error}` : ""}`;
91
+ }
6
92
  let cli;
7
93
  /** Bind the cli-locals this module depends on. */
8
94
  export function bindCli(fns) {
@@ -31,14 +117,13 @@ function seedAgentWithLocalHome(...args) {
31
117
  }
32
118
  export function register(program) {
33
119
  // ─── flair import ────────────────────────────────────────────────────────────
34
- program
120
+ addAdminPassOptions(program
35
121
  .command("import <path>")
36
122
  .description("Import an agent from an export file into this Flair instance")
37
123
  .option("--port <port>", "Harper HTTP port")
38
124
  .option("--ops-port <port>", "Harper operations API port")
39
125
  .option("--url <url>", "Flair base URL (overrides --port)")
40
- .option("--ops-target <url>", "Explicit ops API URL for the Agent seed (env: FLAIR_OPS_TARGET; bypasses port derivation). Use when --url is remote and the ops port isn't HTTP-1.")
41
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS env)")
126
+ .option("--ops-target <url>", "Explicit ops API URL for the Agent seed (env: FLAIR_OPS_TARGET; bypasses port derivation). Use when --url is remote and the ops port isn't HTTP-1."), "Admin password (or set FLAIR_ADMIN_PASS env)")
42
127
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
43
128
  .option("--keys-dir <dir>", "Keys directory", defaultKeysDir())
44
129
  .action(async (importPath, opts) => {
@@ -67,33 +152,52 @@ export function register(program) {
67
152
  process.exit(1);
68
153
  }
69
154
  const agentId = data.agent?.id;
70
- if (!agentId) {
155
+ // Only a missing agent.id (absent or null) means "no agent ID in export".
156
+ // A supplied string, including the empty string, goes through the shared
157
+ // rule below; a supplied non-string is refused just below.
158
+ if (agentId === undefined || agentId === null) {
71
159
  console.error("Error: no agent ID in export");
72
160
  process.exit(1);
73
161
  }
162
+ // A present non-string id is refused before the shared rule: String(0) or
163
+ // String(123) would itself match the rule, so the shared message would
164
+ // wrongly say the id violates it. A type message states the actual refusal.
165
+ if (typeof agentId !== "string") {
166
+ console.error(`Error: agent id in export must be a string (got ${typeof agentId})`);
167
+ process.exit(1);
168
+ }
169
+ // flair#2359 — the ONE agent-ID rule, before the keys directory is created
170
+ // or any key file is written, and before any `fetch` call made by the command action.
171
+ if (!isValidAgentId(agentId)) {
172
+ console.error(`Error: ${invalidAgentIdMessage(agentId)}`);
173
+ process.exit(1);
174
+ }
74
175
  console.log(`Importing agent '${agentId}'...`);
75
176
  // Register agent (generates new key if export doesn't include one)
76
177
  const keysDir = opts.keysDir ?? defaultKeysDir();
77
- mkdirSync(keysDir, { recursive: true });
78
178
  const privPath = privKeyPath(agentId, keysDir);
79
- if (data.privateKey && !existsSync(privPath)) {
80
- // Restore exported key
81
- writeFileSync(privPath, data.privateKey);
82
- chmodSync(privPath, 0o600);
83
- console.log(` Key restored: ${privPath}`);
179
+ let keyFile;
180
+ try {
181
+ ensureAgentKeysDir(keysDir);
182
+ keyFile = readOrCreateAgentKey(privPath, () => {
183
+ if (data.privateKey)
184
+ return data.privateKey;
185
+ const kp = nacl.sign.keyPair();
186
+ return Buffer.from(kp.secretKey.slice(0, 32));
187
+ });
84
188
  }
85
- else if (!existsSync(privPath)) {
86
- // Generate new key
87
- const kp = nacl.sign.keyPair();
88
- writeFileSync(privPath, Buffer.from(kp.secretKey.slice(0, 32)));
89
- chmodSync(privPath, 0o600);
90
- console.log(` New key generated: ${privPath}`);
189
+ catch (err) {
190
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
191
+ process.exit(1);
192
+ }
193
+ if (keyFile.created) {
194
+ console.log(data.privateKey ? ` Key restored: ${privPath}` : ` New key generated: ${privPath}`);
91
195
  }
92
196
  else {
93
197
  console.log(` Using existing key: ${privPath}`);
94
198
  }
95
199
  // Read public key for registration
96
- const seed = readFileSync(privPath);
200
+ const seed = Buffer.from(keyFile.bytes);
97
201
  const decodedSeed = seed.length === 32 ? seed : Buffer.from(seed.toString("utf-8").trim(), "base64");
98
202
  const pubKey = decodedSeed.length === 32
99
203
  ? nacl.sign.keyPair.fromSeed(new Uint8Array(decodedSeed)).publicKey
@@ -107,32 +211,61 @@ export function register(program) {
107
211
  // Restore souls before memories: refuseLearnedSoulWrite matches Memory text.
108
212
  const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
109
213
  let soulCount = 0;
214
+ let memCount = 0;
215
+ let failedCount = 0;
216
+ let unknownCount = 0;
110
217
  for (const soul of data.souls ?? []) {
111
- try {
112
- await fetch(`${baseUrl}/Soul/${encodeRecordId(soul.id)}`, {
113
- method: "PUT",
114
- headers: { "Content-Type": "application/json", Authorization: auth },
115
- body: JSON.stringify(soul),
116
- });
218
+ const outcome = await writeRow(baseUrl, "Soul", soul, auth);
219
+ if (outcome.kind === "imported") {
117
220
  soulCount++;
221
+ continue;
222
+ }
223
+ // A row the server refuses with HTTP 403 for supplying a non-empty
224
+ // `scopeTag` or a non-empty `tags` array is reported with its id and
225
+ // left out of the count; the rest of the export is imported as before
226
+ // (flair#1540).
227
+ if (outcome.kind === "failed" &&
228
+ outcome.status === 403 &&
229
+ outcome.error === SOUL_SCOPE_FIELDS_REFUSAL &&
230
+ suppliesSoulScopeFields(soul)) {
231
+ console.log(`${render.icons.warn} Soul ${soul.id} refused: ${outcome.error}`);
232
+ continue;
118
233
  }
119
- catch { /* skip failures */ }
234
+ if (outcome.kind === "unknown") {
235
+ unknownCount++;
236
+ console.error(`${render.icons.warn} Soul ${soul.id} unknown: ${outcome.message}`);
237
+ continue;
238
+ }
239
+ failedCount++;
240
+ console.error(`${render.icons.error} Soul ${soul.id} failed: ${failureText(outcome)}`);
120
241
  }
121
- let memCount = 0;
122
242
  for (const mem of data.memories ?? []) {
123
- try {
124
- await fetch(`${baseUrl}/Memory/${encodeRecordId(mem.id)}`, {
125
- method: "PUT",
126
- headers: { "Content-Type": "application/json", Authorization: auth },
127
- body: JSON.stringify(mem),
128
- });
243
+ const outcome = await writeRow(baseUrl, "Memory", mem, auth);
244
+ if (outcome.kind === "imported") {
129
245
  memCount++;
246
+ continue;
130
247
  }
131
- catch { /* skip failures */ }
248
+ if (outcome.kind === "unknown") {
249
+ unknownCount++;
250
+ console.error(`${render.icons.warn} Memory ${mem.id} unknown: ${outcome.message}`);
251
+ continue;
252
+ }
253
+ failedCount++;
254
+ console.error(`${render.icons.error} Memory ${mem.id} failed: ${failureText(outcome)}`);
132
255
  }
133
256
  console.log(`\n${render.icons.ok} ${render.wrap(render.c.green, `Agent '${agentId}' imported`)}`);
134
257
  console.log(render.kv("Memories", `${render.wrap(render.c.bold, String(memCount))}${render.wrap(render.c.dim, `/${(data.memories ?? []).length}`)}`));
135
258
  console.log(render.kv("Souls", `${render.wrap(render.c.bold, String(soulCount))}${render.wrap(render.c.dim, `/${(data.souls ?? []).length}`)}`));
259
+ if (failedCount > 0)
260
+ console.log(render.kv("Failed", String(failedCount)));
261
+ if (unknownCount > 0)
262
+ console.log(render.kv("Unknown", String(unknownCount)));
136
263
  console.log(render.kv("Key", render.wrap(render.c.dim, privPath)));
264
+ // An unknown write outcome exits 3, as the REM runner and `flair memory
265
+ // verify` use it, distinct from the 1 a definite failure exits with.
266
+ if (unknownCount > 0)
267
+ process.exit(3);
268
+ if (failedCount > 0)
269
+ process.exit(1);
137
270
  });
138
271
  }