@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
package/dist/cli.js CHANGED
@@ -24,12 +24,13 @@ import { flairConfigPath, flairDataDir } from "./lib/flair-paths.js";
24
24
  import { encodeRecordId } from "./lib/record-id-path.js";
25
25
  import { invalidAgentIdMessage, isValidAgentId } from "./lib/agent-id-rule.js";
26
26
  import { agentHomeEndpoint, decideProbedPairIdentity, readHttpInstanceIdentity, resolveTargetInstanceId, resolveTargetInstanceIdentity, stampAgentHome } from "./lib/agent-home.js";
27
- import { proveLocalInstancePair } from "./lib/local-instance-pair.js";
27
+ import { IncompleteInstancePairError, proveLocalInstancePair } from "./lib/local-instance-pair.js";
28
28
  import { httpBind, httpCorsAccessList, preserveHttpPortValue, preserveSecurePort, qualifySecureBindValue, DEFAULT_HTTP_BIND_HOST, } from "./lib/http-bind.js";
29
29
  import { isNodeKeyId, partitionKeyIds, } from "./doctor-client.js";
30
30
  import { cliBootPathWarning, } from "./install/global-bin-path.js";
31
31
  import { ApiHttpError, ApiRequestOutcomeUnknown, isConnectPhaseFailure, readSecretFileSecure, readAdminPassFileSecure, defaultAdminPassPath, defaultKeysDir, resolveLocalAdminPass, addAdminPassOptions, DEFAULT_ADMIN_USER, resolveAdminUser, resolveKeyPath, buildEd25519Auth, authFetch, KeyLoadError, isLocalBase, authedRequest, } from "./lib/auth-resolve.js";
32
32
  import { resolveSigningIdentity, emitSigningIdentityDebug, } from "./lib/signing-identity.js";
33
+ import { AgentKeyPathRefusal, agentKeyPath, agentPubKeyPath } from "./lib/key-dir.js";
33
34
  import { entityFormatHint, parseEntitiesCsv } from "./lib/entity-vocab-cli.js";
34
35
  import { escapeXml, unescapeXml } from "./lib/xml-escape.js";
35
36
  import { assessLaunchdManagement, verifyLaunchdManagement, checkLaunchdPlistBeforeLoad, diagnoseLaunchdPlistPaths, isDetached, pickInstancePid, plistCarriesInlineAdminPassword, readLaunchctlJobState, readPlistProgramRefs, LAUNCHCTL_QUERY_TIMEOUT_MS, } from "./lib/launchd-management.js";
@@ -41,7 +42,7 @@ import { applyRepointPlan, repointSystemdUserUnit, restartOnLinux } from "./lib/
41
42
  // Aliased: this file also declares its own FileSnapshot (flair#2040's raw-bytes
42
43
  // snapshot for byte-exact restores); this is atomic-write's regular-file snapshot.
43
44
  import { snapshotRegularFile } from "./lib/atomic-write.js";
44
- import { preferVersionManagerAlias } from "./lib/node-alias-path.js";
45
+ import { homebrewOptAlias, preferVersionManagerAlias } from "./lib/node-alias-path.js";
45
46
  import { stabilizeMqttNetworkKeyOrder } from "./lib/stabilize-mqtt-network.js";
46
47
  import { MQTT_DISABLED_CONFIG } from "./lib/mqtt-config.js";
47
48
  import { FABRIC_OPS_PORT, resolveOpsUrlFromTarget } from "./lib/ops-url.js";
@@ -1015,17 +1016,19 @@ export function decideAgentHomeTarget(i) {
1015
1016
  throw new Error(`${AMBIGUOUS_INSTANCE_TARGET_ERROR}: the target (HTTP port ${httpPort}, ops port ${opsPort}) conflicts with the configured pair — `
1016
1017
  + `the config pairs HTTP ${configuredHttp} with ops ${configuredOps}. ${remedy}`);
1017
1018
  }
1018
- return { httpPort, opsPort };
1019
+ // Both sides equal the configured pair (or neither does — only when the
1020
+ // caller named both, since an unnamed port is taken from the pair).
1021
+ return { httpPort, opsPort, pairBound: httpMatches && opsMatches };
1019
1022
  }
1020
1023
  const opsNamed = namedOps !== null;
1021
1024
  if (httpNamed !== opsNamed) {
1022
1025
  const [named, namedPort, other] = httpNamed ? ["HTTP", httpPort, "ops"] : ["ops", namedOps, "HTTP"];
1023
- throw new Error(`${AMBIGUOUS_INSTANCE_TARGET_ERROR}: only the ${named} port (${namedPort}) was named, and no complete port pair could be resolved from config `
1024
- + `(HTTP ${configuredHttp ?? "none"}, ops ${configuredOps ?? "none"}) to take the ${other} port from, so the two ports could address different instances. ${remedy}`);
1026
+ throw new IncompleteInstancePairError(`${AMBIGUOUS_INSTANCE_TARGET_ERROR}: only the ${named} port (${namedPort}) was named, and no complete port pair could be resolved from config `
1027
+ + `(HTTP ${configuredHttp ?? "none"}, ops ${configuredOps ?? "none"}) to take the ${other} port from, so the two ports could address different instances. ${remedy}`, named, other);
1025
1028
  }
1026
1029
  if (namedOps !== null)
1027
- return { httpPort, opsPort: namedOps };
1028
- return { httpPort, opsPort: i.deriveOps() };
1030
+ return { httpPort, opsPort: namedOps, pairBound: false };
1031
+ return { httpPort, opsPort: i.deriveOps(), pairBound: false };
1029
1032
  }
1030
1033
  /**
1031
1034
  * The ports `flair agent stamp-home` and `flair principal add` address
@@ -1064,7 +1067,7 @@ export function resolveAgentHomeTarget(opts, httpPortOverride) {
1064
1067
  const n = Number(opts.opsPort);
1065
1068
  if (!(Number.isInteger(n) && n >= 1 && n <= 65535)) {
1066
1069
  // An invalid --ops-port is refused by resolveOpsPort, which exits.
1067
- return { httpPort, opsPort: resolveOpsPort(opts) };
1070
+ return { httpPort, opsPort: resolveOpsPort(opts), pairBound: false };
1068
1071
  }
1069
1072
  namedOps = n;
1070
1073
  }
@@ -1866,10 +1869,10 @@ function persistDefaultInstallCoordinates(dataDir, port, opsPort, opsBind, httpB
1866
1869
  writeConfig(port, opsPort, opsBind, configPath(), httpBind);
1867
1870
  }
1868
1871
  function privKeyPath(agentId, keysDir) {
1869
- return join(keysDir, `${agentId}.key`);
1872
+ return agentKeyPath(keysDir, agentId);
1870
1873
  }
1871
1874
  function pubKeyPath(agentId, keysDir) {
1872
- return join(keysDir, `${agentId}.pub`);
1875
+ return agentPubKeyPath(keysDir, agentId);
1873
1876
  }
1874
1877
  function flairPackageDir() {
1875
1878
  // dist/cli.js → package root (one level up from dist/)
@@ -2193,7 +2196,7 @@ async function waitForHealth(httpPort, adminUser, adminPass, timeoutMs, beforeRe
2193
2196
  /** `<keysDir>/<id>.key` — the fallback key location for tests and non-standard
2194
2197
  * key dirs; the standard `resolveKeyPath` lookup is always tried first. */
2195
2198
  function fallbackKeyPath(keysDir, agentId) {
2196
- const candidate = join(keysDir, `${agentId}.key`);
2199
+ const candidate = agentKeyPath(keysDir, agentId);
2197
2200
  return existsSync(candidate) ? candidate : null;
2198
2201
  }
2199
2202
  /**
@@ -2228,7 +2231,7 @@ export async function resolveProbeSigningIdentity(baseUrl, agentIdOpt, keysDir)
2228
2231
  catch { /* keysDir missing */ }
2229
2232
  const candidates = keyFiles
2230
2233
  .map((f) => f.replace(/\.key$/, ""))
2231
- .filter((id) => !isNodeKeyId(id, keysDir));
2234
+ .filter((id) => isValidAgentId(id) && !isNodeKeyId(id, keysDir));
2232
2235
  if (candidates.length === 0) {
2233
2236
  return { agentId: null, source: "none", detail: "no agent id or key found" };
2234
2237
  }
@@ -2582,11 +2585,19 @@ export async function probeFlairReachable(url, timeoutMs = 2000) {
2582
2585
  * server naming the agent unknown is a reliable, actionable signal.
2583
2586
  */
2584
2587
  export async function checkAgentRegistered(baseUrl, agentId, keysDir) {
2585
- let keyPath = resolveKeyPath(agentId);
2586
- if (!keyPath) {
2587
- const candidate = join(keysDir, `${agentId}.key`);
2588
- if (existsSync(candidate))
2589
- keyPath = candidate;
2588
+ let keyPath;
2589
+ try {
2590
+ keyPath = resolveKeyPath(agentId);
2591
+ if (!keyPath) {
2592
+ const candidate = agentKeyPath(keysDir, agentId);
2593
+ if (existsSync(candidate))
2594
+ keyPath = candidate;
2595
+ }
2596
+ }
2597
+ catch (err) {
2598
+ if (err instanceof AgentKeyPathRefusal)
2599
+ return { state: "no-key", detail: err.message };
2600
+ throw err;
2590
2601
  }
2591
2602
  if (!keyPath) {
2592
2603
  return { state: "no-key", detail: `no local key for agent '${agentId}' to sign the check` };
@@ -3063,11 +3074,81 @@ async function assertSingleInstanceRowAfterWrite(endpoint, expectedId) {
3063
3074
  if (verification.kind === "not-verified")
3064
3075
  throw new Error(instanceWriteNotVerifiedMessage(expectedId, verification.found));
3065
3076
  }
3066
- // ─── Provision Flair on Harper Fabric ──────────────────────────────────────
3067
- //
3068
- // Atomic provisioning for a fresh Harper Fabric cluster: builds a deploy
3069
- // tarball with .env baked in, deploys via ops API, waits for restart, and
3070
- // creates the super_user admin account.
3077
+ const OPS_API_ERROR_DESCRIPTIONS = {
3078
+ "already-exists": "the user already exists",
3079
+ "not-permitted": "the operation is not permitted for this role",
3080
+ "authentication-failed": "authentication failed",
3081
+ };
3082
+ const OPS_API_REFUSAL_DESCRIPTION = "the ops API refused the request (details withheld)";
3083
+ /**
3084
+ * Harper's exact wording for each category, anchored to the whole field value.
3085
+ * These strings are read here, for classification only, and are never copied
3086
+ * into a message.
3087
+ */
3088
+ const OPS_API_ERROR_PATTERNS = [
3089
+ ["already-exists", /^User (.+) already exists$/],
3090
+ ["not-permitted", /^This operation is not authorized due to role restrictions and\/or invalid database items$/],
3091
+ ["authentication-failed", /^Login failed$/],
3092
+ ];
3093
+ /** The status (and, for already-exists, operation) each category is defined by. */
3094
+ function categoryMatches(category, status, operation) {
3095
+ switch (category) {
3096
+ case "already-exists":
3097
+ return status === 409 && operation === "add_user";
3098
+ case "not-permitted":
3099
+ return status === 403;
3100
+ case "authentication-failed":
3101
+ return status === 401;
3102
+ }
3103
+ }
3104
+ /** A non-2xx ops API response, reduced to a category and a fixed description. */
3105
+ export class OpsApiError extends Error {
3106
+ status;
3107
+ operation;
3108
+ category;
3109
+ constructor(status, operation, category) {
3110
+ super(`Ops API call failed (${status}) for '${operation}': ` +
3111
+ (category === null ? OPS_API_REFUSAL_DESCRIPTION : OPS_API_ERROR_DESCRIPTIONS[category]));
3112
+ this.name = "OpsApiError";
3113
+ this.status = status;
3114
+ this.operation = operation;
3115
+ this.category = category;
3116
+ }
3117
+ }
3118
+ function classifyOpsApiError(status, operation, body, text) {
3119
+ // Classify the parsed body's `error` string, or `message` only when the body
3120
+ // has no `error` key at all, and only when the status (and, for already-exists,
3121
+ // operation) is the category's own. Anything else — a non-JSON body, a value
3122
+ // that is not a string, another field, another status, or another operation for
3123
+ // already-exists — is unclassified. The value is never returned or printed.
3124
+ let parsed;
3125
+ try {
3126
+ parsed = JSON.parse(text);
3127
+ }
3128
+ catch {
3129
+ return null;
3130
+ }
3131
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
3132
+ return null;
3133
+ const record = parsed;
3134
+ const value = "error" in record ? record.error : record.message;
3135
+ if (typeof value !== "string")
3136
+ return null;
3137
+ for (const [category, pattern] of OPS_API_ERROR_PATTERNS) {
3138
+ if (!categoryMatches(category, status, operation))
3139
+ continue;
3140
+ const match = pattern.exec(value);
3141
+ if (match === null)
3142
+ continue;
3143
+ if (category === "already-exists") {
3144
+ // Match the submitted username, not another user named by the response.
3145
+ if (typeof body.username !== "string" || match[1] !== body.username)
3146
+ return null;
3147
+ }
3148
+ return category;
3149
+ }
3150
+ return null;
3151
+ }
3071
3152
  export async function callOpsApi(opsUrl, body, user, pass) {
3072
3153
  const url = `${opsUrl.replace(/\/$/, "")}/`;
3073
3154
  const auth = Buffer.from(`${user}:${pass}`).toString("base64");
@@ -3081,14 +3162,35 @@ export async function callOpsApi(opsUrl, body, user, pass) {
3081
3162
  });
3082
3163
  }
3083
3164
  catch (err) {
3084
- const message = err instanceof Error ? err.message : String(err);
3085
- throw new Error(`ops API unreachable at ${opsUrl} (derived from --target). ` +
3086
- `Set --ops-target or FLAIR_OPS_TARGET to override. ` +
3087
- `(${message})`);
3165
+ let target = "the configured ops target";
3166
+ try {
3167
+ const parsed = new URL(opsUrl);
3168
+ if (parsed.protocol === "http:" || parsed.protocol === "https:")
3169
+ target = parsed.origin;
3170
+ }
3171
+ catch { }
3172
+ let category = "no response";
3173
+ const seen = new Set();
3174
+ for (let current = err; current && typeof current === "object" && !seen.has(current);) {
3175
+ seen.add(current);
3176
+ const failure = current;
3177
+ if (failure.code === "ECONNREFUSED" || failure.code === "ConnectionRefused") {
3178
+ category = "connection refused";
3179
+ break;
3180
+ }
3181
+ if (failure.name === "TimeoutError" || failure.code === "ETIMEDOUT" || failure.code === "UND_ERR_CONNECT_TIMEOUT") {
3182
+ category = "timed out";
3183
+ break;
3184
+ }
3185
+ current = failure.cause;
3186
+ }
3187
+ throw new Error(`ops API request got no response from ${target} (${category}). ` +
3188
+ `Set --ops-target or FLAIR_OPS_TARGET to override.`);
3088
3189
  }
3089
3190
  if (!res.ok) {
3090
3191
  const text = await res.text().catch(() => "");
3091
- throw new Error(`Ops API call failed (${res.status}): ${text}`);
3192
+ const operation = typeof body.operation === "string" ? body.operation : "unknown";
3193
+ throw new OpsApiError(res.status, operation, classifyOpsApiError(res.status, operation, body, text));
3092
3194
  }
3093
3195
  return res.json();
3094
3196
  }
@@ -3185,10 +3287,79 @@ export async function waitForFlairRestart(targetUrl, maxWaitMs = 30_000) {
3185
3287
  }
3186
3288
  throw new Error(`Flair did not respond within ${maxWaitMs / 1000}s`);
3187
3289
  }
3188
- export async function provisionFabric(target, opsTarget, clusterAdminUser, clusterAdminPass, flairAdminPass) {
3290
+ export async function provisionFabric(target, opsTarget, clusterAdminUser, clusterAdminPass, flairAdminPass, hooks = {}) {
3189
3291
  const projectRoot = process.cwd();
3190
- // 1. Build and deploy component tarball. `target` is the served URL this
3191
- // function verifies against in step 2 — the same value the component must
3292
+ // 1. Read the cluster's existing users BEFORE any cluster write. The answer
3293
+ // decides whether this run attempts to set `admin`'s password, and a read that fails
3294
+ // must refuse: treating an unknown as "not a super_user" would go on to
3295
+ // change a cluster we could not read.
3296
+ console.log("Checking existing cluster users via ops API...");
3297
+ let userInfo;
3298
+ try {
3299
+ userInfo = await callOpsApi(opsTarget, {
3300
+ operation: "list_users",
3301
+ }, clusterAdminUser, clusterAdminPass);
3302
+ }
3303
+ catch (err) {
3304
+ const message = err instanceof Error ? err.message : String(err);
3305
+ throw new Error(`Could not read the cluster's existing users, so provisioning refused to change anything: ${message}`);
3306
+ }
3307
+ // list_users returns an array of user objects with role/permission info.
3308
+ // A success response of any other shape is unknown, and an unknown is never
3309
+ // "no super_user": refuse before the password is saved or anything is written.
3310
+ if (!Array.isArray(userInfo)) {
3311
+ throw new Error("The cluster's list_users response was not an array, so provisioning refused to change anything");
3312
+ }
3313
+ const users = userInfo;
3314
+ const usernames = [];
3315
+ const superUsers = [];
3316
+ for (const record of users) {
3317
+ const username = record !== null && typeof record === "object" && !Array.isArray(record)
3318
+ ? typeof record.username === "string"
3319
+ ? record.username
3320
+ : typeof record.user?.username === "string"
3321
+ ? record.user.username
3322
+ : undefined
3323
+ : undefined;
3324
+ // A record with no readable username could be the cluster administrator,
3325
+ // so it still refuses before anything is staged or written.
3326
+ if (username === undefined || username === "") {
3327
+ throw new Error("The cluster's list_users response contained a record with no readable username, so provisioning refused to change anything");
3328
+ }
3329
+ usernames.push(username);
3330
+ // Only the authenticated cluster administrator and `admin` decide
3331
+ // provisioning, so only their records need a boolean super_user. Harper
3332
+ // accepts a role that holds database grants and no super_user flag, and
3333
+ // such an unrelated user must not make remote init refuse.
3334
+ if (username === clusterAdminUser || username === DEFAULT_ADMIN_USER) {
3335
+ const permission = record?.role?.permission ?? record?.permission;
3336
+ const superUser = permission?.super_user;
3337
+ if (typeof superUser !== "boolean") {
3338
+ throw new Error("The cluster's list_users response contained a malformed record for a user that decides provisioning, so provisioning refused to change anything");
3339
+ }
3340
+ superUsers.push(superUser);
3341
+ }
3342
+ else {
3343
+ superUsers.push(undefined);
3344
+ }
3345
+ }
3346
+ const clusterAdminRecords = usernames.filter((name) => name === clusterAdminUser).length;
3347
+ if (clusterAdminRecords !== 1) {
3348
+ throw new Error(`The cluster's list_users response does not confirm the cluster administrator '${clusterAdminUser}' exactly once, so provisioning refused to change anything`);
3349
+ }
3350
+ const adminRecords = usernames.filter((name) => name === DEFAULT_ADMIN_USER).length;
3351
+ if (adminRecords > 1) {
3352
+ throw new Error(`The cluster's list_users response lists more than one Flair administrator '${DEFAULT_ADMIN_USER}' record, so provisioning refused to change anything`);
3353
+ }
3354
+ const clusterAdminIndex = usernames.indexOf(clusterAdminUser);
3355
+ const clusterAdminIsSuperUser = superUsers[clusterAdminIndex] === true;
3356
+ const adminExists = adminRecords === 1;
3357
+ if (!clusterAdminIsSuperUser) {
3358
+ // Save the password before anything on the cluster changes.
3359
+ hooks.beforeAdminPasswordApplied?.();
3360
+ }
3361
+ // 2. Build and deploy component tarball. `target` is the served URL this
3362
+ // function verifies against in step 3 — the same value the component must
3192
3363
  // advertise in OAuth/A2A discovery, so it is what FLAIR_PUBLIC_URL is set from
3193
3364
  // (flair#1005). A loopback target supplies nothing: see resolveDeployPublicUrl.
3194
3365
  console.log("Building deploy tarball...");
@@ -3200,62 +3371,33 @@ export async function provisionFabric(target, opsTarget, clusterAdminUser, clust
3200
3371
  payload: tarballB64,
3201
3372
  restart: "rolling",
3202
3373
  }, clusterAdminUser, clusterAdminPass);
3203
- // 2. Wait for restart
3374
+ // 3. Wait for restart
3204
3375
  console.log("Waiting for Flair to restart...");
3205
3376
  await waitForFlairRestart(target);
3206
3377
  console.log("Flair is running ✓");
3207
- // 3. Provision Harper super_user
3378
+ // 4. Provision Harper super_user
3208
3379
  // Since custom-admin-username support is merged, the username doesn't have to be "admin".
3209
3380
  // We can use the cluster-admin user directly if it's already a super_user.
3210
- // Check if cluster admin is already a super_user first:
3211
- let clusterAdminIsSuperUser = false;
3212
- try {
3213
- const userInfo = await callOpsApi(opsTarget, {
3214
- operation: "list_users",
3215
- }, clusterAdminUser, clusterAdminPass);
3216
- // list_users returns an array of user objects with role/permission info
3217
- const users = Array.isArray(userInfo) ? userInfo : [];
3218
- const adminRecord = users.find((u) => u.username === clusterAdminUser || u.user?.username === clusterAdminUser);
3219
- clusterAdminIsSuperUser = !!(adminRecord?.role?.permission?.super_user ??
3220
- adminRecord?.permission?.super_user ??
3221
- false);
3222
- }
3223
- catch {
3224
- // If we can't check, assume not and proceed with add_user
3225
- }
3226
3381
  if (clusterAdminIsSuperUser) {
3227
- console.log(`Cluster admin '${clusterAdminUser}' is already a super_user — skipping user provisioning`);
3382
+ // Reuse branch: the cluster administrator is already a super_user, so the
3383
+ // later calls authenticate as that administrator with the password the
3384
+ // operator supplied; this run did not create `admin`.
3385
+ console.log(`Cluster admin '${clusterAdminUser}' is already a super_user — reusing it as the init principal`);
3386
+ return { username: clusterAdminUser, password: clusterAdminPass, created: false };
3228
3387
  }
3229
3388
  else {
3230
3389
  console.log(`Provisioning Harper user 'admin' as super_user...`);
3231
- try {
3232
- await callOpsApi(opsTarget, {
3233
- operation: "add_user",
3234
- username: "admin",
3235
- password: flairAdminPass,
3236
- role: "super_user",
3237
- active: true,
3238
- }, clusterAdminUser, clusterAdminPass);
3239
- console.log("User 'admin' created ✓");
3240
- }
3241
- catch (err) {
3242
- const msg = err instanceof Error ? err.message : String(err);
3243
- if (msg.includes("already exists") || msg.includes("duplicate")) {
3244
- // Idempotent: fall back to alter_user
3245
- console.log("User 'admin' already exists — updating password...");
3246
- await callOpsApi(opsTarget, {
3247
- operation: "alter_user",
3248
- username: "admin",
3249
- password: flairAdminPass,
3250
- role: "super_user",
3251
- active: true,
3252
- }, clusterAdminUser, clusterAdminPass);
3253
- console.log("User 'admin' updated ✓");
3254
- }
3255
- else {
3256
- throw err;
3257
- }
3258
- }
3390
+ hooks.adminPasswordRequestSent?.();
3391
+ await callOpsApi(opsTarget, {
3392
+ operation: adminExists ? "alter_user" : "add_user",
3393
+ username: "admin",
3394
+ password: flairAdminPass,
3395
+ role: "super_user",
3396
+ active: true,
3397
+ }, clusterAdminUser, clusterAdminPass);
3398
+ console.log(adminExists ? "User 'admin' updated ✓" : "User 'admin' created ✓");
3399
+ hooks.afterAdminPasswordApplied?.();
3400
+ return { username: "admin", password: flairAdminPass, created: true };
3259
3401
  }
3260
3402
  }
3261
3403
  // ─── flair_pair_initiator role ──────────────────────────────────────────────
@@ -3883,7 +4025,7 @@ program.hook("preAction", async (_thisCommand, actionCommand) => {
3883
4025
  });
3884
4026
  // ─── flair init ────────────────────────────────────────────────────────────
3885
4027
  // Command registration lives in src/commands/init.ts (flair#1636).
3886
- // Bind shared cli-locals first so the extracted module never imports this file.
4028
+ // Bind shared cli-locals first so the extracted module never imports this file at runtime.
3887
4029
  bindInitCli({
3888
4030
  api,
3889
4031
  b64url,
@@ -3893,6 +4035,7 @@ bindInitCli({
3893
4035
  ensureFlairAgentRole,
3894
4036
  ensureFlairAgentUser,
3895
4037
  ensureFlairPairInitiatorRole,
4038
+ FLAIR_AGENT_USERNAME,
3896
4039
  flairPackageDir,
3897
4040
  harperBin,
3898
4041
  harperConfigPath,
@@ -4374,8 +4517,8 @@ function readProcessState(pid, timeoutMs, onReadError) {
4374
4517
  * still answers signal 0. After the signal-0 probe succeeds, read the process
4375
4518
  * state and report a zombie as `gone`, so `flair doctor`'s stop wait stops
4376
4519
  * waiting on a process that has already exited (flair#2313). An unreadable
4377
- * state stays `alive` — a read failure must never report a live process as
4378
- * exited.
4520
+ * state stays `alive` unless a re-probe reports ESRCH — a read failure must
4521
+ * never report a live process as exited.
4379
4522
  *
4380
4523
  * The state reader is injectable so the unreadable and retried branches are
4381
4524
  * unit-testable without a real unreadable process.
@@ -4400,6 +4543,19 @@ export function probePidLiveness(pid, readState = readProcessState, deadlineMs =
4400
4543
  if (state !== null)
4401
4544
  break;
4402
4545
  }
4546
+ if (state === null) {
4547
+ // The pid can exit between the signal-0 probe and the state reads: signal 0
4548
+ // then says it exists while the reads find nothing. Re-probe the pid; ESRCH
4549
+ // is evidence it is gone, where an unreadable state alone stays fail-safe.
4550
+ try {
4551
+ process.kill(pid, 0);
4552
+ }
4553
+ catch (err) {
4554
+ if (err?.code === "ESRCH")
4555
+ return { kind: "gone" };
4556
+ }
4557
+ return { kind: "alive" };
4558
+ }
4403
4559
  return isExitedState(state) ? { kind: "gone" } : { kind: "alive" };
4404
4560
  }
4405
4561
  /**
@@ -4407,7 +4563,8 @@ export function probePidLiveness(pid, readState = readProcessState, deadlineMs =
4407
4563
  * `deadlineMs` passes; return whether `gone` was read and the last read
4408
4564
  * (flair#2330). This is `flair doctor`'s stop wait.
4409
4565
  *
4410
- * If both state reads fail, that poll stays `alive`.
4566
+ * If both state reads fail and the pid still answers signal 0, that poll stays
4567
+ * `alive`; an ESRCH at the re-probe reports it `gone`.
4411
4568
  * Check expiry before each read; an admitted read gets at least 1s to finish.
4412
4569
  * Readers honoring their timeout allow deadline + 1s, plus scheduling and subprocess overhead.
4413
4570
  */
@@ -5037,6 +5194,7 @@ function realRepointDeps() {
5037
5194
  samePath: samePathCanonical,
5038
5195
  canonical: canonicalOr,
5039
5196
  treeVersion: (dir) => readFlairPackageAt(dir)?.version ?? null,
5197
+ homebrewOptAlias: (nodeBin) => homebrewOptAlias(nodeBin),
5040
5198
  };
5041
5199
  }
5042
5200
  /**
@@ -5630,8 +5788,8 @@ function validateAdminPassFileForLauncher(path) {
5630
5788
  * 1. An on-disk plist that is provably ours IN THE PASS-FILE SHAPE is never
5631
5789
  * regenerated. An adopted instance is never downgraded, and a re-run of
5632
5790
  * init does not churn mtime / flap launchd state. Its runtime paths alone
5633
- * are re-pointed when it serves another npm-global tree (flair#2034,
5634
- * src/lib/service-repoint.ts); otherwise it is left byte-for-byte unchanged.
5791
+ * are re-pointed in the cases src/lib/service-repoint.ts lists (flair#2034);
5792
+ * otherwise it is left byte-for-byte unchanged.
5635
5793
  * 2. A plist that is provably another instance's (`foreign`) or cannot be
5636
5794
  * attributed (`unattributable`) is refused, naming `flair doctor --fix`.
5637
5795
  * 3. Otherwise, resolve the pass file BEFORE writing anything: reuse an
@@ -7455,6 +7613,8 @@ bindReembedCli({
7455
7613
  privKeyPath,
7456
7614
  resolveHttpPort,
7457
7615
  resolveOpsPort,
7616
+ resolveAgentHomeTarget,
7617
+ ambiguousInstanceTargetError: AMBIGUOUS_INSTANCE_TARGET_ERROR,
7458
7618
  });
7459
7619
  registerReembed(program);
7460
7620
  // ─── flair test ────────────────────────────────────────────────────────────