@tpsdev-ai/agent 0.5.4 β†’ 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/bin.js +47 -2
  2. package/dist/bin.js.map +1 -1
  3. package/dist/config.d.ts +2 -1
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/config.js +8 -0
  6. package/dist/config.js.map +1 -1
  7. package/dist/index.d.ts +4 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +4 -0
  10. package/dist/index.js.map +1 -1
  11. package/dist/io/flair.d.ts +53 -0
  12. package/dist/io/flair.d.ts.map +1 -0
  13. package/dist/io/flair.js +157 -0
  14. package/dist/io/flair.js.map +1 -0
  15. package/dist/io/mail.d.ts +39 -2
  16. package/dist/io/mail.d.ts.map +1 -1
  17. package/dist/io/mail.js +303 -15
  18. package/dist/io/mail.js.map +1 -1
  19. package/dist/lib/signEnvelope.d.ts +67 -0
  20. package/dist/lib/signEnvelope.d.ts.map +1 -0
  21. package/dist/lib/signEnvelope.js +244 -0
  22. package/dist/lib/signEnvelope.js.map +1 -0
  23. package/dist/llm/provider.d.ts +19 -1
  24. package/dist/llm/provider.d.ts.map +1 -1
  25. package/dist/llm/provider.js +362 -18
  26. package/dist/llm/provider.js.map +1 -1
  27. package/dist/runtime/agent.d.ts +2 -0
  28. package/dist/runtime/agent.d.ts.map +1 -1
  29. package/dist/runtime/agent.js +53 -3
  30. package/dist/runtime/agent.js.map +1 -1
  31. package/dist/runtime/event-loop.d.ts +36 -5
  32. package/dist/runtime/event-loop.d.ts.map +1 -1
  33. package/dist/runtime/event-loop.js +235 -32
  34. package/dist/runtime/event-loop.js.map +1 -1
  35. package/dist/runtime/types.d.ts +16 -1
  36. package/dist/runtime/types.d.ts.map +1 -1
  37. package/dist/telemetry/events.d.ts +57 -0
  38. package/dist/telemetry/events.d.ts.map +1 -0
  39. package/dist/telemetry/events.js +37 -0
  40. package/dist/telemetry/events.js.map +1 -0
  41. package/dist/tools/edit.d.ts.map +1 -1
  42. package/dist/tools/edit.js +94 -16
  43. package/dist/tools/edit.js.map +1 -1
  44. package/package.json +10 -2
  45. package/src/bin.ts +56 -3
  46. package/src/config.ts +10 -1
  47. package/src/index.ts +8 -0
  48. package/src/io/flair.ts +197 -0
  49. package/src/io/mail.ts +341 -19
  50. package/src/lib/signEnvelope.ts +332 -0
  51. package/src/llm/provider.ts +391 -17
  52. package/src/runtime/agent.ts +58 -3
  53. package/src/runtime/event-loop.ts +233 -15
  54. package/src/runtime/types.ts +20 -1
  55. package/src/telemetry/events.ts +101 -0
  56. package/src/tools/edit.ts +108 -17
  57. package/test/bin-launch-id.test.ts +104 -0
  58. package/test/core-loop.test.ts +240 -0
  59. package/test/events.test.ts +33 -0
  60. package/test/flair-context.test.ts +102 -0
  61. package/test/governance.test.ts +103 -2
  62. package/test/io.test.ts +13 -14
  63. package/test/mail-promote-guard.test.ts +325 -0
  64. package/test/provider.test.ts +43 -0
@@ -0,0 +1,37 @@
1
+ import { appendFileSync, mkdirSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ function dayStamp(ts) {
4
+ return ts.slice(0, 10);
5
+ }
6
+ export function sanitizeError(err) {
7
+ const raw = String(err?.message ?? err ?? "unknown_error");
8
+ return raw
9
+ .replace(/(sk-[a-zA-Z0-9_-]+)/g, "[REDACTED_KEY]")
10
+ .replace(/AIza[0-9A-Za-z\-_]{35}/g, "[REDACTED_KEY]")
11
+ .replace(/(api[_-]?key\s*[:=]\s*)[^\s,;]+/gi, "$1[REDACTED]")
12
+ .slice(0, 300);
13
+ }
14
+ export class EventLogger {
15
+ agentId;
16
+ baseDir;
17
+ constructor(agentId, baseDir) {
18
+ this.agentId = agentId;
19
+ this.baseDir = baseDir;
20
+ mkdirSync(this.baseDir, { recursive: true, mode: 0o700 });
21
+ }
22
+ pathFor(ts) {
23
+ return join(this.baseDir, `events-${dayStamp(ts)}.jsonl`);
24
+ }
25
+ emit(event) {
26
+ const ts = event.ts || new Date().toISOString();
27
+ const out = {
28
+ ...event,
29
+ agent: event.agent || this.agentId,
30
+ ts,
31
+ };
32
+ const path = this.pathFor(ts);
33
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
34
+ appendFileSync(path, `${JSON.stringify(out)}\n`, { mode: 0o600, encoding: "utf-8" });
35
+ }
36
+ }
37
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/telemetry/events.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AA8D1C,SAAS,QAAQ,CAAC,EAAU;IAC1B,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AACzB,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,GAAY;IACxC,MAAM,GAAG,GAAG,MAAM,CAAE,GAAW,EAAE,OAAO,IAAI,GAAG,IAAI,eAAe,CAAC,CAAC;IACpE,OAAO,GAAG;SACP,OAAO,CAAC,sBAAsB,EAAE,gBAAgB,CAAC;SACjD,OAAO,CAAC,yBAAyB,EAAE,gBAAgB,CAAC;SACpD,OAAO,CAAC,mCAAmC,EAAE,cAAc,CAAC;SAC5D,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;AACnB,CAAC;AAED,MAAM,OAAO,WAAW;IAEH;IACA;IAFnB,YACmB,OAAe,EACf,OAAe;QADf,YAAO,GAAP,OAAO,CAAQ;QACf,YAAO,GAAP,OAAO,CAAQ;QAEhC,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IAC5D,CAAC;IAEO,OAAO,CAAC,EAAU;QACxB,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC;IAC5D,CAAC;IAED,IAAI,CAAC,KAAU;QACb,MAAM,EAAE,GAAG,KAAK,CAAC,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QAChD,MAAM,GAAG,GAAG;YACV,GAAI,KAAwB;YAC5B,KAAK,EAAE,KAAK,CAAC,KAAK,IAAI,IAAI,CAAC,OAAO;YAClC,EAAE;SACH,CAAC;QAEF,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;QAC9B,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QAC3D,cAAc,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;IACvF,CAAC;CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAS1C,wBAAgB,YAAY,CAAC,QAAQ,EAAE,eAAe,GAAG,IAAI,CA+C5D"}
1
+ {"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAgE1C,wBAAgB,YAAY,CAAC,QAAQ,EAAE,eAAe,GAAG,IAAI,CAmF5D"}
@@ -1,44 +1,122 @@
1
1
  import { readFileSync, writeFileSync, existsSync } from "node:fs";
2
2
  import { BoundaryManager } from "../governance/boundary.js";
3
+ /**
4
+ * Normalize whitespace for fuzzy matching:
5
+ * Collapse runs of spaces/tabs (but not newlines) to a single space,
6
+ * and strip leading/trailing whitespace from each line.
7
+ * This handles the common case where the LLM's indentation differs
8
+ * slightly from the file's actual indentation.
9
+ */
10
+ function normalizeIndent(s) {
11
+ return s
12
+ .split("\n")
13
+ .map((l) => l.replace(/^[ \t]+/, "").replace(/[ \t]+$/, ""))
14
+ .join("\n");
15
+ }
16
+ /**
17
+ * Find `needle` in `haystack`, falling back to indent-normalized matching.
18
+ * Returns { index, matchedText } where matchedText is the actual substring
19
+ * in haystack that corresponds to needle (needed for correct replacement).
20
+ * Returns null if not found.
21
+ */
22
+ function findOccurrence(haystack, needle) {
23
+ // Exact match β€” fast path
24
+ const exact = haystack.indexOf(needle);
25
+ if (exact !== -1)
26
+ return { index: exact, matchedText: needle };
27
+ // Fuzzy: normalize indentation on both sides
28
+ const normHaystack = normalizeIndent(haystack);
29
+ const normNeedle = normalizeIndent(needle);
30
+ const normIdx = normHaystack.indexOf(normNeedle);
31
+ if (normIdx === -1)
32
+ return null;
33
+ // Map the normalized index back to an original-string line number
34
+ const normLines = normHaystack.slice(0, normIdx).split("\n").length - 1;
35
+ const needleLineCount = needle.split("\n").length;
36
+ const origLines = haystack.split("\n");
37
+ // Reconstruct the actual text block from the original lines
38
+ const origBlock = origLines
39
+ .slice(normLines, normLines + needleLineCount)
40
+ .join("\n");
41
+ // Find (and verify) the block in the original haystack
42
+ let charOffset = 0;
43
+ for (let i = 0; i < normLines && i < origLines.length; i++) {
44
+ charOffset += origLines[i].length + 1; // +1 for \n
45
+ }
46
+ const blockIdx = haystack.indexOf(origBlock, Math.max(0, charOffset - 50));
47
+ if (blockIdx === -1)
48
+ return null;
49
+ return { index: blockIdx, matchedText: origBlock };
50
+ }
3
51
  export function makeEditTool(boundary) {
4
52
  return {
5
53
  name: "edit",
6
- description: "Search-and-replace in one file. Replaces exactly one occurrence.\nInput: {\"path\": string, \"old_string\": string, \"new_string\": string}",
54
+ description: "Search-and-replace in one file. Replaces exactly one occurrence. Prefer narrow, unique context in old_string. Use the write tool to rewrite entire files.",
7
55
  input_schema: {
8
- path: { type: "string", description: "Path in workspace" },
9
- old_string: { type: "string", description: "Text to replace" },
10
- new_string: { type: "string", description: "Replacement text" },
56
+ path: { type: "string", description: "Relative path within workspace" },
57
+ old_string: {
58
+ type: "string",
59
+ description: "Exact text to find and replace. Must be unique in the file. Include surrounding lines for context if needed.",
60
+ },
61
+ new_string: {
62
+ type: "string",
63
+ description: "Replacement text",
64
+ },
11
65
  },
12
66
  async execute(args) {
13
67
  const payload = args;
14
68
  if (typeof payload.path !== "string" ||
15
69
  typeof payload.old_string !== "string" ||
16
70
  typeof payload.new_string !== "string") {
17
- return { content: "edit tool requires path, old_string, new_string", isError: true };
71
+ return {
72
+ content: "edit tool requires path, old_string, new_string",
73
+ isError: true,
74
+ };
18
75
  }
19
76
  const workspacePath = boundary.resolveWorkspacePath(payload.path);
20
- if (!existsSync(workspacePath) || !BoundaryManager.canFollowSymlink(workspacePath)) {
77
+ if (!existsSync(workspacePath) ||
78
+ !BoundaryManager.canFollowSymlink(workspacePath)) {
21
79
  if (existsSync(workspacePath)) {
22
- return { content: `Refusing to follow symlink: ${payload.path}`, isError: true };
80
+ return {
81
+ content: `Refusing to follow symlink: ${payload.path}`,
82
+ isError: true,
83
+ };
23
84
  }
24
- return { content: `edit failed: file not found ${payload.path}`, isError: true };
85
+ return {
86
+ content: `edit failed: file not found ${payload.path}`,
87
+ isError: true,
88
+ };
25
89
  }
26
90
  try {
27
91
  const current = readFileSync(workspacePath, "utf-8");
28
- const first = current.indexOf(payload.old_string);
29
- const last = current.lastIndexOf(payload.old_string);
30
- if (first === -1) {
31
- return { content: `No occurrence of old_string found in ${payload.path}`, isError: true };
92
+ const match = findOccurrence(current, payload.old_string);
93
+ if (match === null) {
94
+ return {
95
+ content: `No occurrence of old_string found in ${payload.path}. Tip: use the read tool to verify exact text, or use the write tool to rewrite the full file.`,
96
+ isError: true,
97
+ };
32
98
  }
33
- if (first !== last) {
34
- return { content: `old_string matches multiple locations in ${payload.path} β€” provide narrower context`, isError: true };
99
+ const { index: first, matchedText } = match;
100
+ // Check for multiple occurrences (exact only, to keep fuzzy safe)
101
+ const exactOccurrences = current.split(payload.old_string).length - 1;
102
+ const normOccurrences = normalizeIndent(current).split(normalizeIndent(payload.old_string)).length - 1;
103
+ if (exactOccurrences > 1 || normOccurrences > 1) {
104
+ return {
105
+ content: `old_string matches multiple locations in ${payload.path} β€” provide narrower context`,
106
+ isError: true,
107
+ };
35
108
  }
36
- const next = current.replace(payload.old_string, payload.new_string);
109
+ const next = current.slice(0, first) +
110
+ payload.new_string +
111
+ current.slice(first + matchedText.length);
37
112
  writeFileSync(workspacePath, next, "utf-8");
38
113
  return { content: `Edited ${payload.path}`, isError: false };
39
114
  }
40
115
  catch (err) {
41
- return { content: `edit failed: ${err?.message ?? String(err)}`, isError: true };
116
+ return {
117
+ content: `edit failed: ${err?.message ?? String(err)}`,
118
+ isError: true,
119
+ };
42
120
  }
43
121
  },
44
122
  };
@@ -1 +1 @@
1
- {"version":3,"file":"edit.js","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAU5D,MAAM,UAAU,YAAY,CAAC,QAAyB;IACpD,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,WAAW,EAAE,6IAA6I;QAC1J,YAAY,EAAE;YACZ,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,mBAAmB,EAAE;YAC1D,UAAU,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,iBAAiB,EAAE;YAC9D,UAAU,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,W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AAC;gBAClB,OAAO;oBACL,OAAO,EAAE,gBAAgB,GAAG,EAAE,OAAO,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE;oBACtD,OAAO,EAAE,IAAI;iBACd,CAAC;YACJ,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tpsdev-ai/agent",
3
- "version": "0.5.4",
3
+ "version": "0.7.0",
4
4
  "description": "Native TPS Agent Runtime β€” headless, mail-driven, nono-sandboxed",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -32,9 +32,17 @@
32
32
  "mail-driven"
33
33
  ],
34
34
  "license": "Apache-2.0",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/tpsdev-ai/cli.git",
38
+ "directory": "packages/agent"
39
+ },
40
+ "homepage": "https://github.com/tpsdev-ai/cli/tree/main/packages/agent#readme",
35
41
  "dependencies": {
36
- "js-yaml": "^4.1.0",
42
+ "@noble/ed25519": "^3.0.0",
43
+ "canonicalize": "^3.0.0",
37
44
  "js-tiktoken": "^1.0.13",
45
+ "js-yaml": "^4.3.2",
38
46
  "zod": "^3.24.0"
39
47
  },
40
48
  "devDependencies": {
package/src/bin.ts CHANGED
@@ -2,11 +2,17 @@
2
2
  import { AgentRuntime } from "./runtime/agent.js";
3
3
  import { loadAgentConfig } from "./config.js";
4
4
 
5
+ /** cli#352 r β€” the launch-id charset/traversal rule, same shape as cli#351 r5's. */
6
+ const LAUNCH_ID_RE = /^[a-zA-Z0-9._-]{1,64}$/;
7
+
5
8
  function usage(): never {
6
9
  console.error("Usage:");
7
10
  console.error(" tps-agent run --config <agent.yaml> --message <text>");
8
11
  console.error(" tps-agent start --config <agent.yaml>");
9
12
  console.error(" tps-agent health --config <agent.yaml>");
13
+ console.error(" tps-agent check --id <roster-id> --config <agent.yaml>");
14
+ console.error("Options:");
15
+ console.error(" --id <roster-id> launch id from the supervisor's roster entry (cli#352 r)");
10
16
  process.exit(1);
11
17
  }
12
18
 
@@ -16,19 +22,66 @@ function parseArg(name: string, args: string[]): string | undefined {
16
22
  return undefined;
17
23
  }
18
24
 
19
- function parseConfig(args: string[]): { configPath?: string; command?: string } {
25
+ function parseConfig(args: string[]): { configPath?: string; command?: string; launchId?: string } {
20
26
  const command = args[0];
21
27
  const configPath = parseArg("--config", args);
22
- return { command, configPath };
28
+ const launchId = parseArg("--id", args);
29
+ return { command, configPath, launchId };
30
+ }
31
+
32
+ /**
33
+ * cli#352 r β€” the supervisor's launch path (`nono run … -- tps-agent start`)
34
+ * bypassed the validated-id rule cli#351 r5 put on the CLI path: the agent's
35
+ * writable config could name ANY id, and the runtime would derive its identity
36
+ * key from it. The launch id must come from the supervisor's own roster entry.
37
+ * Mirrors tps agent start's rule exactly: charset + no traversal, and the
38
+ * config must agree (a config that disagrees is tampered or misbuilt).
39
+ */
40
+ function validateLaunchId(id: string, source: string): void {
41
+ if (!LAUNCH_ID_RE.test(id) || id.includes("..")) {
42
+ console.error(
43
+ `Invalid agent id (${source}): ${id} β€” must match ^[a-zA-Z0-9._-]{1,64}$ and contain no traversal`,
44
+ );
45
+ process.exit(1);
46
+ }
47
+ }
48
+
49
+ function assertConfigAgrees(launchId: string, configAgentId: string): void {
50
+ if (configAgentId !== launchId) {
51
+ console.error(
52
+ `❌ agent.yaml agentId '${configAgentId}' does not match the launch id '${launchId}' β€” refusing to launch (cli#352 r)`,
53
+ );
54
+ process.exit(1);
55
+ }
23
56
  }
24
57
 
25
58
  async function main() {
26
59
  const args = process.argv.slice(2);
27
- const { command, configPath } = parseConfig(args);
60
+ const { command, configPath, launchId } = parseConfig(args);
28
61
  if (!command || command === "--help" || command === "-h") usage();
29
62
  if (!configPath) usage();
63
+ if (command === "check" && !launchId) usage();
64
+
65
+ if (launchId !== undefined) validateLaunchId(launchId, "--id");
30
66
 
31
67
  const config = loadAgentConfig(configPath);
68
+
69
+ // cli#352 r β€” `check` is the supervisor's pre-flight: refuse BEFORE anything
70
+ // is launched, so a refusal cannot leave a partial team running. It is the
71
+ // same rule the launch itself applies below, so the two cannot disagree.
72
+ if (command === "check") {
73
+ if (!launchId) usage();
74
+ assertConfigAgrees(launchId, config.agentId);
75
+ return;
76
+ }
77
+
78
+ if (launchId !== undefined) {
79
+ // The runtime derives its identity key from config.agentId; agreeing with
80
+ // the roster id is what makes that derivation safe (cli#352 r).
81
+ assertConfigAgrees(launchId, config.agentId);
82
+ config.agentId = launchId;
83
+ }
84
+
32
85
  const runtime = new AgentRuntime(config);
33
86
 
34
87
  switch (command) {
package/src/config.ts CHANGED
@@ -11,8 +11,9 @@ export interface AgentRuntimeConfig {
11
11
  workspace: string;
12
12
  systemPrompt?: string;
13
13
  llm: {
14
- provider: "anthropic" | "google" | "openai" | "ollama";
14
+ provider: "anthropic" | "claude-oauth" | "google" | "openai" | "ollama";
15
15
  model: string;
16
+ auth?: "oauth" | "api-key";
16
17
  apiKey?: string;
17
18
  baseUrl?: string;
18
19
  };
@@ -71,11 +72,19 @@ export function loadAgentConfig(path: string): AgentConfig {
71
72
  maxTokens: parsed.maxTokens ? Number(parsed.maxTokens) : 1024,
72
73
  tools: parsed.tools ?? ["read", "write", "edit", "exec", "mail"],
73
74
  execAllowlist: parsed.execAllowlist,
75
+ flair: parsed.flair ? {
76
+ url: parsed.flair.url ? String(parsed.flair.url) : undefined,
77
+ keyPath: parsed.flair.keyPath ? String(parsed.flair.keyPath) : undefined,
78
+ } : undefined,
79
+ role: parsed.role ? String(parsed.role) as any : undefined,
80
+ roleConfig: parsed.roleConfig ? parsed.roleConfig as Record<string, unknown> : undefined,
74
81
  llm: {
75
82
  provider: parsed.llm?.provider || parsed.provider || "openai",
76
83
  model: parsed.llm?.model || parsed.model || "gpt-4o-mini",
84
+ auth: parsed.llm?.auth || parsed.auth || "api-key",
77
85
  apiKey: parsed.llm?.apiKey || parsed.apiKey,
78
86
  baseUrl: parsed.llm?.baseUrl || parsed.baseUrl,
87
+ proxyUrl: parsed.llm?.proxyUrl || parsed.llm?.baseUrl || parsed.baseUrl,
79
88
  },
80
89
  };
81
90
 
package/src/index.ts CHANGED
@@ -36,3 +36,11 @@ export { ReviewGate } from "./governance/review-gate.js";
36
36
 
37
37
  // Config
38
38
  export { loadAgentConfig } from "./config.js";
39
+
40
+ // Flair integration
41
+ export { FlairContextProvider } from "./io/flair.js";
42
+ export type { FlairConfig } from "./runtime/types.js";
43
+
44
+ // Signing
45
+ export { signEnvelope, verifyEnvelope } from "./lib/signEnvelope.js";
46
+ export type { Envelope, ChainEntry, FlairClient, VerifyOk, VerifyReject } from "./lib/signEnvelope.js";
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Flair context provider for the agent package.
3
+ *
4
+ * Provides Flair-backed system prompt bootstrapping and memory writes.
5
+ * Uses the same TPS-Ed25519 signing scheme as the CLI FlairClient.
6
+ */
7
+
8
+ import crypto from "node:crypto";
9
+ import { readFileSync, existsSync } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { join } from "node:path";
12
+ import type { FlairConfig } from "../runtime/types.js";
13
+
14
+ export interface FlairAgent {
15
+ id: string;
16
+ name: string;
17
+ publicKey: string;
18
+ }
19
+
20
+ export interface FlairMemory {
21
+ id: string;
22
+ agentId: string;
23
+ content: string;
24
+ type?: string;
25
+ score?: number;
26
+ }
27
+
28
+ export interface FlairSoulEntry {
29
+ key: string;
30
+ value: string;
31
+ }
32
+
33
+ export class FlairContextProvider {
34
+ private readonly url: string;
35
+ private readonly agentId: string;
36
+ private readonly keyPath: string;
37
+
38
+ constructor(agentId: string, config: FlairConfig = {}) {
39
+ this.url = (config.url ?? process.env.FLAIR_URL ?? "http://127.0.0.1:9926").replace(/\/$/, "");
40
+ this.agentId = agentId;
41
+ this.keyPath =
42
+ config.keyPath ??
43
+ join(homedir(), ".tps", "identity", `${agentId}.key`);
44
+ }
45
+
46
+ // ─── Auth ──────────────────────────────────────────────────────────────────
47
+
48
+ private sign(method: string, path: string): string {
49
+ const ts = Date.now().toString();
50
+ const nonce = crypto.randomUUID();
51
+ const payload = `${this.agentId}:${ts}:${nonce}:${method}:${path}`;
52
+
53
+ if (!existsSync(this.keyPath)) {
54
+ throw new Error(`Flair key not found at ${this.keyPath}. Run: tps agent create --id ${this.agentId}`);
55
+ }
56
+
57
+ const raw = readFileSync(this.keyPath, "utf-8").trim();
58
+ let key;
59
+ if (raw.startsWith("-----")) {
60
+ key = crypto.createPrivateKey(raw);
61
+ } else {
62
+ key = crypto.createPrivateKey({ key: Buffer.from(raw, "base64"), format: "der", type: "pkcs8" });
63
+ }
64
+ const sig = crypto.sign(null, Buffer.from(payload), key);
65
+ return `TPS-Ed25519 ${this.agentId}:${ts}:${nonce}:${sig.toString("base64")}`;
66
+ }
67
+
68
+ private async req<T>(method: string, path: string, body?: unknown): Promise<T> {
69
+ const res = await fetch(`${this.url}${path}`, {
70
+ method,
71
+ headers: {
72
+ "Content-Type": "application/json",
73
+ Authorization: this.sign(method, path),
74
+ },
75
+ body: body !== undefined ? JSON.stringify(body) : undefined,
76
+ });
77
+ if (!res.ok) {
78
+ const txt = await res.text().catch(() => "");
79
+ throw new Error(`Flair ${method} ${path} β†’ ${res.status}: ${txt}`);
80
+ }
81
+ if (res.status === 204) return undefined as T;
82
+ return res.json() as Promise<T>;
83
+ }
84
+
85
+ // ─── Public API ────────────────────────────────────────────────────────────
86
+
87
+ async ping(): Promise<boolean> {
88
+ try {
89
+ const res = await fetch(`${this.url}/Health`, { signal: AbortSignal.timeout(3000) });
90
+ return res.ok;
91
+ } catch {
92
+ return false;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Resolve an agent from Flair.
98
+ *
99
+ * Distinguishes "Flair says this principal does not exist" (return null) from
100
+ * "Flair could not be reached" (THROW). The signature verifier built on this
101
+ * would otherwise see null for BOTH and dead-letter every message as a
102
+ * terminal "principal not found" for the duration of a Flair outage. The
103
+ * shared mail-verify client applies the same null→ping→throw rule; the two
104
+ * must not diverge.
105
+ */
106
+ async getAgent(name: string): Promise<FlairAgent | null> {
107
+ try {
108
+ return await this.req<FlairAgent>("GET", `/Agent/${name}`);
109
+ } catch {
110
+ // Either the agent is absent (a reachable 404) or Flair is unreachable.
111
+ if (!(await this.ping())) {
112
+ throw new Error(`Flair unreachable at ${this.url} while resolving agent "${name}"`);
113
+ }
114
+ return null;
115
+ }
116
+ }
117
+
118
+ async getSoul(): Promise<FlairSoulEntry[]> {
119
+ const entries = await this.req<Array<{ key: string; value: string }>>(
120
+ "GET",
121
+ `/Soul?agentId=${encodeURIComponent(this.agentId)}`,
122
+ );
123
+ return entries;
124
+ }
125
+
126
+ async searchMemories(query: string, limit = 5): Promise<FlairMemory[]> {
127
+ return this.req<FlairMemory[]>(
128
+ "GET",
129
+ `/MemorySearch?agentId=${encodeURIComponent(this.agentId)}&q=${encodeURIComponent(query)}&limit=${limit}`,
130
+ );
131
+ }
132
+
133
+ async listRecentMemories(days = 3): Promise<FlairMemory[]> {
134
+ return this.req<FlairMemory[]>(
135
+ "GET",
136
+ `/Memory?agentId=${encodeURIComponent(this.agentId)}&limit=${days * 3}`,
137
+ );
138
+ }
139
+
140
+ async writeMemory(id: string, content: string, type = "conversation"): Promise<void> {
141
+ const existing = await this.req("GET", `/Memory/${id}`).catch(() => null);
142
+ const payload = {
143
+ id,
144
+ agentId: this.agentId,
145
+ content,
146
+ type,
147
+ durability: "standard",
148
+ updatedAt: new Date().toISOString(),
149
+ };
150
+ if (existing) {
151
+ await this.req("PUT", `/Memory/${id}`, payload);
152
+ } else {
153
+ await this.req("POST", "/Memory", { ...payload, createdAt: new Date().toISOString() });
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Build a system prompt supplement from Flair β€” soul + recent context.
159
+ * Returns empty string if Flair is offline (graceful degradation).
160
+ */
161
+ async buildContextBlock(query?: string): Promise<string> {
162
+ if (!(await this.ping())) return "";
163
+
164
+ const parts: string[] = [];
165
+
166
+ // Soul entries β†’ identity block
167
+ try {
168
+ const soul = await this.getSoul();
169
+ if (soul.length > 0) {
170
+ parts.push("## Agent Identity (from Flair)");
171
+ for (const entry of soul) {
172
+ parts.push(`${entry.key}: ${entry.value}`);
173
+ }
174
+ }
175
+ } catch {
176
+ // non-fatal
177
+ }
178
+
179
+ // Semantic search if query provided
180
+ if (query) {
181
+ try {
182
+ const results = await this.searchMemories(query, 5);
183
+ if (results.length > 0) {
184
+ parts.push("\n## Relevant Memory");
185
+ for (const r of results) {
186
+ const score = r.score ? ` [${r.score.toFixed(3)}]` : "";
187
+ parts.push(`${score} ${r.id}: ${r.content.slice(0, 500)}`);
188
+ }
189
+ }
190
+ } catch {
191
+ // non-fatal
192
+ }
193
+ }
194
+
195
+ return parts.join("\n");
196
+ }
197
+ }