@tpsdev-ai/agent 0.7.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 (134) hide show
  1. package/bun.lock +27 -15
  2. package/bunfig.toml +17 -0
  3. package/dist/bin.js +4 -3
  4. package/dist/bin.js.map +1 -1
  5. package/dist/config.d.ts +8 -1
  6. package/dist/config.d.ts.map +1 -1
  7. package/dist/config.js +38 -3
  8. package/dist/config.js.map +1 -1
  9. package/dist/home.d.ts +3 -0
  10. package/dist/home.d.ts.map +1 -0
  11. package/dist/home.js +18 -0
  12. package/dist/home.js.map +1 -0
  13. package/dist/index.d.ts +16 -3
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +12 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/io/flair.d.ts +1 -10
  18. package/dist/io/flair.d.ts.map +1 -1
  19. package/dist/io/flair.js +29 -28
  20. package/dist/io/flair.js.map +1 -1
  21. package/dist/io/mail.d.ts +184 -30
  22. package/dist/io/mail.d.ts.map +1 -1
  23. package/dist/io/mail.js +944 -185
  24. package/dist/io/mail.js.map +1 -1
  25. package/dist/lib/agent-keys.d.ts +106 -0
  26. package/dist/lib/agent-keys.d.ts.map +1 -0
  27. package/dist/lib/agent-keys.js +298 -0
  28. package/dist/lib/agent-keys.js.map +1 -0
  29. package/dist/lib/bridge-identity.d.ts +10 -0
  30. package/dist/lib/bridge-identity.d.ts.map +1 -0
  31. package/dist/lib/bridge-identity.js +56 -0
  32. package/dist/lib/bridge-identity.js.map +1 -0
  33. package/dist/lib/mail-lock-namespace.d.ts +19 -0
  34. package/dist/lib/mail-lock-namespace.d.ts.map +1 -0
  35. package/dist/lib/mail-lock-namespace.js +58 -0
  36. package/dist/lib/mail-lock-namespace.js.map +1 -0
  37. package/dist/lib/mail-lock.d.ts +81 -0
  38. package/dist/lib/mail-lock.d.ts.map +1 -0
  39. package/dist/lib/mail-lock.js +319 -0
  40. package/dist/lib/mail-lock.js.map +1 -0
  41. package/dist/lib/mailbox-filename.d.ts +2 -0
  42. package/dist/lib/mailbox-filename.d.ts.map +1 -0
  43. package/dist/lib/mailbox-filename.js +4 -0
  44. package/dist/lib/mailbox-filename.js.map +1 -0
  45. package/dist/lib/mailbox-policy.d.ts +245 -0
  46. package/dist/lib/mailbox-policy.d.ts.map +1 -0
  47. package/dist/lib/mailbox-policy.js +949 -0
  48. package/dist/lib/mailbox-policy.js.map +1 -0
  49. package/dist/lib/public-key.d.ts +6 -0
  50. package/dist/lib/public-key.d.ts.map +1 -0
  51. package/dist/lib/public-key.js +45 -0
  52. package/dist/lib/public-key.js.map +1 -0
  53. package/dist/lib/registry-key.d.ts +2 -0
  54. package/dist/lib/registry-key.d.ts.map +1 -0
  55. package/dist/lib/registry-key.js +10 -0
  56. package/dist/lib/registry-key.js.map +1 -0
  57. package/dist/lib/relay-lock.d.ts +7 -0
  58. package/dist/lib/relay-lock.d.ts.map +1 -0
  59. package/dist/lib/relay-lock.js +19 -0
  60. package/dist/lib/relay-lock.js.map +1 -0
  61. package/dist/lib/signEnvelope.d.ts +12 -0
  62. package/dist/lib/signEnvelope.d.ts.map +1 -1
  63. package/dist/lib/signEnvelope.js.map +1 -1
  64. package/dist/lib/signing-key.d.ts +2 -0
  65. package/dist/lib/signing-key.d.ts.map +1 -0
  66. package/dist/lib/signing-key.js +9 -0
  67. package/dist/lib/signing-key.js.map +1 -0
  68. package/dist/lib/topic-recipient.d.ts +2 -0
  69. package/dist/lib/topic-recipient.d.ts.map +1 -0
  70. package/dist/lib/topic-recipient.js +2 -0
  71. package/dist/lib/topic-recipient.js.map +1 -0
  72. package/dist/llm/provider.d.ts.map +1 -1
  73. package/dist/llm/provider.js +9 -7
  74. package/dist/llm/provider.js.map +1 -1
  75. package/dist/runtime/agent.d.ts.map +1 -1
  76. package/dist/runtime/agent.js +32 -25
  77. package/dist/runtime/agent.js.map +1 -1
  78. package/dist/runtime/event-loop.d.ts +21 -2
  79. package/dist/runtime/event-loop.d.ts.map +1 -1
  80. package/dist/runtime/event-loop.js +199 -54
  81. package/dist/runtime/event-loop.js.map +1 -1
  82. package/dist/runtime/types.d.ts +11 -0
  83. package/dist/runtime/types.d.ts.map +1 -1
  84. package/dist/runtime/types.js +13 -1
  85. package/dist/runtime/types.js.map +1 -1
  86. package/package.json +3 -4
  87. package/src/bin.ts +4 -3
  88. package/src/config.ts +46 -3
  89. package/src/home.ts +18 -0
  90. package/src/index.ts +33 -2
  91. package/src/io/flair.ts +23 -28
  92. package/src/io/mail.ts +1007 -200
  93. package/src/lib/agent-keys.ts +308 -0
  94. package/src/lib/bridge-identity.ts +49 -0
  95. package/src/lib/mail-lock-namespace.ts +64 -0
  96. package/src/lib/mail-lock.ts +337 -0
  97. package/src/lib/mailbox-filename.ts +3 -0
  98. package/src/lib/mailbox-policy.ts +1085 -0
  99. package/src/lib/public-key.ts +49 -0
  100. package/src/lib/registry-key.ts +8 -0
  101. package/src/lib/relay-lock.ts +20 -0
  102. package/src/lib/signEnvelope.ts +12 -0
  103. package/src/lib/signing-key.ts +8 -0
  104. package/src/lib/topic-recipient.ts +1 -0
  105. package/src/llm/provider.ts +9 -7
  106. package/src/runtime/agent.ts +30 -27
  107. package/src/runtime/event-loop.ts +221 -68
  108. package/src/runtime/types.ts +14 -0
  109. package/test/config.test.ts +85 -2
  110. package/test/core-loop.test.ts +6 -4
  111. package/test/governance.test.ts +4 -1
  112. package/test/helpers/event-loop-child.mjs +50 -0
  113. package/test/helpers/mail-delivery-worker.mjs +16 -0
  114. package/test/helpers/mail-kill-child.mjs +104 -0
  115. package/test/helpers/signed-relay-record.ts +31 -0
  116. package/test/home-per-call.test.ts +72 -0
  117. package/test/io.test.ts +81 -14
  118. package/test/mail-client-lock-namespace.test.ts +155 -0
  119. package/test/mail-client-repoint-root.test.ts +368 -0
  120. package/test/mail-delivery-at-least-once.test.ts +1238 -0
  121. package/test/mail-event-loop-delivery.test.ts +769 -0
  122. package/test/mail-intent-phases.test.ts +304 -0
  123. package/test/mail-interrupted-recovery.test.ts +393 -0
  124. package/test/mail-lock-pid-state.test.ts +238 -0
  125. package/test/mail-lock.test.ts +96 -0
  126. package/test/mail-partial-flair.test.ts +102 -0
  127. package/test/mail-placement-replay.test.ts +116 -0
  128. package/test/mail-promote-guard.test.ts +305 -21
  129. package/test/mail-relay-reservation.test.ts +60 -0
  130. package/test/mailbox-filename.test.ts +16 -0
  131. package/test/public-key.test.ts +108 -0
  132. package/test/runtime-key-encoding.test.ts +105 -0
  133. package/test/runtime-pending-key.test.ts +117 -0
  134. package/test/security/mail-trust.test.ts +406 -109
package/src/config.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { readFileSync } from "node:fs";
2
+ import { dirname, isAbsolute, resolve } from "node:path";
2
3
  import yaml from "js-yaml";
3
4
  import { createHash } from "node:crypto";
4
5
  import type { AgentConfig } from "./runtime/types.js";
@@ -23,7 +24,7 @@ export interface AgentRuntimeConfig {
23
24
  execAllowlist?: string[];
24
25
  }
25
26
 
26
- function interpolateEnvInString(raw: string): string {
27
+ export function interpolateEnvInString(raw: string): string {
27
28
  return raw.replace(/\$\{([A-Z0-9_]+)\}/g, (_match, varName: string) => {
28
29
  const resolved = process.env[varName];
29
30
  if (resolved === undefined) {
@@ -53,12 +54,54 @@ function interpolateEnvVars<T>(value: T): T {
53
54
  return value;
54
55
  }
55
56
 
56
- export function loadAgentConfig(path: string): AgentConfig {
57
+ export function refuseTildeWorkspace(configured: string, key = "workspace"): void {
58
+ if (configured.startsWith("~")) {
59
+ throw new Error(
60
+ `${key} '${configured}' starts with '~', which is not expanded: use an absolute path or a path relative to the config file`,
61
+ );
62
+ }
63
+ }
64
+
65
+ function readConfiguredPath(parsed: Record<string, unknown>, key: "workspace" | "repo"): string | undefined {
66
+ if (!Object.hasOwn(parsed, key)) return undefined;
67
+ const value = parsed[key];
68
+ if (value === null) {
69
+ throw new Error(
70
+ `${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`,
71
+ );
72
+ }
73
+ if (typeof value !== "string") throw new Error(`${key} must be a string path`);
74
+ if (value.trim() === "") {
75
+ throw new Error(
76
+ `${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`,
77
+ );
78
+ }
79
+ refuseTildeWorkspace(value, key);
80
+ return value;
81
+ }
82
+
83
+ /** The `workspace` and `repo` values a parsed agent config sets; an absent key reads as undefined. */
84
+ export function readConfiguredWorkspace(parsed: Record<string, unknown>): { workspace?: string; repo?: string } {
85
+ return { workspace: readConfiguredPath(parsed, "workspace"), repo: readConfiguredPath(parsed, "repo") };
86
+ }
87
+
88
+ /**
89
+ * A relative workspace is anchored at the config file's directory, so the
90
+ * launching process and a sandboxed child resolve the same absolute path. An
91
+ * absolute workspace remains absolute and is normalized.
92
+ */
93
+ function resolveWorkspace(configured: string, configDir: string): string {
94
+ return isAbsolute(configured) ? resolve(configured) : resolve(configDir, configured);
95
+ }
96
+
97
+ export function loadAgentConfig(path: string, baseDir: string = dirname(path)): AgentConfig {
57
98
  const raw = readFileSync(path, "utf-8");
58
99
  const parsedRaw = (yaml.load(raw) ?? {}) as Record<string, any>;
59
100
  const parsed = interpolateEnvVars(parsedRaw);
60
101
 
61
- const workspace = String(parsed.workspace || parsed.repo || process.cwd());
102
+ const configured = readConfiguredWorkspace(parsed);
103
+ const configuredWorkspace = configured.workspace ?? configured.repo;
104
+ const workspace = configuredWorkspace ? resolveWorkspace(configuredWorkspace, baseDir) : process.cwd();
62
105
  const memoryPath = parsed.memoryPath || `${workspace}/.openclaw/agent.memory.jsonl`;
63
106
 
64
107
  const agent: AgentConfig = {
package/src/home.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * home.ts — the home directory, resolved when it is needed (cli#439).
3
+ *
4
+ * `homeDir()` returns `process.env.HOME` when it is set and not empty, and
5
+ * otherwise `os.homedir()`. It mirrors the CLI's `src/utils/home.ts`; the agent
6
+ * package cannot import the CLI package (see `io/mail.ts`), so the rule is
7
+ * spelled out here.
8
+ *
9
+ * Call it where a path is used, not once at module load: a path built at import
10
+ * time keeps whatever HOME was set then, and every later call in the same
11
+ * process uses that path whatever HOME says now.
12
+ */
13
+ import { homedir } from "node:os";
14
+
15
+ /** `process.env.HOME` when set and not empty, else `os.homedir()`. Read on every call. */
16
+ export function homeDir(): string {
17
+ return process.env.HOME || homedir();
18
+ }
package/src/index.ts CHANGED
@@ -3,6 +3,8 @@
3
3
  // Runtime
4
4
  export { AgentRuntime } from "./runtime/agent.js";
5
5
  export { EventLoop } from "./runtime/event-loop.js";
6
+ export type { MailDeliverySource } from "./runtime/event-loop.js";
7
+ export { signedTrustTier } from "./runtime/types.js";
6
8
  export type {
7
9
  AgentConfig,
8
10
  LLMConfig,
@@ -13,11 +15,12 @@ export type {
13
15
  ToolSpec,
14
16
  LLMMessage,
15
17
  ToolResult,
18
+ TrustLevel,
16
19
  } from "./runtime/types.js";
17
20
 
18
21
  // I/O
19
22
  export { MailClient } from "./io/mail.js";
20
- export type { MailMessage } from "./io/mail.js";
23
+ export type { MailMessage, MailDelivery, DeliverNextResult, DeliveryDeferral, DeliveryCompletion, DeliveryRelease } from "./io/mail.js";
21
24
  export { MemoryStore } from "./io/memory.js";
22
25
  export type { MemoryEvent } from "./io/memory.js";
23
26
  export { ContextManager } from "./io/context.js";
@@ -35,7 +38,7 @@ export { BoundaryManager } from "./governance/boundary.js";
35
38
  export { ReviewGate } from "./governance/review-gate.js";
36
39
 
37
40
  // Config
38
- export { loadAgentConfig } from "./config.js";
41
+ export { interpolateEnvInString, loadAgentConfig, readConfiguredWorkspace, refuseTildeWorkspace } from "./config.js";
39
42
 
40
43
  // Flair integration
41
44
  export { FlairContextProvider } from "./io/flair.js";
@@ -44,3 +47,31 @@ export type { FlairConfig } from "./runtime/types.js";
44
47
  // Signing
45
48
  export { signEnvelope, verifyEnvelope } from "./lib/signEnvelope.js";
46
49
  export type { Envelope, ChainEntry, FlairClient, VerifyOk, VerifyReject } from "./lib/signEnvelope.js";
50
+ export { parseFlairPublicKey, PublicKeyFormatError } from "./lib/public-key.js";
51
+
52
+ export { isMailboxMessageFile } from "./lib/mailbox-filename.js";
53
+
54
+ // Mailbox policy (cli#380)
55
+ export {
56
+ ENVELOPE_ID_SHAPE, ENVELOPE_ID_SHAPE_TEXT, isValidEnvelopeId, tryParseEnvelope, parseSignedEnvelope,
57
+ decideEnvelopeForMailbox, isTopicRecipient, mailboxReplayStore, peekConsumedForMailboxRoot, hasCommittedMessageId,
58
+ pendingPlacementEntries,
59
+ placeCurRecord, fileIdentity, matchesFileIdentity,
60
+ MAX_DELIVERY_PRESENTATIONS, DELIVERY_PRESENTATION_TTL_MS,
61
+ } from "./lib/mailbox-policy.js";
62
+ export type { MailboxPolicyRejectClass, MailboxPolicyResult, PlacementPhase, ReplayStore, FirstDelivery, PresentationAdvance, PresentationClaim, PlacementState, PlacementCompletion } from "./lib/mailbox-policy.js";
63
+ export { acquireMailLock, acquireMailLockSync, isValidPid, MAIL_LOCK_DIR, mailLockPath, pidState, pidStateFromProbeError, processIsGone, processStartToken } from "./lib/mail-lock.js";
64
+ export type { MailLock, PidState } from "./lib/mail-lock.js";
65
+ export {
66
+ KeyFormatError, AgentKeyError, AgentKeyConflictError,
67
+ agentKeyCandidates, existingAgentKeyPaths, resolveAgentKeyPath,
68
+ readAgentPrivateKey, readPrivateKeyAtPath, toEd25519Seed,
69
+ } from "./lib/agent-keys.js";
70
+
71
+ export { decodeRegistryPublicKey } from "./lib/registry-key.js";
72
+ export { BRIDGE_ADAPTERS, resolveBridgeAgentId, configureBridgeIdentity, bridgePrincipalIds, verifiedMailTier } from "./lib/bridge-identity.js";
73
+
74
+ export { RELAY_ACCEPT_LOCK_STRIPES, relayAcceptanceLockRoot, tryAcquireRelayMoveLock } from "./lib/relay-lock.js";
75
+ export {
76
+ canonicalMailRoot, canonicalMailboxRoot, acceptanceLockRoot, mailboxLockRoot, configuredMailRoot,
77
+ } from "./lib/mail-lock-namespace.js";
package/src/io/flair.ts CHANGED
@@ -6,7 +6,8 @@
6
6
  */
7
7
 
8
8
  import crypto from "node:crypto";
9
- import { readFileSync, existsSync } from "node:fs";
9
+ import { parseFlairPublicKey } from "../lib/public-key.js";
10
+ import { readPrivateKeyAtPath } from "../lib/agent-keys.js";
10
11
  import { homedir } from "node:os";
11
12
  import { join } from "node:path";
12
13
  import type { FlairConfig } from "../runtime/types.js";
@@ -30,6 +31,10 @@ export interface FlairSoulEntry {
30
31
  value: string;
31
32
  }
32
33
 
34
+ class FlairHttpError extends Error {
35
+ constructor(message: string, readonly status: number) { super(message); }
36
+ }
37
+
33
38
  export class FlairContextProvider {
34
39
  private readonly url: string;
35
40
  private readonly agentId: string;
@@ -50,17 +55,14 @@ export class FlairContextProvider {
50
55
  const nonce = crypto.randomUUID();
51
56
  const payload = `${this.agentId}:${ts}:${nonce}:${method}:${path}`;
52
57
 
53
- if (!existsSync(this.keyPath)) {
58
+ const seed = readPrivateKeyAtPath(this.keyPath);
59
+ if (!seed) {
54
60
  throw new Error(`Flair key not found at ${this.keyPath}. Run: tps agent create --id ${this.agentId}`);
55
61
  }
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
- }
62
+ const key = crypto.createPrivateKey({
63
+ key: Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), seed]),
64
+ format: "der", type: "pkcs8",
65
+ });
64
66
  const sig = crypto.sign(null, Buffer.from(payload), key);
65
67
  return `TPS-Ed25519 ${this.agentId}:${ts}:${nonce}:${sig.toString("base64")}`;
66
68
  }
@@ -76,7 +78,7 @@ export class FlairContextProvider {
76
78
  });
77
79
  if (!res.ok) {
78
80
  const txt = await res.text().catch(() => "");
79
- throw new Error(`Flair ${method} ${path} → ${res.status}: ${txt}`);
81
+ throw new FlairHttpError(`Flair ${method} ${path} → ${res.status}: ${txt}`, res.status);
80
82
  }
81
83
  if (res.status === 204) return undefined as T;
82
84
  return res.json() as Promise<T>;
@@ -93,25 +95,18 @@ export class FlairContextProvider {
93
95
  }
94
96
  }
95
97
 
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
- */
98
+ /** Return null only for a not-found response; other failures throw. */
106
99
  async getAgent(name: string): Promise<FlairAgent | null> {
107
100
  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;
101
+ const agent = await this.req<FlairAgent>("GET", `/Agent/${encodeURIComponent(name)}`);
102
+ if (!agent || typeof agent.publicKey !== "string") throw new Error("invalid principal record");
103
+ // Flair's placeholder until the principal's key is registered: retryable, not malformed.
104
+ if (agent.publicKey === "pending") throw new Error(`Flair has no registered public key for ${name} yet (pending)`);
105
+ parseFlairPublicKey(agent.publicKey);
106
+ return agent;
107
+ } catch (err) {
108
+ if (err instanceof FlairHttpError && err.status === 404) return null;
109
+ throw err;
115
110
  }
116
111
  }
117
112