@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.
- package/README.md +8 -7
- package/SECURITY.md +55 -33
- package/dist/bridges/runtime/import-runner.js +4 -0
- package/dist/build-info.json +3 -3
- package/dist/cli.js +243 -83
- package/dist/commands/agent.js +298 -72
- package/dist/commands/attention.js +2 -0
- package/dist/commands/bootstrap.js +2 -0
- package/dist/commands/bridge.js +10 -0
- package/dist/commands/doctor.js +87 -42
- package/dist/commands/export.js +141 -11
- package/dist/commands/import.js +36 -15
- package/dist/commands/init.js +373 -157
- package/dist/commands/keys.js +12 -8
- package/dist/commands/mcp.js +146 -62
- package/dist/commands/memory.js +5 -2
- package/dist/commands/migrate-harness-memory.js +9 -3
- package/dist/commands/principal.js +19 -14
- package/dist/commands/quality.js +23 -3
- package/dist/commands/reembed.js +468 -111
- package/dist/commands/search.js +2 -0
- package/dist/commands/service.js +25 -0
- package/dist/commands/status.js +130 -107
- package/dist/doctor-client.js +2 -23
- package/dist/federation/scheduler.js +148 -12
- package/dist/keystore.js +77 -10
- package/dist/lib/agent-key-file.js +509 -0
- package/dist/lib/agent-rotation-lock.js +249 -0
- package/dist/lib/atomic-write.js +2 -2
- package/dist/lib/auth-resolve.js +14 -14
- package/dist/lib/key-dir.js +203 -0
- package/dist/lib/launchd-management.js +7 -3
- package/dist/lib/local-instance-pair.js +8 -1
- package/dist/lib/node-alias-path.js +50 -2
- package/dist/lib/remote-admin-pass.js +157 -0
- package/dist/lib/scheduler-platform.js +13 -0
- package/dist/lib/service-repoint.js +13 -4
- package/dist/lib/skill-seed.js +35 -3
- package/dist/lib/terminal-text.js +32 -0
- package/dist/mcp-client-assertion.js +5 -4
- package/dist/resources/Memory.js +47 -3
- package/dist/resources/health.js +39 -22
- package/dist/resources/in-process-api.js +74 -11
- package/dist/resources/mcp-client-metadata-fields.js +4 -0
- package/dist/resources/mcp-handler.js +40 -1
- package/dist/resources/mcp-oauth.js +17 -1
- package/dist/resources/mcp-tool-scopes.js +69 -0
- package/dist/resources/mcp-tools.js +10 -0
- package/dist/resources/skill-version-write.js +16 -0
- package/dist/src/keystore.js +77 -10
- package/dist/src/lib/atomic-write.js +2 -2
- package/dist/src/lib/key-dir.js +203 -0
- package/dist/src/lib/scheduler-platform.js +13 -0
- package/docs/access-control.md +21 -12
- package/docs/api-reference.md +35 -24
- package/docs/auth.md +31 -22
- package/docs/deploying-on-fabric.md +10 -2
- package/docs/embedding-in-a-harper-app.md +7 -7
- package/docs/entity-vocabulary.md +4 -5
- package/docs/hosted-on-fabric.md +1 -1
- package/docs/secrets-and-keys.md +8 -13
- package/docs/upgrade.md +15 -5
- package/package.json +1 -1
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* remote-admin-pass.ts — save the Flair administrator password chosen for a
|
|
3
|
+
* remote `flair init` provisioning run BEFORE the cluster change that applies
|
|
4
|
+
* it (flair#3130).
|
|
5
|
+
*
|
|
6
|
+
* Save before the cluster change so a failed save stops provisioning.
|
|
7
|
+
* An existing credential stays in place until the staged value is confirmed.
|
|
8
|
+
* After a password attempt, keep a direct write or remaining sibling.
|
|
9
|
+
*/
|
|
10
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, } from "node:fs";
|
|
11
|
+
import { randomBytes } from "node:crypto";
|
|
12
|
+
import { basename, dirname, join } from "node:path";
|
|
13
|
+
/** A save/confirm refusal. The caller prints the message (which names the file). */
|
|
14
|
+
export class RemoteAdminPassError extends Error {
|
|
15
|
+
constructor(message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "RemoteAdminPassError";
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
let beforeRenameForTests;
|
|
21
|
+
export function setRemoteAdminPassTestHooks(hooks) {
|
|
22
|
+
beforeRenameForTests = hooks?.beforeRename;
|
|
23
|
+
}
|
|
24
|
+
function errnoCode(error) {
|
|
25
|
+
const code = error?.code;
|
|
26
|
+
return typeof code === "string" ? code : undefined;
|
|
27
|
+
}
|
|
28
|
+
const NOFOLLOW = process.platform === "win32" ? 0 : constants.O_NOFOLLOW;
|
|
29
|
+
const O_NONBLOCK = process.platform === "win32" ? 0 : constants.O_NONBLOCK;
|
|
30
|
+
function currentUid() {
|
|
31
|
+
return typeof process.getuid === "function" ? process.getuid() : undefined;
|
|
32
|
+
}
|
|
33
|
+
function modeText(mode) {
|
|
34
|
+
return (mode & 0o777).toString(8).padStart(3, "0");
|
|
35
|
+
}
|
|
36
|
+
function assertReplaceableTarget(path, st) {
|
|
37
|
+
if (st.isSymbolicLink()) {
|
|
38
|
+
throw new RemoteAdminPassError(`credential file ${path} is a symbolic link; replace it with a real regular file you own`);
|
|
39
|
+
}
|
|
40
|
+
if (!st.isFile()) {
|
|
41
|
+
throw new RemoteAdminPassError(`credential file ${path} is not a regular file; make it a writable regular file you own`);
|
|
42
|
+
}
|
|
43
|
+
const uid = currentUid();
|
|
44
|
+
if (uid !== undefined && st.uid !== uid) {
|
|
45
|
+
throw new RemoteAdminPassError(`credential file ${path} is owned by another user; move it aside so flair can write a file you own`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** Read the final path's current state, or null when it does not exist. */
|
|
49
|
+
function readTarget(path) {
|
|
50
|
+
try {
|
|
51
|
+
return lstatSync(path);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (errnoCode(error) === "ENOENT")
|
|
55
|
+
return null;
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function verifySaved(path, expected) {
|
|
60
|
+
// Open once; no-follow on POSIX, ordinary open on Windows. Stat and read
|
|
61
|
+
// through that descriptor.
|
|
62
|
+
let fd;
|
|
63
|
+
try {
|
|
64
|
+
fd = openSync(path, constants.O_RDONLY | NOFOLLOW | O_NONBLOCK);
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
if (errnoCode(error) === "ELOOP") {
|
|
68
|
+
throw new RemoteAdminPassError(`credential file ${path} is a symbolic link after saving; replace it with a real regular file you own`);
|
|
69
|
+
}
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
const st = fstatSync(fd);
|
|
74
|
+
if (!st.isFile()) {
|
|
75
|
+
throw new RemoteAdminPassError(`credential file ${path} is not a regular file after saving`);
|
|
76
|
+
}
|
|
77
|
+
const uid = currentUid();
|
|
78
|
+
if (uid !== undefined && st.uid !== uid) {
|
|
79
|
+
throw new RemoteAdminPassError(`credential file ${path} is owned by another user after saving`);
|
|
80
|
+
}
|
|
81
|
+
if ((st.mode & 0o077) !== 0) {
|
|
82
|
+
throw new RemoteAdminPassError(`credential file ${path} is accessible to other users after saving (mode ${modeText(st.mode)}); run chmod 600 ${path}`);
|
|
83
|
+
}
|
|
84
|
+
const actual = readFileSync(fd, "utf8");
|
|
85
|
+
if (actual !== expected) {
|
|
86
|
+
throw new RemoteAdminPassError(`credential file ${path} does not hold the saved value after saving`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
closeSync(fd);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function passes(path, expected) {
|
|
94
|
+
try {
|
|
95
|
+
verifySaved(path, expected);
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Save `password` to `path` before the cluster change. Returns a stage whose
|
|
104
|
+
* `confirm()` must run after the change succeeds.
|
|
105
|
+
*
|
|
106
|
+
* - No existing file: writes `path` now (0600); `abort()` is a no-op because
|
|
107
|
+
* the saved value is kept for a later run.
|
|
108
|
+
* - Existing file: writes a mode-0600 sibling and `confirm()` renames it over
|
|
109
|
+
* `path`; `abort()` attempts to remove the sibling and leaves `path` untouched.
|
|
110
|
+
*/
|
|
111
|
+
export function stageRemoteAdminPassword(path, password, writeOwnerOnly) {
|
|
112
|
+
const content = password + "\n";
|
|
113
|
+
const current = readTarget(path);
|
|
114
|
+
if (current === null) {
|
|
115
|
+
writeOwnerOnly(path, content);
|
|
116
|
+
return {
|
|
117
|
+
path,
|
|
118
|
+
hadExistingFile: false,
|
|
119
|
+
stagedPath: null,
|
|
120
|
+
stagedFileVerified: false,
|
|
121
|
+
confirm: () => verifySaved(path, content),
|
|
122
|
+
stillValid: () => passes(path, content),
|
|
123
|
+
abort: () => {
|
|
124
|
+
/* the freshly saved value is kept for the next run */
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
assertReplaceableTarget(path, current);
|
|
129
|
+
const pending = join(dirname(path), `.${basename(path)}.pending-${process.pid}-${randomBytes(6).toString("hex")}`);
|
|
130
|
+
writeOwnerOnly(pending, content);
|
|
131
|
+
let stagedFileVerified = false;
|
|
132
|
+
return {
|
|
133
|
+
path,
|
|
134
|
+
hadExistingFile: true,
|
|
135
|
+
stagedPath: pending,
|
|
136
|
+
get stagedFileVerified() { return stagedFileVerified; },
|
|
137
|
+
confirm: () => {
|
|
138
|
+
// Check before publishing; leave a remaining sibling for recovery.
|
|
139
|
+
// Rename publishes the checked file unless the staged path is replaced in between.
|
|
140
|
+
stagedFileVerified = false;
|
|
141
|
+
verifySaved(pending, content);
|
|
142
|
+
stagedFileVerified = true;
|
|
143
|
+
beforeRenameForTests?.(pending);
|
|
144
|
+
renameSync(pending, path);
|
|
145
|
+
},
|
|
146
|
+
stillValid: () => passes(pending, content),
|
|
147
|
+
abort: () => {
|
|
148
|
+
try {
|
|
149
|
+
unlinkSync(pending);
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
if (errnoCode(error) !== "ENOENT")
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
@@ -477,6 +477,19 @@ export function describeScheduledDriverFinding(f) {
|
|
|
477
477
|
};
|
|
478
478
|
}
|
|
479
479
|
// Loaded from here down.
|
|
480
|
+
if (f.shimMissingNode) {
|
|
481
|
+
const m = f.shimMissingNode;
|
|
482
|
+
return {
|
|
483
|
+
state: "degraded",
|
|
484
|
+
icon: "error",
|
|
485
|
+
isIssue: true,
|
|
486
|
+
message: `${f.label} DEGRADED — the shim its unit file names execs a node binary that does not exist (${m.nodeBin})`,
|
|
487
|
+
detail: [
|
|
488
|
+
`${m.unitPath} names ${m.shimPath} as its program; the shim's exec line names ${m.nodeBin}, which does not exist.`,
|
|
489
|
+
`Fix: flair init # then check: ${f.statusCommand}`,
|
|
490
|
+
],
|
|
491
|
+
};
|
|
492
|
+
}
|
|
480
493
|
const le = f.lastExit;
|
|
481
494
|
if (!le || le.state === "unavailable") {
|
|
482
495
|
return {
|
|
@@ -45,10 +45,15 @@
|
|
|
45
45
|
* - the old tree's flair version (or this CLI's) cannot be read, is not strict
|
|
46
46
|
* semver, or is newer by semver ordering (0.57.0-beta.1 is older than 0.57.0)
|
|
47
47
|
* → refused: a downgrade cannot be ruled out;
|
|
48
|
-
* - it serves THIS CLI's tree with an existing, different
|
|
49
|
-
*
|
|
48
|
+
* - with valid targets, it serves THIS CLI's tree with an existing, different
|
|
49
|
+
* node and its other runtime paths exist → `pinned-node`, apart from the
|
|
50
|
+
* launchd Homebrew case below; systemd refuses missing runtime paths;
|
|
50
51
|
* - launchd only: it serves this CLI's tree and one of its runtime paths no
|
|
51
|
-
* longer exists →
|
|
52
|
+
* longer exists → the missing path is replaced (systemd: refused);
|
|
53
|
+
* - launchd only: it serves this CLI's tree with an existing node path in
|
|
54
|
+
* Homebrew's Cellar whose `opt/<formula>` alias resolves to the same
|
|
55
|
+
* binary → that node path is replaced by the alias, including in the same
|
|
56
|
+
* write as a missing runtime path (flair#3056).
|
|
52
57
|
*
|
|
53
58
|
* Every refusal names the unit file, what did not match, and the remedy — the
|
|
54
59
|
* paths to set by hand, an update, or a reinstall.
|
|
@@ -395,13 +400,17 @@ export function planPlistRuntimeRepoint(raw, t, deps, plistPath, owner) {
|
|
|
395
400
|
const next = { ...current };
|
|
396
401
|
const sameTree = deps.samePath(oldTree, t.workingDirectory);
|
|
397
402
|
if (sameTree) {
|
|
398
|
-
// Same tree: replace
|
|
403
|
+
// Same tree: replace what no longer exists, and an existing Homebrew Cellar
|
|
404
|
+
// node whose opt alias resolves to the same binary (flair#3056); any other
|
|
405
|
+
// existing different node is a deliberate pin.
|
|
399
406
|
if (!deps.exists(current.launcher))
|
|
400
407
|
next.launcher = t.launcher;
|
|
401
408
|
if (!deps.exists(current.harperBin))
|
|
402
409
|
next.harperBin = t.harperBin;
|
|
403
410
|
if (!deps.exists(current.nodeBin))
|
|
404
411
|
next.nodeBin = t.nodeBin;
|
|
412
|
+
else
|
|
413
|
+
next.nodeBin = deps.homebrewOptAlias(current.nodeBin) ?? current.nodeBin;
|
|
405
414
|
}
|
|
406
415
|
else {
|
|
407
416
|
const refusal = treeGate(oldTree, t, deps, unit, true);
|
package/dist/lib/skill-seed.js
CHANGED
|
@@ -200,7 +200,13 @@ export async function runSkillSeed(io, current, clock = REAL_CLOCK) {
|
|
|
200
200
|
await clock.pause(SEED_SKILL_WRITE_RETRY_BACKOFF_MS);
|
|
201
201
|
}
|
|
202
202
|
}
|
|
203
|
-
|
|
203
|
+
/**
|
|
204
|
+
* The seed's reads and refusals, with no write. {@link seedPass} runs it before
|
|
205
|
+
* its writes, and {@link checkUsingFlairSkill} runs it alone as init's
|
|
206
|
+
* preflight; the two calls use the same checks and message templates (expiry
|
|
207
|
+
* checks read the real clock on each pass).
|
|
208
|
+
*/
|
|
209
|
+
async function checkSeed(io, current) {
|
|
204
210
|
const rowRead = await io.readRow();
|
|
205
211
|
if (!rowRead.ok) {
|
|
206
212
|
return refused("skill_seed_row_unreadable", `the "${SEED_SKILL_ID}" Memory row could not be read (${rowRead.detail ?? "no detail"}); ${NOTHING_WRITTEN}. ` +
|
|
@@ -243,6 +249,13 @@ async function seedPass(io, current, rowWriteBudget) {
|
|
|
243
249
|
return refused("skill_seed_assignment_mismatch", `the "${SEED_ASSIGNMENT_ID}" org assignment ${problems.join("; ")}; ${NOTHING_WRITTEN}. ${ASSIGNMENT_REMEDY}`);
|
|
244
250
|
}
|
|
245
251
|
}
|
|
252
|
+
return { kind: "ready", storedContent, assignment: assignRead.row ?? null };
|
|
253
|
+
}
|
|
254
|
+
async function seedPass(io, current, rowWriteBudget) {
|
|
255
|
+
const checked = await checkSeed(io, current);
|
|
256
|
+
if (checked.kind !== "ready")
|
|
257
|
+
return checked;
|
|
258
|
+
const { storedContent, assignment } = checked;
|
|
246
259
|
const action = decideSkillSeed(storedContent, current.content, current.hashes);
|
|
247
260
|
if (action === "create" || action === "replace") {
|
|
248
261
|
const budgetMs = rowWriteBudget();
|
|
@@ -274,8 +287,8 @@ async function seedPass(io, current, rowWriteBudget) {
|
|
|
274
287
|
`${problems.join("; ")}; the org assignment was not written. Check the Memory table and re-run 'flair init'`);
|
|
275
288
|
}
|
|
276
289
|
}
|
|
277
|
-
let assignmentId = String(
|
|
278
|
-
if (!
|
|
290
|
+
let assignmentId = String(assignment?.id ?? "");
|
|
291
|
+
if (!assignment) {
|
|
279
292
|
const write = await io.putAssignment();
|
|
280
293
|
if (!write.ok) {
|
|
281
294
|
return refused("skill_seed_write_failed", `writing the "${SEED_ASSIGNMENT_ID}" org assignment failed (${write.detail ?? "no detail"}); re-run 'flair init'`);
|
|
@@ -446,3 +459,22 @@ export function skillSeedRestIo(opts, current = currentSeed()) {
|
|
|
446
459
|
export function seedUsingFlairSkill(opts) {
|
|
447
460
|
return runSkillSeed(skillSeedRestIo(opts), currentSeed());
|
|
448
461
|
}
|
|
462
|
+
/**
|
|
463
|
+
* Run the seed's reads and refusals on the instance at `baseUrl` without
|
|
464
|
+
* writing anything. `flair init` calls it before the role, shared-user and
|
|
465
|
+
* Agent writes in `finishRemoteInit`, and before the local agent write when it
|
|
466
|
+
* starts its own instance; the seed re-runs the same checks when it writes.
|
|
467
|
+
*/
|
|
468
|
+
export async function checkUsingFlairSkill(opts) {
|
|
469
|
+
const current = currentSeed();
|
|
470
|
+
const checked = await checkSeed(skillSeedRestIo(opts), current);
|
|
471
|
+
if (checked.kind !== "ready")
|
|
472
|
+
return checked;
|
|
473
|
+
return {
|
|
474
|
+
kind: "ok",
|
|
475
|
+
action: decideSkillSeed(checked.storedContent, current.content, current.hashes),
|
|
476
|
+
skillId: SEED_SKILL_ID,
|
|
477
|
+
assignmentId: String(checked.assignment?.id ?? ""),
|
|
478
|
+
message: "the using-flair skill seed passed its checks",
|
|
479
|
+
};
|
|
480
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* terminal-text.ts — escape six Unicode categories in a dynamic fragment
|
|
3
|
+
* before it is printed to a terminal.
|
|
4
|
+
*
|
|
5
|
+
* A stored value (an Agent id, a Soul key, an embedding-model name, a
|
|
6
|
+
* federation field, a server warning) is data, not layout. Printed raw, a
|
|
7
|
+
* control character can move the cursor or erase a line, and a bidi override
|
|
8
|
+
* can reorder one so the row reads differently from the bytes. This renders
|
|
9
|
+
* such a value for a HUMAN: a code point in control (Cc), format (Cf,
|
|
10
|
+
* including bidi overrides), surrogate (Cs), unassigned (Cn), line separator
|
|
11
|
+
* (Zl) or paragraph separator (Zp) is shown as a visible `\u{...}` escape, and
|
|
12
|
+
* every other code point is unchanged.
|
|
13
|
+
*
|
|
14
|
+
* This is display only: callers keep the stored value for JSON output and
|
|
15
|
+
* request bodies, so those stay byte-identical. It deliberately does not
|
|
16
|
+
* reuse boundServerText (auth-resolve.ts), which collapses whitespace and
|
|
17
|
+
* truncates — either would change an id's spelling.
|
|
18
|
+
*/
|
|
19
|
+
const ESCAPED_CATEGORIES = /[\p{Cc}\p{Cf}\p{Cs}\p{Cn}\p{Zl}\p{Zp}]/u;
|
|
20
|
+
export function escapeTerminalText(value) {
|
|
21
|
+
let out = "";
|
|
22
|
+
for (const ch of value) {
|
|
23
|
+
if (ESCAPED_CATEGORIES.test(ch)) {
|
|
24
|
+
const cp = ch.codePointAt(0) ?? 0;
|
|
25
|
+
out += `\\u{${cp.toString(16).padStart(2, "0")}}`;
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
out += ch;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
@@ -64,6 +64,7 @@ import { createPrivateKey, createPublicKey, randomUUID, sign } from "node:crypto
|
|
|
64
64
|
import { existsSync, readFileSync } from "node:fs";
|
|
65
65
|
import { join } from "node:path";
|
|
66
66
|
import { resolveHome } from "./lib/home.js";
|
|
67
|
+
import { agentKeyPath, legacyAgentKeyPath } from "./lib/key-dir.js";
|
|
67
68
|
// ─── RFC 7523 constants ─────────────────────────────────────────────────────
|
|
68
69
|
/** RFC 7523 §2.2 value for `client_assertion_type`. */
|
|
69
70
|
export const CLIENT_ASSERTION_TYPE_JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
|
|
@@ -175,10 +176,10 @@ export async function resolveClientAssertionAudience(params) {
|
|
|
175
176
|
*/
|
|
176
177
|
export function resolveAgentKeyPath(agentId, keysDirOverride) {
|
|
177
178
|
const candidates = [
|
|
178
|
-
keysDirOverride ?
|
|
179
|
-
process.env.FLAIR_KEY_DIR ?
|
|
180
|
-
join(resolveHome(), ".flair", "keys",
|
|
181
|
-
|
|
179
|
+
keysDirOverride ? agentKeyPath(keysDirOverride, agentId) : null,
|
|
180
|
+
process.env.FLAIR_KEY_DIR ? agentKeyPath(process.env.FLAIR_KEY_DIR, agentId) : null,
|
|
181
|
+
agentKeyPath(join(resolveHome(), ".flair", "keys"), agentId),
|
|
182
|
+
legacyAgentKeyPath(agentId),
|
|
182
183
|
].filter((p) => Boolean(p));
|
|
183
184
|
return candidates.find((p) => existsSync(p)) ?? null;
|
|
184
185
|
}
|
package/dist/resources/Memory.js
CHANGED
|
@@ -32,7 +32,7 @@ import { admitLockedMemoryWrite } from "./memory-write-transaction.js";
|
|
|
32
32
|
import { assertValidDurability, stampEphemeralExpiry } from "./memory-durability.js";
|
|
33
33
|
import { embedTextField, enforceSkillDurability, isSkillWrite, rejectSkillWritePath, refuseSkillWriteSource, skillEmbedText, skillScanGate, skillMetadataHasDuplicateKey } from "./skill-write.js";
|
|
34
34
|
import { embeddedTextHash, hashEmbeddedText } from "./memory-embed-hash.js";
|
|
35
|
-
import { afterCloseStaged, buildSkillSuccessorRow, closedSkillPayloadReadable, defaultSkillHooks, grantedSkillClose, resolveSkillHead, rowIsSkill, runSkillVersionWrite, skillVersionVisibility, skillPayloadUnchanged, prepareSkillBody, validateSkillSnapshots, authorizeSkillOwners, skillWriteConflict } from "./skill-version-write.js";
|
|
35
|
+
import { afterCloseStaged, buildSkillSuccessorRow, closedSkillPayloadReadable, defaultSkillHooks, grantedSkillClose, resolveSkillHead, rowIsSkill, runSkillVersionWrite, skillTargetSnapshotChanged, skillVersionVisibility, skillPayloadUnchanged, prepareSkillBody, validateSkillSnapshots, authorizeSkillOwners, skillWriteConflict } from "./skill-version-write.js";
|
|
36
36
|
import { SKILL_SUBJECT_TYPE, removeAppendedVersion } from "./instruction-version-record.js";
|
|
37
37
|
import { deriveSkillSubjectId } from "./skill-subject.js";
|
|
38
38
|
import { DEDUP_COSINE_THRESHOLD_DEFAULT, DEDUP_LEXICAL_THRESHOLD_DEFAULT, DEDUP_MIN_CONTENT_LENGTH, computeMatchConfidence, cosineSimilarity, isConservativeMatch, } from "./dedup.js";
|
|
@@ -1441,7 +1441,14 @@ async function writeSkillCreateOrUpdate(args) {
|
|
|
1441
1441
|
// verb can re-plan with it.
|
|
1442
1442
|
const runSkillWrite = (heldIds, headMoved) => runSkillVersionWrite({
|
|
1443
1443
|
ctx,
|
|
1444
|
-
|
|
1444
|
+
// A POST that SUPERSEDES an existing target plans in a fresh OWNED
|
|
1445
|
+
// transaction (flair#3170): the joined request transaction's reads can
|
|
1446
|
+
// predate a commit the verb's target read already saw (a previous write's
|
|
1447
|
+
// embedding backfill), and the stale-target check would refuse the retry.
|
|
1448
|
+
// An in-place reserved seed POST supersedes nothing and joins the caller's
|
|
1449
|
+
// transaction when one is open and joinable, so a caller abort still
|
|
1450
|
+
// undoes it.
|
|
1451
|
+
joinCallerTransaction: method === "post" && (!storedRow || inPlaceId != null),
|
|
1445
1452
|
subjectId,
|
|
1446
1453
|
agentId: String(content.agentId),
|
|
1447
1454
|
deferConfirmation: true,
|
|
@@ -1589,6 +1596,11 @@ async function writeSkillCreateOrUpdate(args) {
|
|
|
1589
1596
|
return new SkillLockExtension([String(head.id)]);
|
|
1590
1597
|
}
|
|
1591
1598
|
const headMoved = { id: null };
|
|
1599
|
+
// Test-only: holds a skill POST before its plan runs under the lock, after
|
|
1600
|
+
// the verb read its target (flair#3170).
|
|
1601
|
+
const planPause = txnPausePoint("memory-post-skill-plan");
|
|
1602
|
+
if (planPause)
|
|
1603
|
+
await planPause;
|
|
1592
1604
|
const outcome = await runSkillWrite(heldIds, headMoved);
|
|
1593
1605
|
if (headMoved.id)
|
|
1594
1606
|
return new SkillLockExtension([headMoved.id]);
|
|
@@ -2316,6 +2328,12 @@ export class Memory extends databases.flair.Memory {
|
|
|
2316
2328
|
* commits after the lock is released; a superseding skill write owns its
|
|
2317
2329
|
* commit. A POST that names neither takes no lock. */
|
|
2318
2330
|
async post(content, context) {
|
|
2331
|
+
// Test-only: on the HTTP request path, holds a POST after its request
|
|
2332
|
+
// transaction opened and before it takes the target's lock and reads it, so
|
|
2333
|
+
// a concurrent commit can land in between (flair#3170).
|
|
2334
|
+
const targetReadPause = txnPausePoint("memory-post-target-read");
|
|
2335
|
+
if (targetReadPause)
|
|
2336
|
+
await targetReadPause;
|
|
2319
2337
|
// flair#2307: resolve the `supersedes` reference to its canonical id once,
|
|
2320
2338
|
// before lock selection (some POSTs take no lock), so the predecessor read,
|
|
2321
2339
|
// the close and any lock taken name that id (a selector or encoded
|
|
@@ -2425,7 +2443,33 @@ export class Memory extends databases.flair.Memory {
|
|
|
2425
2443
|
(typeof postUrlTargetId === "string" || typeof postUrlTargetId === "number")) {
|
|
2426
2444
|
content.id = postUrlTargetId;
|
|
2427
2445
|
}
|
|
2428
|
-
const
|
|
2446
|
+
const postSnapshot = content.id ? await databases.flair.Memory.get(content.id) : null;
|
|
2447
|
+
// The in-place predicate the skill plan uses, a reserved seed id named by
|
|
2448
|
+
// the body or the URL: an in-place POST supersedes nothing, so it keeps the
|
|
2449
|
+
// request-snapshot target read and the caller's transaction (flair#3170).
|
|
2450
|
+
const postInPlace = [content?.id, postUrlTargetId].some((candidate) => isReservedSeedId("Memory", candidate));
|
|
2451
|
+
// flair#3170: a skill POST that supersedes a target present in the request
|
|
2452
|
+
// snapshot reads the target as committed when it still exists. The only
|
|
2453
|
+
// change that window accepts is the previous write's embedding backfill
|
|
2454
|
+
// fields. The plan's stale-target check then compares two committed reads
|
|
2455
|
+
// and the retry is not refused. Any other change to the target in that
|
|
2456
|
+
// window answers 409 skill_target_changed, and a target gone by this read
|
|
2457
|
+
// is refused the same way, recreating no row and appending no
|
|
2458
|
+
// InstructionVersion. The body may omit `tags` and inherit the skill
|
|
2459
|
+
// tag from the stored row, the source prepareSkillBody uses, so either
|
|
2460
|
+
// row's tags decide whether this read applies.
|
|
2461
|
+
const postStoredRead = !!(postSnapshot && !postInPlace && (isSkillWrite(content) || rowIsSkill(postSnapshot)));
|
|
2462
|
+
// Test-only: holds a skill POST after its request-snapshot read and before
|
|
2463
|
+
// its committed target read, so a concurrent delete can land in between
|
|
2464
|
+
// (flair#3170).
|
|
2465
|
+
const committedReadPause = postStoredRead ? txnPausePoint("memory-post-committed-read") : undefined;
|
|
2466
|
+
if (committedReadPause)
|
|
2467
|
+
await committedReadPause;
|
|
2468
|
+
const postCommitted = postStoredRead && postSnapshot ? await databases.flair.Memory.get(String(postSnapshot.id), {}) : null;
|
|
2469
|
+
if (postStoredRead && postSnapshot && (!postCommitted || skillTargetSnapshotChanged(postSnapshot, postCommitted))) {
|
|
2470
|
+
return skillWriteConflict("skill_target_changed");
|
|
2471
|
+
}
|
|
2472
|
+
const postStored = postStoredRead && postSnapshot ? (postCommitted ?? postSnapshot) : postSnapshot;
|
|
2429
2473
|
// flair#2561: the fields this request supplies that `stored` can report —
|
|
2430
2474
|
// its string-valued text fields and, for a skill, the skill fields it
|
|
2431
2475
|
// supplies (flair#2575) — read before a skill predecessor is merged into the
|
package/dist/resources/health.js
CHANGED
|
@@ -365,33 +365,48 @@ export class HealthDetail extends Resource {
|
|
|
365
365
|
}
|
|
366
366
|
const unregisteredMap = new Map();
|
|
367
367
|
const cutoff24h = nowMs - 24 * 3600 * 1000;
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
368
|
+
// Only a completed Memory scan yields counts. A scan that threw part-way
|
|
369
|
+
// leaves a partial `memoriesList`; counting it would report partial
|
|
370
|
+
// numbers as facts, so the loop is skipped and every row below reports
|
|
371
|
+
// its Memory-derived values as unknown.
|
|
372
|
+
if (memoryScanComplete) {
|
|
373
|
+
for (const m of memoriesList) {
|
|
374
|
+
if (!m.agentId)
|
|
375
|
+
continue;
|
|
376
|
+
const known = perAgentMap.get(m.agentId);
|
|
377
|
+
const row = known ?? unregisteredMap.get(m.agentId) ?? blank(m.agentId);
|
|
378
|
+
row.memoryCount++;
|
|
379
|
+
row.usageCount += (m.usageCount ?? 0);
|
|
380
|
+
if (!m.embeddingModel || m.embeddingModel === "hash-512d")
|
|
381
|
+
row.hashFallback++;
|
|
382
|
+
if (m.createdAt) {
|
|
383
|
+
const ts = new Date(m.createdAt).getTime();
|
|
384
|
+
if (ts >= cutoff24h)
|
|
385
|
+
row.writes24h++;
|
|
386
|
+
if (!row.lastWriteAt || ts > new Date(row.lastWriteAt).getTime()) {
|
|
387
|
+
row.lastWriteAt = m.createdAt;
|
|
388
|
+
}
|
|
383
389
|
}
|
|
390
|
+
if (known)
|
|
391
|
+
perAgentMap.set(m.agentId, row);
|
|
392
|
+
else
|
|
393
|
+
unregisteredMap.set(m.agentId, row);
|
|
384
394
|
}
|
|
385
|
-
if (known)
|
|
386
|
-
perAgentMap.set(m.agentId, row);
|
|
387
|
-
else
|
|
388
|
-
unregisteredMap.set(m.agentId, row);
|
|
389
395
|
}
|
|
390
396
|
const agentIds = Array.from(perAgentMap.keys());
|
|
391
|
-
const perAgentFull =
|
|
397
|
+
const perAgentFull = memoryScanComplete
|
|
398
|
+
? Array.from(perAgentMap.values()).sort((a, b) => b.memoryCount - a.memoryCount)
|
|
399
|
+
: agentIds.map((id) => ({
|
|
400
|
+
id,
|
|
401
|
+
memoryCount: null,
|
|
402
|
+
hashFallback: null,
|
|
403
|
+
writes24h: null,
|
|
404
|
+
lastWriteAt: null,
|
|
405
|
+
usageCount: null,
|
|
406
|
+
}));
|
|
392
407
|
const perAgent = isAdmin
|
|
393
408
|
? perAgentFull
|
|
394
|
-
: perAgentFull.filter((r) => r.id === callerAgent || r.memoryCount > 0);
|
|
409
|
+
: perAgentFull.filter((r) => r.id === callerAgent || (r.memoryCount ?? 0) > 0);
|
|
395
410
|
const unregisteredMemoryAuthors = Array.from(unregisteredMap.values())
|
|
396
411
|
.sort((a, b) => b.memoryCount - a.memoryCount)
|
|
397
412
|
.map((r) => ({ id: r.id, memoryCount: r.memoryCount }));
|
|
@@ -405,7 +420,9 @@ export class HealthDetail extends Resource {
|
|
|
405
420
|
// and rows with memories. unregisteredMemoryAuthors is undefined for
|
|
406
421
|
// a non-admin. An admin gets that list only after a complete Memory
|
|
407
422
|
// scan; null means the scan did not finish, so the answer is unknown
|
|
408
|
-
// rather than empty or partial.
|
|
423
|
+
// rather than empty or partial. The same rule covers each row's
|
|
424
|
+
// Memory-derived values: they are null (unknown), never zero or a
|
|
425
|
+
// partial count, when the scan did not complete.
|
|
409
426
|
unregisteredMemoryAuthors: isAdmin
|
|
410
427
|
? (memoryScanComplete ? unregisteredMemoryAuthors : null)
|
|
411
428
|
: undefined,
|
|
@@ -33,6 +33,27 @@ import { agentContext, adminContext, internalContext, collectionResource, InProc
|
|
|
33
33
|
// ─── Re-export for the "./server" entry point ────────────────────────────────
|
|
34
34
|
export { agentContext, adminContext, internalContext, collectionResource, InProcessContextError };
|
|
35
35
|
// ─── Resource resolution ─────────────────────────────────────────────────────
|
|
36
|
+
/**
|
|
37
|
+
* A by-id read through the resource's static `get(id, context)` form, which
|
|
38
|
+
* binds the id before `get()` runs. Resolves to the stored row, or `null` when
|
|
39
|
+
* the resource reports the id absent: a 404 `Response` from a scoped read, or an
|
|
40
|
+
* absent row for an unfiltered one. Any other failure throws rather than
|
|
41
|
+
* resolving to a value a caller could mistake for a missing record.
|
|
42
|
+
*/
|
|
43
|
+
async function readMemoryById(Cls, id, context) {
|
|
44
|
+
const result = await Cls.get(id, context);
|
|
45
|
+
if (result instanceof Response) {
|
|
46
|
+
if (result.status === 404)
|
|
47
|
+
return null;
|
|
48
|
+
throw new Error(`Memory.get(${id}) failed with HTTP ${result.status}`);
|
|
49
|
+
}
|
|
50
|
+
if (result && typeof result === "object" && "error" in result && "status" in result) {
|
|
51
|
+
if (result.status === 404)
|
|
52
|
+
return null;
|
|
53
|
+
throw new Error(`Memory.get(${id}) failed with HTTP ${result.status}: ${result.error}`);
|
|
54
|
+
}
|
|
55
|
+
return result ?? null;
|
|
56
|
+
}
|
|
36
57
|
/**
|
|
37
58
|
* Resolve a Flair resource class from the Harper server registry.
|
|
38
59
|
* Throws with a helpful message listing available resources if not found.
|
|
@@ -105,7 +126,15 @@ export class AgentHandle {
|
|
|
105
126
|
body.subject = opts.subject;
|
|
106
127
|
if (opts?.subjects)
|
|
107
128
|
body.subjects = opts.subjects;
|
|
108
|
-
|
|
129
|
+
const result = await unwrap(await h.post(body));
|
|
130
|
+
if (isFailureEnvelope(result)) {
|
|
131
|
+
throw new Error(`recall() failed: ${result.error} (HTTP ${result.status})`);
|
|
132
|
+
}
|
|
133
|
+
if (Array.isArray(result))
|
|
134
|
+
return result;
|
|
135
|
+
if (result && Array.isArray(result.results))
|
|
136
|
+
return result.results;
|
|
137
|
+
throw new Error(`recall() failed: ${result?.error ?? "unexpected response"}${result?.status ? ` (HTTP ${result.status})` : ""}`);
|
|
109
138
|
}
|
|
110
139
|
}
|
|
111
140
|
// ─── AgentMemory (per-agent memory operations) ───────────────────────────────
|
|
@@ -144,11 +173,10 @@ class AgentMemory {
|
|
|
144
173
|
body.id = opts.id;
|
|
145
174
|
return unwrap(await h.post(body));
|
|
146
175
|
}
|
|
147
|
-
/** Get a memory by id, scoped to this agent. */
|
|
176
|
+
/** Get a memory by id, scoped to this agent. Resolves to `null` when the record is absent or not readable by this agent. */
|
|
148
177
|
async get(id) {
|
|
149
178
|
const Cls = resolveResource(this.#server, "Memory");
|
|
150
|
-
|
|
151
|
-
return unwrap(await h.get(id));
|
|
179
|
+
return readMemoryById(Cls, id, this.#ctx);
|
|
152
180
|
}
|
|
153
181
|
/**
|
|
154
182
|
* Search memories scoped to this agent.
|
|
@@ -175,8 +203,26 @@ class AgentMemory {
|
|
|
175
203
|
if (opts?.visibility) {
|
|
176
204
|
conditions.push({ search_attribute: "visibility", search_type: "equals", search_value: opts.visibility });
|
|
177
205
|
}
|
|
178
|
-
const
|
|
179
|
-
|
|
206
|
+
const limit = opts?.limit;
|
|
207
|
+
if (limit !== undefined && limit <= 0)
|
|
208
|
+
return [];
|
|
209
|
+
const query = conditions.length > 0 ? { conditions, operator: "and" } : {};
|
|
210
|
+
if (limit !== undefined)
|
|
211
|
+
query.limit = limit;
|
|
212
|
+
const source = await unwrap(await h.search(conditions.length > 0 || limit !== undefined ? query : undefined));
|
|
213
|
+
if (Array.isArray(source)) {
|
|
214
|
+
return limit !== undefined ? source.slice(0, limit) : source;
|
|
215
|
+
}
|
|
216
|
+
if (source && typeof source[Symbol.asyncIterator] === "function") {
|
|
217
|
+
const rows = [];
|
|
218
|
+
for await (const row of source) {
|
|
219
|
+
rows.push(row);
|
|
220
|
+
if (limit !== undefined && rows.length >= limit)
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
return rows;
|
|
224
|
+
}
|
|
225
|
+
throw new Error(`memory.search() failed: ${source?.error ?? "unexpected response"}${source?.status ? ` (HTTP ${source.status})` : ""}`);
|
|
180
226
|
}
|
|
181
227
|
}
|
|
182
228
|
// ─── AdminHandle ─────────────────────────────────────────────────────────────
|
|
@@ -235,11 +281,10 @@ class AdminMemory {
|
|
|
235
281
|
this.#ctx = ctx;
|
|
236
282
|
this.#agentId = agentId;
|
|
237
283
|
}
|
|
238
|
-
/** Read any memory by id, unfiltered. */
|
|
284
|
+
/** Read any memory by id, unfiltered. Resolves to `null` for an absent id. */
|
|
239
285
|
async get(id) {
|
|
240
286
|
const Cls = resolveResource(this.#server, "Memory");
|
|
241
|
-
|
|
242
|
-
return unwrap(await h.get(id));
|
|
287
|
+
return readMemoryById(Cls, id, this.#ctx);
|
|
243
288
|
}
|
|
244
289
|
/**
|
|
245
290
|
* Write a memory attributed to another agent.
|
|
@@ -368,19 +413,37 @@ export class Flair {
|
|
|
368
413
|
}
|
|
369
414
|
}
|
|
370
415
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
416
|
+
/**
|
|
417
|
+
* A structured failure: an object carrying an `error` and a numeric
|
|
418
|
+
* `status` >= 400. Only these are rejected before results are extracted.
|
|
419
|
+
*/
|
|
420
|
+
function isFailureEnvelope(value) {
|
|
421
|
+
return (value !== null &&
|
|
422
|
+
typeof value === "object" &&
|
|
423
|
+
!Array.isArray(value) &&
|
|
424
|
+
"error" in value &&
|
|
425
|
+
typeof value.status === "number" &&
|
|
426
|
+
value.status >= 400);
|
|
427
|
+
}
|
|
371
428
|
/**
|
|
372
429
|
* Unwrap a handler return value into a plain object.
|
|
373
430
|
* Handlers may return a `Response` (the 401/403/400 guards) — surface its
|
|
374
431
|
* JSON body so the caller sees the structured error rather than an opaque object.
|
|
432
|
+
* A 2xx `Response` resolves to its parsed body unchanged; a non-2xx one becomes
|
|
433
|
+
* `{ ...body, error, status }` with the response's own status winning.
|
|
375
434
|
*/
|
|
376
435
|
async function unwrap(value) {
|
|
377
436
|
if (value && typeof value === "object" && typeof value.json === "function" && "status" in value) {
|
|
437
|
+
const status = value.status;
|
|
438
|
+
const ok = typeof status === "number" && status >= 200 && status < 300;
|
|
378
439
|
try {
|
|
379
440
|
const body = await value.json();
|
|
380
|
-
|
|
441
|
+
if (ok)
|
|
442
|
+
return body;
|
|
443
|
+
return { ...body, error: body?.error ?? "request failed", status };
|
|
381
444
|
}
|
|
382
445
|
catch {
|
|
383
|
-
return { error: "request failed", status
|
|
446
|
+
return { error: "request failed", status };
|
|
384
447
|
}
|
|
385
448
|
}
|
|
386
449
|
return value;
|