@tpsdev-ai/agent 0.8.0 → 0.9.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 (133) hide show
  1. package/bun.lock +27 -15
  2. package/dist/bin.js +4 -3
  3. package/dist/bin.js.map +1 -1
  4. package/dist/config.d.ts +8 -1
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/config.js +38 -3
  7. package/dist/config.js.map +1 -1
  8. package/dist/home.d.ts +3 -0
  9. package/dist/home.d.ts.map +1 -0
  10. package/dist/home.js +18 -0
  11. package/dist/home.js.map +1 -0
  12. package/dist/index.d.ts +16 -3
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +12 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/io/flair.d.ts +1 -10
  17. package/dist/io/flair.d.ts.map +1 -1
  18. package/dist/io/flair.js +29 -28
  19. package/dist/io/flair.js.map +1 -1
  20. package/dist/io/mail.d.ts +184 -30
  21. package/dist/io/mail.d.ts.map +1 -1
  22. package/dist/io/mail.js +944 -185
  23. package/dist/io/mail.js.map +1 -1
  24. package/dist/lib/agent-keys.d.ts +106 -0
  25. package/dist/lib/agent-keys.d.ts.map +1 -0
  26. package/dist/lib/agent-keys.js +298 -0
  27. package/dist/lib/agent-keys.js.map +1 -0
  28. package/dist/lib/bridge-identity.d.ts +10 -0
  29. package/dist/lib/bridge-identity.d.ts.map +1 -0
  30. package/dist/lib/bridge-identity.js +56 -0
  31. package/dist/lib/bridge-identity.js.map +1 -0
  32. package/dist/lib/mail-lock-namespace.d.ts +19 -0
  33. package/dist/lib/mail-lock-namespace.d.ts.map +1 -0
  34. package/dist/lib/mail-lock-namespace.js +58 -0
  35. package/dist/lib/mail-lock-namespace.js.map +1 -0
  36. package/dist/lib/mail-lock.d.ts +81 -0
  37. package/dist/lib/mail-lock.d.ts.map +1 -0
  38. package/dist/lib/mail-lock.js +319 -0
  39. package/dist/lib/mail-lock.js.map +1 -0
  40. package/dist/lib/mailbox-filename.d.ts +2 -0
  41. package/dist/lib/mailbox-filename.d.ts.map +1 -0
  42. package/dist/lib/mailbox-filename.js +4 -0
  43. package/dist/lib/mailbox-filename.js.map +1 -0
  44. package/dist/lib/mailbox-policy.d.ts +245 -0
  45. package/dist/lib/mailbox-policy.d.ts.map +1 -0
  46. package/dist/lib/mailbox-policy.js +949 -0
  47. package/dist/lib/mailbox-policy.js.map +1 -0
  48. package/dist/lib/public-key.d.ts +6 -0
  49. package/dist/lib/public-key.d.ts.map +1 -0
  50. package/dist/lib/public-key.js +45 -0
  51. package/dist/lib/public-key.js.map +1 -0
  52. package/dist/lib/registry-key.d.ts +2 -0
  53. package/dist/lib/registry-key.d.ts.map +1 -0
  54. package/dist/lib/registry-key.js +10 -0
  55. package/dist/lib/registry-key.js.map +1 -0
  56. package/dist/lib/relay-lock.d.ts +7 -0
  57. package/dist/lib/relay-lock.d.ts.map +1 -0
  58. package/dist/lib/relay-lock.js +19 -0
  59. package/dist/lib/relay-lock.js.map +1 -0
  60. package/dist/lib/signEnvelope.d.ts +2 -0
  61. package/dist/lib/signEnvelope.d.ts.map +1 -1
  62. package/dist/lib/signEnvelope.js.map +1 -1
  63. package/dist/lib/signing-key.d.ts +2 -0
  64. package/dist/lib/signing-key.d.ts.map +1 -0
  65. package/dist/lib/signing-key.js +9 -0
  66. package/dist/lib/signing-key.js.map +1 -0
  67. package/dist/lib/topic-recipient.d.ts +2 -0
  68. package/dist/lib/topic-recipient.d.ts.map +1 -0
  69. package/dist/lib/topic-recipient.js +2 -0
  70. package/dist/lib/topic-recipient.js.map +1 -0
  71. package/dist/llm/provider.d.ts.map +1 -1
  72. package/dist/llm/provider.js +9 -7
  73. package/dist/llm/provider.js.map +1 -1
  74. package/dist/runtime/agent.d.ts.map +1 -1
  75. package/dist/runtime/agent.js +32 -25
  76. package/dist/runtime/agent.js.map +1 -1
  77. package/dist/runtime/event-loop.d.ts +21 -2
  78. package/dist/runtime/event-loop.d.ts.map +1 -1
  79. package/dist/runtime/event-loop.js +199 -54
  80. package/dist/runtime/event-loop.js.map +1 -1
  81. package/dist/runtime/types.d.ts +11 -0
  82. package/dist/runtime/types.d.ts.map +1 -1
  83. package/dist/runtime/types.js +13 -1
  84. package/dist/runtime/types.js.map +1 -1
  85. package/package.json +2 -3
  86. package/src/bin.ts +4 -3
  87. package/src/config.ts +46 -3
  88. package/src/home.ts +18 -0
  89. package/src/index.ts +33 -2
  90. package/src/io/flair.ts +23 -28
  91. package/src/io/mail.ts +1007 -200
  92. package/src/lib/agent-keys.ts +308 -0
  93. package/src/lib/bridge-identity.ts +49 -0
  94. package/src/lib/mail-lock-namespace.ts +64 -0
  95. package/src/lib/mail-lock.ts +337 -0
  96. package/src/lib/mailbox-filename.ts +3 -0
  97. package/src/lib/mailbox-policy.ts +1085 -0
  98. package/src/lib/public-key.ts +49 -0
  99. package/src/lib/registry-key.ts +8 -0
  100. package/src/lib/relay-lock.ts +20 -0
  101. package/src/lib/signEnvelope.ts +2 -0
  102. package/src/lib/signing-key.ts +8 -0
  103. package/src/lib/topic-recipient.ts +1 -0
  104. package/src/llm/provider.ts +9 -7
  105. package/src/runtime/agent.ts +30 -27
  106. package/src/runtime/event-loop.ts +221 -68
  107. package/src/runtime/types.ts +14 -0
  108. package/test/config.test.ts +85 -2
  109. package/test/core-loop.test.ts +6 -4
  110. package/test/governance.test.ts +4 -1
  111. package/test/helpers/event-loop-child.mjs +50 -0
  112. package/test/helpers/mail-delivery-worker.mjs +16 -0
  113. package/test/helpers/mail-kill-child.mjs +104 -0
  114. package/test/helpers/signed-relay-record.ts +31 -0
  115. package/test/home-per-call.test.ts +72 -0
  116. package/test/io.test.ts +81 -14
  117. package/test/mail-client-lock-namespace.test.ts +155 -0
  118. package/test/mail-client-repoint-root.test.ts +368 -0
  119. package/test/mail-delivery-at-least-once.test.ts +1238 -0
  120. package/test/mail-event-loop-delivery.test.ts +769 -0
  121. package/test/mail-intent-phases.test.ts +304 -0
  122. package/test/mail-interrupted-recovery.test.ts +393 -0
  123. package/test/mail-lock-pid-state.test.ts +238 -0
  124. package/test/mail-lock.test.ts +96 -0
  125. package/test/mail-partial-flair.test.ts +102 -0
  126. package/test/mail-placement-replay.test.ts +116 -0
  127. package/test/mail-promote-guard.test.ts +305 -21
  128. package/test/mail-relay-reservation.test.ts +60 -0
  129. package/test/mailbox-filename.test.ts +16 -0
  130. package/test/public-key.test.ts +108 -0
  131. package/test/runtime-key-encoding.test.ts +105 -0
  132. package/test/runtime-pending-key.test.ts +117 -0
  133. package/test/security/mail-trust.test.ts +406 -109
@@ -1,6 +1,6 @@
1
1
  import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2
- import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
- import { join } from "node:path";
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { isAbsolute, join } from "node:path";
4
4
  import { tmpdir } from "node:os";
5
5
  import { loadAgentConfig } from "../src/config.js";
6
6
 
@@ -64,4 +64,87 @@ describe("agent config env interpolation", () => {
64
64
 
65
65
  expect(() => loadAgentConfig(cfg)).toThrow("Missing environment variable: MISSING_API_KEY");
66
66
  });
67
+
68
+ test("resolves a relative workspace against the config directory", () => {
69
+ const configDir = join(dir, "config");
70
+ mkdirSync(configDir);
71
+ const cfg = join(configDir, "agent.yaml");
72
+ writeFileSync(cfg, "agentId: probe\nworkspace: worktree\n", "utf-8");
73
+
74
+ const parsed = loadAgentConfig(cfg);
75
+ const workspace = join(configDir, "worktree");
76
+ expect(parsed.workspace).toBe(workspace);
77
+ expect(isAbsolute(parsed.workspace)).toBe(true);
78
+ expect(parsed.mailDir).toBe(join(workspace, "mail"));
79
+ expect(parsed.memoryPath).toBe(join(workspace, ".openclaw", "agent.memory.jsonl"));
80
+ });
81
+
82
+ test("normalizes an absolute workspace before deriving the default paths", () => {
83
+ const cfg = join(dir, "agent.yaml");
84
+ writeFileSync(cfg, `agentId: probe\nworkspace: ${dir}/elsewhere/../other\n`, "utf-8");
85
+
86
+ const parsed = loadAgentConfig(cfg);
87
+ expect(parsed.workspace).toBe(join(dir, "other"));
88
+ expect(parsed.mailDir).toBe(join(dir, "other", "mail"));
89
+ expect(parsed.memoryPath).toBe(join(dir, "other", ".openclaw", "agent.memory.jsonl"));
90
+ });
91
+
92
+ test("refuses a workspace starting with ~", () => {
93
+ const cfg = join(dir, "agent.yaml");
94
+ writeFileSync(cfg, "agentId: probe\nworkspace: ~/work\n", "utf-8");
95
+
96
+ expect(() => loadAgentConfig(cfg)).toThrow(
97
+ "workspace '~/work' starts with '~', which is not expanded: use an absolute path or a path relative to the config file",
98
+ );
99
+ });
100
+
101
+ const nullRefusal = (key: string) =>
102
+ `${key} is set but has no value (in YAML, a bare ~ or nothing after '${key}:' is null): give an absolute path or a path relative to the config file, or remove the key`;
103
+ const emptyRefusal = (key: string) =>
104
+ `${key} is set to an empty or blank string: give an absolute path or a path relative to the config file, or remove the key`;
105
+ for (const [line, message] of [
106
+ ["workspace: ~", nullRefusal("workspace")],
107
+ ["workspace:", nullRefusal("workspace")],
108
+ ["workspace: null", nullRefusal("workspace")],
109
+ ["workspace: 42", "workspace must be a string path"],
110
+ ['workspace: ""', emptyRefusal("workspace")],
111
+ ['workspace: " "', emptyRefusal("workspace")],
112
+ ["repo: ~", nullRefusal("repo")],
113
+ ["repo: 42", "repo must be a string path"],
114
+ ['repo: ""', emptyRefusal("repo")],
115
+ [
116
+ "repo: ~/work",
117
+ "repo '~/work' starts with '~', which is not expanded: use an absolute path or a path relative to the config file",
118
+ ],
119
+ ] as const) {
120
+ test(`refuses ${JSON.stringify(line)}`, () => {
121
+ const cfg = join(dir, "agent.yaml");
122
+ writeFileSync(cfg, `agentId: probe\n${line}\n`, "utf-8");
123
+
124
+ expect(() => loadAgentConfig(cfg)).toThrow(message);
125
+ });
126
+ }
127
+
128
+ test("uses the current directory when the config has no workspace or repo key", () => {
129
+ const cfg = join(dir, "agent.yaml");
130
+ writeFileSync(cfg, "agentId: probe\n", "utf-8");
131
+
132
+ const parsed = loadAgentConfig(cfg);
133
+ expect(parsed.workspace).toBe(process.cwd());
134
+ expect(parsed.mailDir).toBe(`${process.cwd()}/mail`);
135
+ });
136
+
137
+ test("resolves a relative repo against the config directory when there is no workspace key", () => {
138
+ const cfg = join(dir, "agent.yaml");
139
+ writeFileSync(cfg, "agentId: probe\nrepo: worktree\n", "utf-8");
140
+
141
+ expect(loadAgentConfig(cfg).workspace).toBe(join(dir, "worktree"));
142
+ });
143
+
144
+ test("uses workspace over repo when both keys are set", () => {
145
+ const cfg = join(dir, "agent.yaml");
146
+ writeFileSync(cfg, "agentId: probe\nworkspace: chosen\nrepo: ignored\n", "utf-8");
147
+
148
+ expect(loadAgentConfig(cfg).workspace).toBe(join(dir, "chosen"));
149
+ });
67
150
  });
@@ -1,5 +1,6 @@
1
1
  import { describe, test, expect, mock } from "bun:test";
2
2
  import { EventLoop } from "../src/runtime/event-loop.js";
3
+ import { ToolRegistry } from "../src/tools/registry.js";
3
4
  import type {
4
5
  AgentConfig,
5
6
  CompletionRequest,
@@ -139,11 +140,12 @@ describe("ops-32: auto-compaction trigger", () => {
139
140
  { content: "Done.", toolCalls: undefined, inputTokens: 10, outputTokens: 5 },
140
141
  ];
141
142
  const { loop, calls, memory } = makeLoop(completions, { contextWindowTokens: 200 });
142
- (loop as any).deps.tools = {
143
- list: () => [],
144
- execute: mock(async () => ({ content: bigContent })),
145
- };
143
+ const tools = new ToolRegistry();
144
+ const execute = mock(async () => ({ content: bigContent }));
145
+ tools.register({ name: "read", description: "Read a file", input_schema: {}, execute });
146
+ (loop as any).deps.tools = tools;
146
147
  await (loop as any).processMessage("hello", "user");
148
+ expect(execute).toHaveBeenCalledTimes(1);
147
149
  expect(calls.length).toBeGreaterThanOrEqual(2);
148
150
  const memCalls: any[] = (memory.append as ReturnType<typeof mock>).mock.calls;
149
151
  const compactionEntry = memCalls.find((c: any) => c[0]?.type === "compaction");
@@ -46,7 +46,10 @@ describe("ReviewGate", () => {
46
46
 
47
47
  beforeEach(() => {
48
48
  tmpDir = mkdtempSync(join(tmpdir(), "tps-gate-test-"));
49
- mail = new MailClient(tmpDir, undefined, "testagent");
49
+ // sendMail signs as the agent; give it a raw 32-byte Ed25519 seed.
50
+ const keyPath = join(tmpDir, "testagent.key");
51
+ writeFileSync(keyPath, Buffer.alloc(32, 5));
52
+ mail = new MailClient(tmpDir, undefined, "testagent", { getAgent: async () => null }, keyPath);
50
53
  });
51
54
 
52
55
  afterEach(() => {
@@ -0,0 +1,50 @@
1
+ // event-loop-child.mjs — cli#617 slice (c) test helper.
2
+ //
3
+ // Runs EventLoop with MailClient; the provider marks handler entry and waits.
4
+ //
5
+ // argv: <mailDir> <agentId>
6
+ // env: TPS_FROM, TPS_SEED, TPS_MARKER, TPS_WORKSPACE
7
+ import { mkdirSync, writeFileSync } from "node:fs";
8
+ import * as ed from "@noble/ed25519";
9
+ import { MailClient } from "../../src/io/mail.js";
10
+ import { EventLoop } from "../../src/runtime/event-loop.js";
11
+
12
+ const [mailDir, agentId] = process.argv.slice(2);
13
+ const from = process.env.TPS_FROM;
14
+ const seed = Buffer.from(process.env.TPS_SEED, "base64");
15
+ const workspace = process.env.TPS_WORKSPACE;
16
+ mkdirSync(workspace, { recursive: true });
17
+
18
+ const client = new MailClient(mailDir, undefined, agentId, {
19
+ async getAgent(name) {
20
+ return name === from ? { publicKey: Buffer.from(ed.getPublicKey(seed)) } : null;
21
+ },
22
+ });
23
+
24
+ const provider = {
25
+ async complete() {
26
+ writeFileSync(process.env.TPS_MARKER, "in-handler");
27
+ await new Promise(() => {}); // spin until SIGKILL
28
+ },
29
+ };
30
+
31
+ const config = {
32
+ agentId,
33
+ name: "loop-child",
34
+ mailDir,
35
+ memoryPath: `${workspace}/mem.jsonl`,
36
+ workspace,
37
+ llm: { provider: "test", model: "test-model" },
38
+ contextWindowTokens: 8000,
39
+ maxToolTurns: 50,
40
+ };
41
+
42
+ const loop = new EventLoop({
43
+ config,
44
+ memory: { append: async () => {} },
45
+ context: {},
46
+ provider,
47
+ tools: { list: () => [], execute: async () => ({ content: "ok" }) },
48
+ });
49
+
50
+ await loop.runDeliveries(client);
@@ -0,0 +1,16 @@
1
+ import { parentPort, workerData } from "node:worker_threads";
2
+ import * as ed from "@noble/ed25519";
3
+
4
+ const { MailClient } = await import(workerData.module);
5
+ const client = new MailClient(workerData.mailDir, undefined, workerData.agent, {
6
+ async getAgent(name) {
7
+ return name === workerData.from
8
+ ? { publicKey: Buffer.from(ed.getPublicKey(Buffer.from(workerData.seed, "base64"))) }
9
+ : null;
10
+ },
11
+ });
12
+ const result = await client.deliverNext();
13
+ parentPort.once("message", async () => {
14
+ parentPort.postMessage(result.status === "delivered" ? await client.completeDelivery(result.delivery) : result);
15
+ });
16
+ parentPort.postMessage(result);
@@ -0,0 +1,104 @@
1
+ // mail-kill-child.mjs — test helper for cli#600.
2
+ //
3
+ // Runs a REAL MailClient in a child process that a test can
4
+ // SIGKILL at an injected pause point at a named filesystem operation, so an
5
+ // interrupted first delivery is simulated with a KILLED process (never an
6
+ // injected error).
7
+ //
8
+ // The pause point is injected by wrapping node:fs BEFORE the mail module is
9
+ // loaded, so the mail module's `import { … } from "node:fs"` bindings resolve to
10
+ // the wrappers.
11
+ //
12
+ // argv: <mailDir> <agentId>
13
+ // env: TPS_MAIL_MODULE file:// URL of the mail module
14
+ // TPS_DRIVE "checkNewMail" (default) or "deliverNext"
15
+ // TPS_KILL_AT symbolic step boundary (see BOUNDARIES below), or
16
+ // "after-delivery": no filesystem boundary; with
17
+ // TPS_DRIVE=deliverNext the child blocks, ALIVE, after
18
+ // deliverNext() hands a message over and before it is
19
+ // completed or released (a held local token)
20
+ // TPS_KILL_AFTER "1" pauses AFTER the matched op completes
21
+ // TPS_KILL_MARKER marker file written just before blocking
22
+ // TPS_MAIL_ROOT the mailbox root (<mailDir>/<agentId>)
23
+ // TPS_SRC, TPS_CUR the new/<file> source and its cur/<file> sibling
24
+ // TPS_FROM the sender id the verifier resolves
25
+ // TPS_SEED base64 Ed25519 seed for the sender
26
+ import { createRequire } from "node:module";
27
+ import { basename, join } from "node:path";
28
+
29
+ const require = createRequire(import.meta.url);
30
+ const fs = require("node:fs");
31
+ const origWrite = fs.writeFileSync;
32
+
33
+ const KILL_AT = process.env.TPS_KILL_AT ?? "";
34
+ const KILL_AFTER = process.env.TPS_KILL_AFTER === "1";
35
+ const MARKER = process.env.TPS_KILL_MARKER;
36
+ const ROOT = process.env.TPS_MAIL_ROOT ?? "";
37
+ const SRC = process.env.TPS_SRC ?? "";
38
+ const CUR = process.env.TPS_CUR ?? "";
39
+ const LEDGER = join(ROOT, "consumed.jsonl");
40
+
41
+ const isIntent = (p) => typeof p === "string" && basename(p).startsWith(".placement-") && p.endsWith(".json");
42
+ // The phase transition writes the intent via a `.phase.tmp` scratch file.
43
+ const isPhaseScratch = (p) => typeof p === "string" && p.endsWith(".phase.tmp");
44
+
45
+ // fn -> predicate over the call's arguments: true means "pause HERE".
46
+ const BOUNDARIES = {
47
+ "intent-write": (name, args) => name === "renameSync" && isIntent(args[1]),
48
+ "link-to-cur": (name, args) => name === "linkSync" && args[1] === CUR,
49
+ "source-removal": (name, args) => name === "unlinkSync" && args[0] === SRC,
50
+ "ledger-commit": (name, args) => name === "appendFileSync" && args[0] === LEDGER,
51
+ "intent-finish": (name, args) => name === "unlinkSync" && isIntent(args[0]),
52
+ // cli#617 slice (b): the `in_progress` phase write (placing -> in_progress).
53
+ "phase-write": (name, args) => name === "renameSync" && isIntent(args[1]) && isPhaseScratch(args[0]),
54
+ };
55
+ const HOLD_AFTER_DELIVERY = KILL_AT === "after-delivery";
56
+ const matches = HOLD_AFTER_DELIVERY ? () => false : BOUNDARIES[KILL_AT];
57
+ if (!matches) {
58
+ process.stderr.write(`mail-kill-child: unknown TPS_KILL_AT=${JSON.stringify(KILL_AT)}\n`);
59
+ process.exit(2);
60
+ }
61
+
62
+ let paused = false;
63
+ function pause() {
64
+ paused = true;
65
+ if (MARKER) origWrite.call(fs, MARKER, "paused");
66
+ const deadline = Date.now() + 60_000;
67
+ while (Date.now() < deadline) {
68
+ /* spin until killed */
69
+ }
70
+ process.exit(3);
71
+ }
72
+ for (const name of ["writeFileSync", "openSync", "linkSync", "appendFileSync", "rmSync", "unlinkSync", "renameSync"]) {
73
+ const orig = fs[name];
74
+ fs[name] = function (...args) {
75
+ if (KILL_AFTER) {
76
+ const result = orig.apply(this, args);
77
+ if (!paused && matches(name, args)) pause();
78
+ return result;
79
+ }
80
+ if (!paused && matches(name, args)) pause();
81
+ return orig.apply(this, args);
82
+ };
83
+ }
84
+
85
+ const [mailDir, agentId] = process.argv.slice(2);
86
+ const ed = await import("@noble/ed25519");
87
+ const seed = Buffer.from(process.env.TPS_SEED, "base64");
88
+ const from = process.env.TPS_FROM;
89
+ const mod = await import(process.env.TPS_MAIL_MODULE);
90
+ const client = new mod.MailClient(mailDir, undefined, agentId, {
91
+ async getAgent(name) {
92
+ return name === from ? { publicKey: Buffer.from(ed.getPublicKey(seed)) } : null;
93
+ },
94
+ });
95
+ let count;
96
+ if ((process.env.TPS_DRIVE ?? "checkNewMail") === "deliverNext") {
97
+ const result = await client.deliverNext();
98
+ count = result.status === "delivered" ? 1 : 0;
99
+ if (HOLD_AFTER_DELIVERY && result.status === "delivered") pause();
100
+ } else {
101
+ count = (await client.checkNewMail()).length;
102
+ }
103
+ process.stdout.write(JSON.stringify({ count }));
104
+ process.exit(0);
@@ -0,0 +1,31 @@
1
+ /**
2
+ * signed-relay-record.ts — a relayed mail record carrying a validly signed
3
+ * envelope, and a Flair stub that resolves the sender's public key, which
4
+ * MailClient uses to verify it, for MailClient promotion tests.
5
+ */
6
+ import * as ed from "@noble/ed25519";
7
+ import { signEnvelope } from "../../src/lib/signEnvelope.js";
8
+
9
+ const SENDER_SEED = Buffer.alloc(32, 1);
10
+
11
+ /** A Flair stub that resolves the sender's public key, as MailClient needs to verify. */
12
+ export function senderKeyResolver() {
13
+ return {
14
+ async getAgent() {
15
+ return { publicKey: Buffer.from(ed.getPublicKey(SENDER_SEED)) };
16
+ },
17
+ };
18
+ }
19
+
20
+ /** The raw bytes of a relayed record whose body is an envelope signed by `sender`, addressed to `to`. */
21
+ export function signedRelayRecord(to: string, messageId: string, relayDelivery: { branchId: string; id: string }): string {
22
+ const timestamp = new Date().toISOString();
23
+ const envelope = signEnvelope({
24
+ v: 1, from: "sender", to, body: "hello", messageId, timestamp,
25
+ delegationChain: [
26
+ { agent: "system", kind: "human", timestamp, rationale: "origin", signature: null },
27
+ { agent: "sender", kind: "agent", timestamp, rationale: "send", signature: null },
28
+ ],
29
+ }, { sender: SENDER_SEED });
30
+ return JSON.stringify({ from: "sender", body: JSON.stringify(envelope), relayDelivery });
31
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * home-per-call.test.ts — cli#439, agent package.
3
+ *
4
+ * `llm/provider.ts` built its auth-directory path once, when the module loaded.
5
+ * This case imports the module and then uses it under a *different* HOME: the
6
+ * credential it acts on must follow the HOME in effect at the call.
7
+ *
8
+ * Both homes are temp dirs; nothing here reads or writes a real home.
9
+ */
10
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { tmpdir } from "node:os";
14
+
15
+ let homeA: string;
16
+ let homeB: string;
17
+ let startHome: string | undefined;
18
+
19
+ beforeAll(() => {
20
+ startHome = process.env.HOME;
21
+ homeA = mkdtempSync(join(tmpdir(), "tps-agent-home-a-"));
22
+ homeB = mkdtempSync(join(tmpdir(), "tps-agent-home-b-"));
23
+ });
24
+
25
+ afterAll(() => {
26
+ process.env.HOME = startHome;
27
+ rmSync(homeA, { recursive: true, force: true });
28
+ rmSync(homeB, { recursive: true, force: true });
29
+ });
30
+
31
+ describe("cli#439: home-relative paths follow the HOME in effect at each call (agent)", () => {
32
+ test("llm/provider.ts: the OAuth credential is read from the current HOME", async () => {
33
+ process.env.HOME = homeA;
34
+ const mod: any = await import("../src/llm/provider.js?home-per-call");
35
+ process.env.HOME = homeB;
36
+
37
+ const dir = join(homeB, ".tps", "auth");
38
+ mkdirSync(dir, { recursive: true });
39
+ writeFileSync(
40
+ join(dir, "anthropic.json"),
41
+ JSON.stringify({
42
+ provider: "anthropic",
43
+ refreshToken: "r",
44
+ accessToken: "token-from-b",
45
+ expiresAt: Date.now() + 3_600_000,
46
+ clientId: "id",
47
+ scopes: "s",
48
+ }),
49
+ );
50
+
51
+ let sentKey: string | undefined;
52
+ const originalFetch = globalThis.fetch;
53
+ globalThis.fetch = (async (_url: string | URL, init?: RequestInit) => {
54
+ sentKey = (init?.headers as Record<string, string>)?.["x-api-key"];
55
+ return new Response(
56
+ JSON.stringify({ content: [{ type: "text", text: "ok" }], usage: { input_tokens: 1, output_tokens: 2 } }),
57
+ { status: 200, headers: { "Content-Type": "application/json" } },
58
+ );
59
+ }) as typeof globalThis.fetch;
60
+
61
+ try {
62
+ const manager = new mod.ProviderManager({ provider: "anthropic", model: "claude-x", auth: "oauth" });
63
+ const out = await manager.complete({ messages: [{ role: "user", content: "hi" }], tools: [] });
64
+ expect(out.content).toBe("ok");
65
+ } finally {
66
+ globalThis.fetch = originalFetch;
67
+ }
68
+
69
+ // Not "configured": the credential B holds is the one that reached the API.
70
+ expect(sentKey).toBe("token-from-b");
71
+ }, 20_000);
72
+ });
package/test/io.test.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { describe, test, expect, beforeEach, afterEach } from "bun:test";
2
- import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { mkdtempSync, rmSync, writeFileSync, mkdirSync, readdirSync } from "node:fs";
3
+ import { generateKeyPairSync } from "node:crypto";
3
4
  import { join } from "node:path";
4
5
  import { tmpdir } from "node:os";
5
6
  import { MailClient } from "../src/io/mail.js";
@@ -8,11 +9,15 @@ import { ContextManager } from "../src/io/context.js";
8
9
 
9
10
  describe("MailClient", () => {
10
11
  let tmpDir: string;
12
+ let keyPath: string;
11
13
  let client: MailClient;
12
14
 
13
15
  beforeEach(() => {
14
16
  tmpDir = mkdtempSync(join(tmpdir(), "tps-mail-test-"));
15
- client = new MailClient(tmpDir, undefined, "testagent");
17
+ // sendMail signs as the agent; give it a raw 32-byte Ed25519 seed.
18
+ keyPath = join(tmpDir, "testagent.key");
19
+ writeFileSync(keyPath, Buffer.alloc(32, 3));
20
+ client = new MailClient(tmpDir, undefined, "testagent", { getAgent: async () => null }, keyPath);
16
21
  });
17
22
 
18
23
  afterEach(() => {
@@ -31,24 +36,86 @@ describe("MailClient", () => {
31
36
  expect(msgs).toEqual([]);
32
37
  });
33
38
 
34
- test("checkNewMail refuses to promote when no verifier is configured (cli#380 F1)", async () => {
35
- const { writeFileSync, existsSync } = await import("node:fs");
36
- writeFileSync(join(tmpDir, "testagent", "new", "test-1.json"), "hello world", "utf-8");
37
-
38
- // No FlairClient → verification cannot run. An absent verifier must never
39
- // mean "promote without verifying": the record is NOT moved.
40
- const msgs = await client.checkNewMail();
41
- expect(msgs.length).toBe(0);
42
- expect(existsSync(join(tmpDir, "testagent", "new", "test-1.json"))).toBe(true);
43
- expect(existsSync(join(tmpDir, "testagent", "cur", "test-1.json"))).toBe(false);
39
+ test("constructing a MailClient without a verifier throws (cli#380)", () => {
40
+ expect(() => new MailClient(tmpDir, undefined, "testagent")).toThrow(/requires a Flair verifier/);
44
41
  });
45
42
 
46
- test("sendMail writes a file to outbox/new", async () => {
43
+ test("sendMail writes a signed envelope to outbox/new", async () => {
47
44
  await client.sendMail("host@tps", "hello from agent");
48
45
 
49
- const { readdirSync } = await import("node:fs");
46
+ const { readdirSync, readFileSync } = await import("node:fs");
50
47
  const files = readdirSync(join(tmpDir, "testagent", "outbox"));
51
48
  expect(files.length).toBe(1);
49
+ const record = JSON.parse(readFileSync(join(tmpDir, "testagent", "outbox", files[0]!), "utf-8"));
50
+ expect(record.from).toBe("testagent");
51
+ const envelope = JSON.parse(record.body);
52
+ expect(envelope.v).toBe(1);
53
+ expect(envelope.from).toBe("testagent");
54
+ expect(envelope.to).toBe("host@tps");
55
+ expect(envelope.body).toBe("hello from agent");
56
+ expect(envelope.signature).toMatch(/^ed25519:/);
57
+ });
58
+
59
+ test("sendMail refuses with a named error and writes nothing when no key exists", async () => {
60
+ const keyless = new MailClient(tmpDir, undefined, "nokeyagent", { getAgent: async () => null });
61
+ await expect(keyless.sendMail("host@tps", "hi")).rejects.toThrow(/no Ed25519 private key/);
62
+ const { readdirSync } = await import("node:fs");
63
+ expect(readdirSync(join(tmpDir, "nokeyagent", "outbox")).filter((f) => f.endsWith(".json")).length).toBe(0);
64
+ });
65
+
66
+ test("sendMail accepts raw PKCS8 DER through the shared key reader", async () => {
67
+ const { privateKey } = generateKeyPairSync("ed25519");
68
+ writeFileSync(keyPath, privateKey.export({ format: "der", type: "pkcs8" }));
69
+ await client.sendMail("host", "DER signed");
70
+ expect(readdirSync(join(tmpDir, "testagent", "outbox")).filter((f) => f.endsWith(".json"))).toHaveLength(1);
71
+ });
72
+
73
+ test("sendMail refuses X25519 material before writing", async () => {
74
+ const { privateKey } = generateKeyPairSync("x25519");
75
+ writeFileSync(keyPath, privateKey.export({ format: "der", type: "pkcs8" }));
76
+ await expect(client.sendMail("host", "wrong algorithm")).rejects.toThrow(/not an Ed25519 key/);
77
+ expect(readdirSync(join(tmpDir, "testagent", "outbox")).filter((f) => f.endsWith(".json"))).toHaveLength(0);
78
+ });
79
+
80
+ test("sendMail refuses conflicting Flair and identity keys", async () => {
81
+ const oldHome = process.env.HOME;
82
+ const oldTestKeys = process.env.TPS_TEST_KEYS_DIR;
83
+ try {
84
+ process.env.HOME = tmpDir;
85
+ delete process.env.TPS_TEST_KEYS_DIR;
86
+ const flair = join(tmpDir, ".flair", "keys");
87
+ const identity = join(tmpDir, ".tps", "identity");
88
+ mkdirSync(flair, { recursive: true });
89
+ mkdirSync(identity, { recursive: true });
90
+ writeFileSync(join(flair, "conflict.key"), Buffer.alloc(32, 1));
91
+ writeFileSync(join(identity, "conflict.key"), Buffer.alloc(32, 2));
92
+ const conflicting = new MailClient(tmpDir, undefined, "conflict", { getAgent: async () => null });
93
+ await expect(conflicting.sendMail("host", "no delivery")).rejects.toThrow(/two different Ed25519 private keys/);
94
+ expect(readdirSync(join(tmpDir, "conflict", "outbox")).filter((f) => f.endsWith(".json"))).toHaveLength(0);
95
+ } finally {
96
+ if (oldHome === undefined) delete process.env.HOME; else process.env.HOME = oldHome;
97
+ if (oldTestKeys === undefined) delete process.env.TPS_TEST_KEYS_DIR; else process.env.TPS_TEST_KEYS_DIR = oldTestKeys;
98
+ }
99
+ });
100
+
101
+ test("an explicit Flair key path cannot bypass conflicting default locations", async () => {
102
+ const oldHome = process.env.HOME;
103
+ const oldTestKeys = process.env.TPS_TEST_KEYS_DIR;
104
+ try {
105
+ process.env.HOME = tmpDir;
106
+ delete process.env.TPS_TEST_KEYS_DIR;
107
+ const flair = join(tmpDir, ".flair", "keys");
108
+ const identity = join(tmpDir, ".tps", "identity");
109
+ mkdirSync(flair, { recursive: true });
110
+ mkdirSync(identity, { recursive: true });
111
+ writeFileSync(join(flair, "testagent.key"), Buffer.alloc(32, 3));
112
+ writeFileSync(join(identity, "testagent.key"), Buffer.alloc(32, 4));
113
+ await expect(client.sendMail("host", "no delivery")).rejects.toThrow(/two different Ed25519 private keys/);
114
+ expect(readdirSync(join(tmpDir, "testagent", "outbox")).filter((f) => f.endsWith(".json"))).toHaveLength(0);
115
+ } finally {
116
+ if (oldHome === undefined) delete process.env.HOME; else process.env.HOME = oldHome;
117
+ if (oldTestKeys === undefined) delete process.env.TPS_TEST_KEYS_DIR; else process.env.TPS_TEST_KEYS_DIR = oldTestKeys;
118
+ }
52
119
  });
53
120
  });
54
121