@tpsdev-ai/agent 0.5.3 → 0.6.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 +43 -0
  12. package/dist/io/flair.d.ts.map +1 -0
  13. package/dist/io/flair.js +143 -0
  14. package/dist/io/flair.js.map +1 -0
  15. package/dist/io/mail.d.ts +24 -2
  16. package/dist/io/mail.d.ts.map +1 -1
  17. package/dist/io/mail.js +168 -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 +21 -1
  24. package/dist/llm/provider.d.ts.map +1 -1
  25. package/dist/llm/provider.js +422 -23
  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 +50 -3
  30. package/dist/runtime/agent.js.map +1 -1
  31. package/dist/runtime/event-loop.d.ts +44 -2
  32. package/dist/runtime/event-loop.d.ts.map +1 -1
  33. package/dist/runtime/event-loop.js +478 -56
  34. package/dist/runtime/event-loop.js.map +1 -1
  35. package/dist/runtime/types.d.ts +27 -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 +183 -0
  49. package/src/io/mail.ts +184 -19
  50. package/src/lib/signEnvelope.ts +332 -0
  51. package/src/llm/provider.ts +454 -22
  52. package/src/runtime/agent.ts +55 -3
  53. package/src/runtime/event-loop.ts +523 -44
  54. package/src/runtime/types.ts +32 -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 +8 -8
  63. package/test/provider.test.ts +471 -0
  64. package/test/security/mail-trust.test.ts +266 -0
@@ -1,3 +1,7 @@
1
+ import crypto from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
1
5
  import type {
2
6
  LLMConfig,
3
7
  CompletionRequest,
@@ -6,28 +10,214 @@ import type {
6
10
  ToolSpec,
7
11
  LLMMessage,
8
12
  } from "../runtime/types.js";
13
+ import type { EventLogger } from "../telemetry/events.js";
14
+ import { sanitizeError } from "../telemetry/events.js";
9
15
 
10
16
  type ProviderKind = LLMConfig["provider"];
11
17
 
18
+ interface OAuthCredentials {
19
+ provider: string;
20
+ refreshToken: string;
21
+ accessToken: string;
22
+ expiresAt: number;
23
+ clientId: string;
24
+ scopes: string;
25
+ }
26
+
27
+ const AUTH_DIR = join(process.env.HOME || homedir(), ".tps", "auth");
28
+ const ANTHROPIC_TOKEN_URL = "https://console.anthropic.com/v1/oauth/token";
29
+ const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
30
+
31
+ function oauthPath(provider: string): string {
32
+ return join(AUTH_DIR, `${provider}.json`);
33
+ }
34
+
35
+ function loadOAuth(provider: string): OAuthCredentials | null {
36
+ const p = oauthPath(provider);
37
+ if (!existsSync(p)) return null;
38
+ return JSON.parse(readFileSync(p, "utf-8")) as OAuthCredentials;
39
+ }
40
+
41
+ function saveOAuth(provider: string, creds: OAuthCredentials): void {
42
+ mkdirSync(AUTH_DIR, { recursive: true, mode: 0o700 });
43
+ writeFileSync(oauthPath(provider), JSON.stringify(creds, null, 2), { mode: 0o600 });
44
+ }
45
+
46
+ export async function refreshAnthropicOAuthToken(creds: OAuthCredentials): Promise<OAuthCredentials> {
47
+ const res = await fetch(ANTHROPIC_TOKEN_URL, {
48
+ method: "POST",
49
+ headers: {
50
+ "Content-Type": "application/json",
51
+ "User-Agent": "claude-code/1.0",
52
+ },
53
+ body: JSON.stringify({
54
+ grant_type: "refresh_token",
55
+ client_id: creds.clientId,
56
+ refresh_token: creds.refreshToken,
57
+ }),
58
+ });
59
+
60
+ if (!res.ok) {
61
+ throw new Error(`Anthropic token refresh failed: ${res.status} ${await res.text()}`);
62
+ }
63
+
64
+ const token = (await res.json()) as any;
65
+ const refreshed: OAuthCredentials = {
66
+ ...creds,
67
+ accessToken: token.access_token,
68
+ refreshToken: token.refresh_token || creds.refreshToken,
69
+ expiresAt: Date.now() + Number(token.expires_in || 0) * 1000,
70
+ };
71
+
72
+ // Sync back to Claude Code's credential file to prevent split-brain (S46-C)
73
+ syncToClaudeCode(refreshed);
74
+
75
+ return refreshed;
76
+ }
77
+
78
+ /**
79
+ * Keep Claude Code's credentials in sync after TPS refreshes the token.
80
+ */
81
+ function syncToClaudeCode(creds: OAuthCredentials): void {
82
+ const credPath = join(process.env.HOME || homedir(), ".claude", ".credentials.json");
83
+ if (!existsSync(credPath)) return;
84
+ try {
85
+ const data = JSON.parse(readFileSync(credPath, "utf-8"));
86
+ if (!data.claudeAiOauth) return;
87
+ data.claudeAiOauth.accessToken = creds.accessToken;
88
+ data.claudeAiOauth.refreshToken = creds.refreshToken;
89
+ data.claudeAiOauth.expiresAt = creds.expiresAt;
90
+ writeFileSync(credPath, JSON.stringify(data, null, 2), { mode: 0o600 });
91
+ } catch {
92
+ // Best-effort sync
93
+ }
94
+ }
95
+
96
+
97
+ export async function refreshGoogleOAuthToken(creds: OAuthCredentials): Promise<OAuthCredentials> {
98
+ if (!creds.clientId) {
99
+ throw new Error("Google OAuth refresh requires clientId. Run: tps auth login google");
100
+ }
101
+
102
+ const body = new URLSearchParams({
103
+ grant_type: "refresh_token",
104
+ client_id: creds.clientId,
105
+ refresh_token: creds.refreshToken,
106
+ });
107
+
108
+ const res = await fetch(GOOGLE_TOKEN_URL, {
109
+ method: "POST",
110
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
111
+ body,
112
+ });
113
+
114
+ if (!res.ok) {
115
+ throw new Error(`Google token refresh failed: ${res.status} ${await res.text()}`);
116
+ }
117
+
118
+ const token = (await res.json()) as any;
119
+ const refreshed: OAuthCredentials = {
120
+ ...creds,
121
+ accessToken: token.access_token,
122
+ refreshToken: token.refresh_token || creds.refreshToken,
123
+ expiresAt: Date.now() + Number(token.expires_in || 0) * 1000,
124
+ scopes: token.scope || creds.scopes,
125
+ };
126
+
127
+ syncToGeminiCli(refreshed);
128
+ return refreshed;
129
+ }
130
+
131
+ function syncToGeminiCli(creds: OAuthCredentials): void {
132
+ const home = process.env.HOME || homedir();
133
+ const xdg = process.env.XDG_CONFIG_HOME || join(home, ".config");
134
+ const candidates = [
135
+ join(home, ".gemini", "oauth_creds.json"),
136
+ join(xdg, "gemini", "oauth_creds.json"),
137
+ ];
138
+
139
+ for (const credPath of candidates) {
140
+ if (!existsSync(credPath)) continue;
141
+ try {
142
+ const data = JSON.parse(readFileSync(credPath, "utf-8"));
143
+ data.access_token = creds.accessToken;
144
+ data.refresh_token = creds.refreshToken;
145
+ data.expiry_date = creds.expiresAt;
146
+ if (creds.scopes) data.scope = creds.scopes;
147
+ if (creds.clientId) data.client_id = creds.clientId;
148
+ writeFileSync(credPath, JSON.stringify(data, null, 2), { mode: 0o600 });
149
+ return;
150
+ } catch {
151
+ // Best-effort sync
152
+ }
153
+ }
154
+ }
155
+
12
156
  /**
13
157
  * Routes completion requests to the configured provider and normalizes
14
158
  * tool-call responses into a common shape.
15
159
  */
16
160
  export class ProviderManager {
17
- constructor(private readonly config: LLMConfig) {}
161
+ constructor(
162
+ private readonly config: LLMConfig,
163
+ private readonly events?: EventLogger,
164
+ private readonly agentId = "unknown",
165
+ ) {}
18
166
 
19
167
  async complete(request: CompletionRequest): Promise<CompletionResponse> {
20
- switch (this.config.provider) {
21
- case "anthropic":
22
- return this.completeAnthropic(request);
23
- case "google":
24
- return this.completeGoogle(request);
25
- case "openai":
26
- return this.completeOpenAI(request);
27
- case "ollama":
28
- return this.completeOllama(request);
29
- default:
30
- throw new Error(`Unsupported provider: ${this.config.provider}`);
168
+ const started = Date.now();
169
+ const provider = this.config.provider;
170
+ const model = this.config.model;
171
+ try {
172
+ let out: CompletionResponse;
173
+
174
+ // Route through proxy when configured (sandbox mode)
175
+ if (this.config.proxyUrl) {
176
+ out = await this.completeViaProxy(request);
177
+ } else
178
+ switch (provider) {
179
+ case "anthropic":
180
+ out = await this.completeAnthropic(request);
181
+ break;
182
+ case "google":
183
+ out = await this.completeGoogle(request);
184
+ break;
185
+ case "openai":
186
+ out = await this.completeOpenAI(request);
187
+ break;
188
+ case "ollama":
189
+ out = await this.completeOllama(request);
190
+ break;
191
+ default:
192
+ throw new Error(`Unsupported provider: ${provider}`);
193
+ }
194
+
195
+ this.events?.emit({
196
+ type: "llm.request",
197
+ agent: this.agentId,
198
+ provider,
199
+ model,
200
+ inputTokens: out.inputTokens ?? 0,
201
+ outputTokens: out.outputTokens ?? 0,
202
+ cacheReadTokens: out.cacheReadTokens,
203
+ cacheWriteTokens: out.cacheWriteTokens,
204
+ durationMs: Date.now() - started,
205
+ status: "ok",
206
+ });
207
+ return out;
208
+ } catch (err) {
209
+ this.events?.emit({
210
+ type: "llm.request",
211
+ agent: this.agentId,
212
+ provider,
213
+ model,
214
+ inputTokens: 0,
215
+ outputTokens: 0,
216
+ durationMs: Date.now() - started,
217
+ status: "error",
218
+ error: sanitizeError(err),
219
+ });
220
+ throw err;
31
221
  }
32
222
  }
33
223
 
@@ -83,6 +273,10 @@ export class ProviderManager {
83
273
  toolCalls: toolCalls.length ? toolCalls : undefined,
84
274
  inputTokens: raw?.usage?.input_tokens ?? 0,
85
275
  outputTokens: raw?.usage?.output_tokens ?? 0,
276
+ cacheReadTokens: raw?.usage?.cache_read_input_tokens ?? 0,
277
+ cacheWriteTokens: raw?.usage?.cache_creation_input_tokens ?? 0,
278
+ // Raw assistant message preserves tool_use blocks for history
279
+ rawAssistantMessage: { role: "assistant", content: raw?.content },
86
280
  };
87
281
  }
88
282
 
@@ -99,6 +293,8 @@ export class ProviderManager {
99
293
  toolCalls: toolCalls.length ? toolCalls : undefined,
100
294
  inputTokens: raw?.usage?.prompt_tokens ?? 0,
101
295
  outputTokens: raw?.usage?.completion_tokens ?? 0,
296
+ cacheReadTokens: raw?.usage?.prompt_tokens_details?.cached_tokens ?? 0,
297
+ rawAssistantMessage: message,
102
298
  };
103
299
  }
104
300
 
@@ -121,6 +317,7 @@ export class ProviderManager {
121
317
  toolCalls: toolCalls && toolCalls.length ? toolCalls : undefined,
122
318
  inputTokens: raw?.prompt_eval_count ?? 0,
123
319
  outputTokens: raw?.eval_count ?? 0,
320
+ rawAssistantMessage: message,
124
321
  };
125
322
  }
126
323
 
@@ -137,17 +334,231 @@ export class ProviderManager {
137
334
  return {};
138
335
  }
139
336
 
337
+ /** Build messages array, using raw assistant messages when available */
338
+ private buildMessages(messages: LLMMessage[]): any[] {
339
+ return messages.map((m) => {
340
+ if (m.role === "assistant" && m._raw) {
341
+ return m._raw;
342
+ }
343
+ if (m.role === "tool") {
344
+ return {
345
+ role: "tool",
346
+ tool_call_id: m.tool_call_id,
347
+ content: m.content ?? "",
348
+ };
349
+ }
350
+ return { role: m.role, content: m.content ?? "" };
351
+ });
352
+ }
353
+
354
+
355
+ /**
356
+ * Route LLM request through the TPS localhost proxy.
357
+ * The proxy holds API keys; agent authenticates with Ed25519.
358
+ */
359
+ private async completeViaProxy(request: CompletionRequest): Promise<CompletionResponse> {
360
+ const proxyUrl = this.config.proxyUrl!;
361
+ const provider = this.config.provider;
362
+ const model = this.config.model;
363
+
364
+ // Build provider-specific request body
365
+ let body: Record<string, unknown>;
366
+ let providerPath: string;
367
+
368
+ switch (provider) {
369
+ case "claude-oauth":
370
+ case "anthropic": {
371
+ providerPath = provider === "claude-oauth" ? "/proxy/claude-oauth/v1/messages" : "/proxy/anthropic/v1/messages";
372
+ const anthropicMessages = request.messages.map((m) => {
373
+ if (m._raw) return m._raw;
374
+ if (m.role === "tool") {
375
+ return {
376
+ role: "user",
377
+ content: [{
378
+ type: "tool_result",
379
+ tool_use_id: m.tool_call_id,
380
+ content: m.content ?? "",
381
+ }],
382
+ };
383
+ }
384
+ return { role: m.role, content: m.content ?? "" };
385
+ });
386
+ body = {
387
+ model,
388
+ max_tokens: request.maxTokens ?? 4096,
389
+ system: request.systemPrompt,
390
+ messages: anthropicMessages,
391
+ };
392
+ if (request.tools?.length) {
393
+ body.tools = request.tools.map((t) => ({
394
+ name: t.name,
395
+ description: t.description,
396
+ input_schema: t.input_schema,
397
+ }));
398
+ body.tool_choice = { type: "auto" };
399
+ }
400
+ break;
401
+ }
402
+ case "openai":
403
+ case "openai-oauth":
404
+ providerPath = provider === "openai-oauth"
405
+ ? "/proxy/openai-oauth/v1/chat/completions"
406
+ : "/proxy/openai/v1/chat/completions";
407
+ body = {
408
+ model,
409
+ max_tokens: request.maxTokens ?? 4096,
410
+ messages: [
411
+ ...(request.systemPrompt ? [{ role: "system", content: request.systemPrompt }] : []),
412
+ ...request.messages.map((m) => ({ role: m.role, content: m.content })),
413
+ ],
414
+ };
415
+ if (request.tools?.length) {
416
+ body.tools = request.tools.map((t) => ({
417
+ type: "function",
418
+ function: { name: t.name, description: t.description, parameters: t.input_schema },
419
+ }));
420
+ }
421
+ break;
422
+ default:
423
+ throw new Error(`Proxy not supported for provider: ${provider}. Use direct mode.`);
424
+ }
425
+
426
+ // Sign with Ed25519
427
+ const ts = Date.now().toString();
428
+ const nonce = crypto.randomUUID();
429
+ const signPayload = `${this.agentId}:${ts}:${nonce}:POST:${providerPath}`;
430
+
431
+ const keyPath = join(homedir(), ".tps", "identity", `${this.agentId}.key`);
432
+ let authHeader = "";
433
+ try {
434
+ const rawBuf = readFileSync(keyPath);
435
+ let key;
436
+ const rawStr = rawBuf.toString("utf-8").trim();
437
+ if (rawStr.startsWith("-----")) {
438
+ // PEM format
439
+ key = crypto.createPrivateKey(rawStr);
440
+ } else if (rawBuf.length === 32) {
441
+ // Raw 32-byte Ed25519 seed — wrap in PKCS8 envelope
442
+ const pkcs8Header = Buffer.from("302e020100300506032b657004220420", "hex");
443
+ key = crypto.createPrivateKey({ key: Buffer.concat([pkcs8Header, rawBuf]), format: "der", type: "pkcs8" });
444
+ } else {
445
+ // Assume base64-encoded DER/PKCS8
446
+ key = crypto.createPrivateKey({ key: Buffer.from(rawStr, "base64"), format: "der", type: "pkcs8" });
447
+ }
448
+ const sig = crypto.sign(null, Buffer.from(signPayload), key);
449
+ authHeader = `TPS-Ed25519 ${this.agentId}:${ts}:${nonce}:${sig.toString("base64")}`;
450
+ } catch {
451
+ throw new Error(`Cannot sign proxy request. Key not found at ${keyPath}`);
452
+ }
453
+
454
+ const res = await fetch(`${proxyUrl}${providerPath}`, {
455
+ method: "POST",
456
+ headers: {
457
+ "Content-Type": "application/json",
458
+ Authorization: authHeader,
459
+ },
460
+ body: JSON.stringify(body),
461
+ });
462
+
463
+ if (!res.ok) {
464
+ const text = await res.text().catch(() => "");
465
+ throw new Error(`LLM proxy error: ${res.status} ${text}`);
466
+ }
467
+
468
+ const data = await res.json() as Record<string, unknown>;
469
+
470
+ // Normalize response (proxy returns provider-native format)
471
+ if (provider === "anthropic" || provider === "claude-oauth") {
472
+ const content = (data as any).content ?? [];
473
+ const text = content.filter((b: any) => b.type === "text").map((b: any) => b.text).join("");
474
+ const toolCalls: ToolCall[] = content
475
+ .filter((b: any) => b.type === "tool_use")
476
+ .map((b: any) => ({ id: b.id, name: b.name, input: b.input }));
477
+ return {
478
+ content: text,
479
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
480
+ inputTokens: (data as any).usage?.input_tokens ?? 0,
481
+ outputTokens: (data as any).usage?.output_tokens ?? 0,
482
+ cacheReadTokens: (data as any).usage?.cache_read_input_tokens,
483
+ cacheWriteTokens: (data as any).usage?.cache_creation_input_tokens,
484
+ // Preserve raw for history — tool_use blocks must survive into next turn
485
+ rawAssistantMessage: { role: "assistant", content },
486
+ };
487
+ }
488
+
489
+ // OpenAI format
490
+ const choice = ((data as any).choices ?? [])[0];
491
+ const msg = choice?.message ?? {};
492
+ const toolCalls: ToolCall[] = (msg.tool_calls ?? []).map((tc: any) => ({
493
+ id: tc.id,
494
+ name: tc.function.name,
495
+ input: JSON.parse(tc.function.arguments ?? "{}"),
496
+ }));
497
+ return {
498
+ content: msg.content ?? "",
499
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
500
+ inputTokens: (data as any).usage?.prompt_tokens ?? 0,
501
+ outputTokens: (data as any).usage?.completion_tokens ?? 0,
502
+ };
503
+ }
504
+
140
505
  private async completeAnthropic(request: CompletionRequest): Promise<CompletionResponse> {
141
- const apiKey = this.config.apiKey ?? process.env.ANTHROPIC_API_KEY;
506
+ let apiKey = this.config.apiKey ?? process.env.ANTHROPIC_API_KEY;
507
+
508
+ if (this.config.auth === "oauth") {
509
+ const oauth = loadOAuth("anthropic");
510
+ if (!oauth) {
511
+ throw new Error("Anthropic OAuth not configured. Run: tps auth login anthropic");
512
+ }
513
+ let current = oauth;
514
+ if (Date.now() > oauth.expiresAt - 5 * 60_000) {
515
+ current = await refreshAnthropicOAuthToken(oauth);
516
+ saveOAuth("anthropic", current);
517
+ }
518
+ apiKey = current.accessToken;
519
+ }
520
+
142
521
  if (!apiKey) throw new Error("ANTHROPIC_API_KEY not set");
143
522
 
523
+ // Cache-aware system prompt (multi-block with breakpoint)
524
+ const system = request.systemPrompt
525
+ ? [{ type: "text", text: request.systemPrompt, cache_control: { type: "ephemeral" } }]
526
+ : undefined;
527
+
528
+ // Cache breakpoint on last tool only
529
+ const tools = this.toolSetForAnthropic(request.tools) as any[];
530
+ if (tools.length > 0) {
531
+ tools[tools.length - 1] = {
532
+ ...tools[tools.length - 1],
533
+ cache_control: { type: "ephemeral" },
534
+ };
535
+ }
536
+
537
+ // Use raw assistant messages for Anthropic format compliance
538
+ const messages = request.messages.map((m) => {
539
+ if (m.role === "assistant" && m._raw) return m._raw;
540
+ if (m.role === "tool") {
541
+ return {
542
+ role: "user",
543
+ content: [{
544
+ type: "tool_result",
545
+ tool_use_id: m.tool_call_id,
546
+ content: m.content ?? "",
547
+ }],
548
+ };
549
+ }
550
+ return { role: m.role, content: m.content ?? "" };
551
+ });
552
+
144
553
  const body = {
145
554
  model: this.config.model,
146
- max_tokens: request.maxTokens ?? 2048,
147
- system: request.systemPrompt,
148
- messages: request.messages,
149
- tools: this.toolSetForAnthropic(request.tools),
150
- tool_choice: request.toolChoice ?? "auto",
555
+ max_tokens: request.maxTokens ?? 4096,
556
+ system,
557
+ messages,
558
+ tools,
559
+ tool_choice: request.toolChoice === "required"
560
+ ? { type: "any" }
561
+ : { type: "auto" },
151
562
  };
152
563
 
153
564
  const res = await fetch("https://api.anthropic.com/v1/messages", {
@@ -169,15 +580,34 @@ export class ProviderManager {
169
580
  }
170
581
 
171
582
  private async completeGoogle(request: CompletionRequest): Promise<CompletionResponse> {
172
- const apiKey = this.config.apiKey ?? process.env.GOOGLE_API_KEY;
173
- if (!apiKey) throw new Error("GOOGLE_API_KEY not set");
583
+ let authHeader: string | undefined;
584
+ let url = `https://generativelanguage.googleapis.com/v1beta/models/${this.config.model}:generateContent`;
585
+
586
+ if (this.config.auth === "oauth") {
587
+ const oauth = loadOAuth("google");
588
+ if (!oauth) {
589
+ throw new Error("Google OAuth not configured. Run: tps auth login google");
590
+ }
591
+ let current = oauth;
592
+ if (Date.now() > oauth.expiresAt - 5 * 60_000) {
593
+ current = await refreshGoogleOAuthToken(oauth);
594
+ saveOAuth("google", current);
595
+ }
596
+ authHeader = `Bearer ${current.accessToken}`;
597
+ } else {
598
+ const apiKey = this.config.apiKey ?? process.env.GOOGLE_API_KEY;
599
+ if (!apiKey) throw new Error("GOOGLE_API_KEY not set");
600
+ url = `${url}?key=${apiKey}`;
601
+ }
174
602
 
175
- const url = `https://generativelanguage.googleapis.com/v1beta/models/${this.config.model}:generateContent?key=${apiKey}`;
176
603
  const toolPayload = this.toolSetForGoogle(request.tools);
177
604
 
178
605
  const res = await fetch(url, {
179
606
  method: "POST",
180
- headers: { "Content-Type": "application/json" },
607
+ headers: {
608
+ "Content-Type": "application/json",
609
+ ...(authHeader ? { Authorization: authHeader } : {}),
610
+ },
181
611
  body: JSON.stringify({
182
612
  systemInstruction: request.systemPrompt
183
613
  ? { parts: [{ text: request.systemPrompt }] }
@@ -217,6 +647,8 @@ export class ProviderManager {
217
647
  toolCalls: toolCalls.length ? toolCalls : undefined,
218
648
  inputTokens: data?.usageMetadata?.promptTokenCount ?? 0,
219
649
  outputTokens: data?.usageMetadata?.candidatesTokenCount ?? 0,
650
+ cacheReadTokens: data?.usageMetadata?.cachedContentTokenCount ?? 0,
651
+ rawAssistantMessage: candidate?.content,
220
652
  };
221
653
  }
222
654
 
@@ -8,17 +8,39 @@ import { ContextManager } from "../io/context.js";
8
8
  import { ProviderManager } from "../llm/provider.js";
9
9
  import { BoundaryManager } from "../governance/boundary.js";
10
10
  import { createDefaultToolset } from "../tools/index.js";
11
+ import { EventLogger } from "../telemetry/events.js";
12
+ import { FlairContextProvider } from "../io/flair.js";
13
+ import type { FlairClient } from "../lib/signEnvelope.js";
11
14
 
12
15
  export class AgentRuntime {
13
16
  private loop: EventLoop;
14
17
  private readonly mail: MailClient;
15
18
  private readonly boundary: BoundaryManager;
19
+ private readonly flair: FlairContextProvider | null;
16
20
 
17
21
  constructor(public readonly config: AgentConfig) {
18
- const mail = new MailClient(config.mailDir);
22
+ const events = new EventLogger(
23
+ config.agentId,
24
+ join(config.workspace, ".tps", "events"),
25
+ );
26
+ this.flair = config.flair ? new FlairContextProvider(config.agentId, config.flair) : null;
27
+
28
+ // Build FlairClient adapter for envelope verification
29
+ let flairClient: FlairClient | undefined;
30
+ if (this.flair) {
31
+ flairClient = {
32
+ getAgent: async (name: string) => {
33
+ const a = await this.flair!.getAgent(name);
34
+ if (!a) return null;
35
+ return { publicKey: Buffer.from(a.publicKey, "hex") };
36
+ },
37
+ };
38
+ }
39
+
40
+ const mail = new MailClient(config.mailDir, events, config.agentId, flairClient);
19
41
  const memory = new MemoryStore(config.memoryPath);
20
42
  const context = new ContextManager(memory, config.contextWindowTokens ?? 8000);
21
- const provider = new ProviderManager(config.llm);
43
+ const provider = new ProviderManager(config.llm, events, config.agentId);
22
44
 
23
45
  this.mail = mail;
24
46
  this.boundary = new BoundaryManager(config.workspace);
@@ -29,11 +51,17 @@ export class AgentRuntime {
29
51
  execAllowlist: config.execAllowlist,
30
52
  });
31
53
 
32
- this.loop = new EventLoop({ config, memory, context, provider, tools });
54
+ const flairContext = this.flair
55
+ ? (query: string) => this.flair!.buildContextBlock(query)
56
+ : undefined;
57
+ this.loop = new EventLoop({ config, memory, context, provider, tools, events, flairContext, mailClient: mail });
33
58
  }
34
59
 
35
60
  async start(): Promise<void> {
36
61
  const checkInbox = async () => this.mail.checkNewMail();
62
+ const deliverOutbox = () => this.mail.deliverOutbox();
63
+
64
+
37
65
  const pidPath = join(this.config.workspace, ".tps-agent.pid");
38
66
  mkdirSync(dirname(pidPath), { recursive: true });
39
67
  writeFileSync(pidPath, `${process.pid}\n`, "utf-8");
@@ -59,9 +87,33 @@ export class AgentRuntime {
59
87
  }
60
88
 
61
89
  async runOnce(message: string): Promise<void> {
90
+ if (this.flair) {
91
+ // Inject Flair context as a system prompt supplement
92
+ try {
93
+ const ctx = await this.flair.buildContextBlock(message.slice(0, 200));
94
+ if (ctx) {
95
+ await this.loop.runOnce(`${message}
96
+
97
+ [Flair Context]
98
+ ${ctx}`);
99
+ return;
100
+ }
101
+ } catch {
102
+ // Fall through to normal path
103
+ }
104
+ }
62
105
  await this.loop.runOnce(message);
63
106
  }
64
107
 
108
+ async writeConversationMemory(id: string, content: string): Promise<void> {
109
+ if (!this.flair) return;
110
+ try {
111
+ await this.flair.writeMemory(id, content, "conversation");
112
+ } catch {
113
+ // Non-fatal — local memory still works
114
+ }
115
+ }
116
+
65
117
  getState(): string {
66
118
  return this.loop.getState();
67
119
  }