@blockrun/franklin 3.32.1 → 3.34.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 (97) hide show
  1. package/README.md +23 -2
  2. package/dist/agent/approvals.d.ts +47 -0
  3. package/dist/agent/approvals.js +66 -0
  4. package/dist/agent/commands.js +230 -7
  5. package/dist/agent/compact.js +1 -1
  6. package/dist/agent/context.js +1 -1
  7. package/dist/agent/input-queue.d.ts +26 -0
  8. package/dist/agent/input-queue.js +65 -0
  9. package/dist/agent/loop.js +198 -5
  10. package/dist/agent/optimize.js +1 -1
  11. package/dist/agent/streaming-executor.d.ts +4 -0
  12. package/dist/agent/streaming-executor.js +52 -0
  13. package/dist/agent/tokens.js +2 -0
  14. package/dist/agent/tool-guard.d.ts +7 -0
  15. package/dist/agent/tool-guard.js +21 -0
  16. package/dist/agent/types.d.ts +26 -0
  17. package/dist/audit/approvals.d.ts +20 -0
  18. package/dist/audit/approvals.js +21 -0
  19. package/dist/commands/init.js +1 -1
  20. package/dist/commands/models.d.ts +11 -0
  21. package/dist/commands/models.js +157 -37
  22. package/dist/commands/start.d.ts +10 -1
  23. package/dist/commands/start.js +53 -1
  24. package/dist/events/types.d.ts +38 -1
  25. package/dist/gateway-models.d.ts +14 -2
  26. package/dist/gateway-models.js +8 -0
  27. package/dist/goal/engine.d.ts +39 -0
  28. package/dist/goal/engine.js +182 -0
  29. package/dist/goal/prompts.d.ts +16 -0
  30. package/dist/goal/prompts.js +206 -0
  31. package/dist/goal/runtime.d.ts +20 -0
  32. package/dist/goal/runtime.js +110 -0
  33. package/dist/goal/store.d.ts +22 -0
  34. package/dist/goal/store.js +79 -0
  35. package/dist/goal/types.d.ts +63 -0
  36. package/dist/goal/types.js +26 -0
  37. package/dist/hooks/loader.d.ts +19 -0
  38. package/dist/hooks/loader.js +115 -0
  39. package/dist/hooks/runner.d.ts +31 -0
  40. package/dist/hooks/runner.js +147 -0
  41. package/dist/hooks/types.d.ts +64 -0
  42. package/dist/hooks/types.js +35 -0
  43. package/dist/index.js +5 -1
  44. package/dist/learnings/extractor.js +1 -1
  45. package/dist/memory/capture.d.ts +40 -0
  46. package/dist/memory/capture.js +95 -0
  47. package/dist/memory/dream.d.ts +24 -0
  48. package/dist/memory/dream.js +147 -0
  49. package/dist/memory/indexer.d.ts +29 -0
  50. package/dist/memory/indexer.js +144 -0
  51. package/dist/memory/store.d.ts +50 -0
  52. package/dist/memory/store.js +163 -0
  53. package/dist/monitors/registry.d.ts +42 -0
  54. package/dist/monitors/registry.js +104 -0
  55. package/dist/panel/html.js +299 -0
  56. package/dist/panel/server.js +41 -0
  57. package/dist/pricing.js +4 -1
  58. package/dist/router/index.js +15 -9
  59. package/dist/router/vision.js +5 -4
  60. package/dist/scheduler/service.d.ts +24 -0
  61. package/dist/scheduler/service.js +44 -0
  62. package/dist/scheduler/store.d.ts +26 -0
  63. package/dist/scheduler/store.js +116 -0
  64. package/dist/scheduler/types.d.ts +36 -0
  65. package/dist/scheduler/types.js +31 -0
  66. package/dist/serve/agent-host.d.ts +63 -0
  67. package/dist/serve/agent-host.js +270 -0
  68. package/dist/serve/server.js +131 -2
  69. package/dist/session/live-registry.d.ts +32 -0
  70. package/dist/session/live-registry.js +83 -0
  71. package/dist/session/search.d.ts +6 -0
  72. package/dist/session/search.js +3 -3
  73. package/dist/session/storage.d.ts +6 -0
  74. package/dist/session/storage.js +6 -0
  75. package/dist/tools/goal.d.ts +7 -0
  76. package/dist/tools/goal.js +29 -0
  77. package/dist/tools/index.js +11 -0
  78. package/dist/tools/memory.js +14 -4
  79. package/dist/tools/moa.js +1 -1
  80. package/dist/tools/monitor.d.ts +11 -0
  81. package/dist/tools/monitor.js +96 -0
  82. package/dist/tools/scheduler.d.ts +12 -0
  83. package/dist/tools/scheduler.js +79 -0
  84. package/dist/tools/spend-tools.d.ts +33 -0
  85. package/dist/tools/spend-tools.js +114 -0
  86. package/dist/tools/tool-categories.js +7 -0
  87. package/dist/tools/trade-plan.d.ts +11 -0
  88. package/dist/tools/trade-plan.js +137 -0
  89. package/dist/tools/trading-execute.js +24 -0
  90. package/dist/trading/trade-plan.d.ts +75 -0
  91. package/dist/trading/trade-plan.js +290 -0
  92. package/dist/ui/app.js +54 -9
  93. package/dist/ui/model-picker.d.ts +40 -0
  94. package/dist/ui/model-picker.js +135 -25
  95. package/package.json +2 -2
  96. package/dist/agent/media-router.d.ts +0 -98
  97. package/dist/agent/media-router.js +0 -328
@@ -1 +1,12 @@
1
+ /**
2
+ * Compact USD — keeps sub-cent prices honest ($0.435/M must not round to
3
+ * $0.44). Exported for tests.
4
+ */
5
+ export declare function money(n: number): string;
6
+ /**
7
+ * 1000000 → 1M, 1048576 → 1M, 1050000 → 1.1M, 262144 → 262K.
8
+ * Both 1000000 and 1048576 are "1M context" to a reader — don't render one as
9
+ * `1M` and the other as `1.0M` in the same column. Exported for tests.
10
+ */
11
+ export declare function formatContext(n: number | undefined): string;
1
12
  export declare function modelsCommand(): Promise<void>;
@@ -1,56 +1,176 @@
1
1
  import chalk from 'chalk';
2
2
  import { loadChain, API_URLS } from '../config.js';
3
+ import { getGatewayModels, GATEWAY_MARGIN, } from '../gateway-models.js';
4
+ /**
5
+ * `franklin models` — the live catalog.
6
+ *
7
+ * Reuses gateway-models.ts rather than re-fetching: it already types every
8
+ * billing mode, caches for 5 minutes, and serves stale-on-error.
9
+ *
10
+ * The old version modelled pricing as `{ input, output }` for every model and
11
+ * printed `$0.00/M` for anything that isn't token-metered — so the entire
12
+ * image/video/music/speech catalog rendered as free under a "Paid Models"
13
+ * heading. The gateway actually bills seven different ways, and each needs its
14
+ * own unit; that's what BILLING_GROUPS below encodes.
15
+ */
16
+ const RULE_WIDTH = 74;
17
+ /**
18
+ * Compact USD — keeps sub-cent prices honest ($0.435/M must not round to
19
+ * $0.44). Exported for tests.
20
+ */
21
+ export function money(n) {
22
+ if (n === 0)
23
+ return '$0';
24
+ const decimals = n < 0.01 ? 4 : n < 1 ? 3 : 2;
25
+ return `$${n.toFixed(decimals).replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '')}`;
26
+ }
27
+ /**
28
+ * 1000000 → 1M, 1048576 → 1M, 1050000 → 1.1M, 262144 → 262K.
29
+ * Both 1000000 and 1048576 are "1M context" to a reader — don't render one as
30
+ * `1M` and the other as `1.0M` in the same column. Exported for tests.
31
+ */
32
+ export function formatContext(n) {
33
+ if (!n)
34
+ return '';
35
+ if (n >= 1_000_000)
36
+ return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`;
37
+ return `${Math.round(n / 1000)}K`;
38
+ }
39
+ function pricingOf(m) {
40
+ return m.pricing;
41
+ }
42
+ // Ordered as printed. `free` and `paid` are handled separately — free gets its
43
+ // own promoted section, and paid is the only one with an Input/Output/Context
44
+ // table rather than a single price column.
45
+ const BILLING_GROUPS = [
46
+ {
47
+ mode: 'per_image',
48
+ heading: 'Image generation (per image)',
49
+ render: m => `${money(pricingOf(m).per_image ?? 0)}/image`,
50
+ },
51
+ {
52
+ mode: 'per_second',
53
+ heading: 'Video generation (per second)',
54
+ render: m => {
55
+ const p = pricingOf(m);
56
+ const per = p.per_second ?? 0;
57
+ const def = p.default_duration_seconds;
58
+ const max = p.max_duration_seconds;
59
+ const parts = [`${money(per)}/sec`];
60
+ if (def)
61
+ parts.push(`${def}s default ≈ ${money(per * def)}`);
62
+ if (max)
63
+ parts.push(`max ${max}s`);
64
+ return parts.join(' · ');
65
+ },
66
+ },
67
+ {
68
+ mode: 'per_character',
69
+ heading: 'Speech / TTS (per 1K characters)',
70
+ render: m => {
71
+ const p = pricingOf(m);
72
+ const s = `${money(p.per_1k_chars ?? 0)}/1K chars`;
73
+ return p.max_input_chars ? `${s} · max ${formatContext(p.max_input_chars)} chars` : s;
74
+ },
75
+ },
76
+ {
77
+ mode: 'per_track',
78
+ heading: 'Music (per track)',
79
+ render: m => `${money(pricingOf(m).per_track ?? 0)}/track`,
80
+ },
81
+ {
82
+ mode: 'per_generation',
83
+ heading: 'Sound effects (per generation)',
84
+ render: m => {
85
+ const p = pricingOf(m);
86
+ const s = `${money(p.per_generation ?? 0)}/generation`;
87
+ return p.max_duration_seconds ? `${s} · max ${p.max_duration_seconds}s` : s;
88
+ },
89
+ },
90
+ {
91
+ mode: 'flat',
92
+ heading: 'Flat rate (per call)',
93
+ render: m => `${money(pricingOf(m).flat ?? 0)}/call`,
94
+ },
95
+ ];
96
+ function printSection(heading, models, render) {
97
+ if (models.length === 0)
98
+ return;
99
+ console.log(chalk.yellow.bold(heading));
100
+ console.log(chalk.dim('─'.repeat(RULE_WIDTH)));
101
+ for (const m of models) {
102
+ console.log(` ${chalk.cyan(m.id.padEnd(44))} ${render(m)}`);
103
+ }
104
+ console.log('');
105
+ }
3
106
  export async function modelsCommand() {
4
107
  const chain = loadChain();
5
108
  const apiUrl = API_URLS[chain];
6
109
  console.log(chalk.bold('Available Models\n'));
7
110
  console.log(`Chain: ${chalk.magenta(chain)} — ${chalk.dim(apiUrl)}\n`);
111
+ let models;
8
112
  try {
9
- const controller = new AbortController();
10
- const timeout = setTimeout(() => controller.abort(), 15_000);
11
- const response = await fetch(`${apiUrl}/v1/models`, { signal: controller.signal });
12
- clearTimeout(timeout);
13
- if (!response.ok) {
14
- console.log(chalk.red(`Failed to fetch models: ${response.status}`));
15
- return;
16
- }
17
- const data = (await response.json());
18
- if (!data.data || data.data.length === 0) {
19
- console.log(chalk.yellow('No models returned from API.'));
20
- return;
21
- }
22
- const models = data.data
23
- .sort((a, b) => (a.pricing?.input ?? 0) - (b.pricing?.input ?? 0));
24
- const free = models.filter((m) => m.billing_mode === 'free');
25
- const paid = models.filter((m) => m.billing_mode !== 'free');
26
- if (free.length > 0) {
27
- console.log(chalk.green.bold('Free Models (no USDC needed)'));
28
- console.log(chalk.dim('─'.repeat(70)));
29
- for (const m of free) {
30
- console.log(` ${chalk.cyan(m.id)}`);
31
- }
32
- console.log('');
33
- }
34
- console.log(chalk.yellow.bold('Paid Models'));
35
- console.log(chalk.dim('─'.repeat(70)));
36
- console.log(chalk.dim(` ${'Model'.padEnd(35)} ${'Input'.padEnd(12)} ${'Output'.padEnd(12)} Context`));
37
- console.log(chalk.dim('─'.repeat(70)));
38
- for (const m of paid) {
39
- const input = `$${(m.pricing?.input ?? 0).toFixed(2)}/M`;
40
- const output = `$${(m.pricing?.output ?? 0).toFixed(2)}/M`;
41
- const ctx = '';
42
- console.log(` ${chalk.cyan(m.id.padEnd(35))} ${input.padEnd(12)} ${output.padEnd(12)} ${ctx}`);
43
- }
44
- console.log(`\n${chalk.dim(`${models.length} models available. Use:`)} ${chalk.bold('franklin start --model <model-id>')}`);
113
+ models = await getGatewayModels();
45
114
  }
46
115
  catch (err) {
47
116
  const msg = err instanceof Error ? err.message : 'unknown error';
48
- if (msg.includes('fetch') || msg.includes('ECONNREFUSED') || msg.includes('ENOTFOUND')) {
117
+ if (/fetch|ECONNREFUSED|ENOTFOUND|abort/i.test(msg)) {
49
118
  console.log(chalk.red(`Cannot reach BlockRun API at ${apiUrl}`));
50
119
  console.log(chalk.dim('Check your internet connection or try again later.'));
51
120
  }
52
121
  else {
53
122
  console.log(chalk.red(`Error: ${msg}`));
54
123
  }
124
+ return;
125
+ }
126
+ if (models.length === 0) {
127
+ console.log(chalk.yellow('No models returned from API.'));
128
+ return;
129
+ }
130
+ // Free first — it's the "no USDC needed" on-ramp and the reason many people
131
+ // install Franklin at all.
132
+ const free = models.filter(m => m.billing_mode === 'free');
133
+ if (free.length > 0) {
134
+ console.log(chalk.green.bold('Free Models (no USDC needed)'));
135
+ console.log(chalk.dim('─'.repeat(RULE_WIDTH)));
136
+ for (const m of free) {
137
+ const ctx = formatContext(m.context_window);
138
+ console.log(` ${chalk.cyan(m.id.padEnd(44))} ${chalk.dim(ctx ? `${ctx} ctx` : '')}`);
139
+ }
140
+ console.log('');
141
+ }
142
+ // Token-metered — the only group with a two-price table.
143
+ const paid = models
144
+ .filter(m => m.billing_mode === 'paid')
145
+ .sort((a, b) => {
146
+ const ap = a.pricing;
147
+ const bp = b.pricing;
148
+ return (ap.input ?? 0) - (bp.input ?? 0);
149
+ });
150
+ if (paid.length > 0) {
151
+ console.log(chalk.yellow.bold('Chat & Reasoning (per 1M tokens)'));
152
+ console.log(chalk.dim('─'.repeat(RULE_WIDTH)));
153
+ console.log(chalk.dim(` ${'Model'.padEnd(44)} ${'Input'.padEnd(11)} ${'Output'.padEnd(11)} Context`));
154
+ console.log(chalk.dim('─'.repeat(RULE_WIDTH)));
155
+ for (const m of paid) {
156
+ const p = pricingOf(m);
157
+ const input = `${money(p.input ?? 0)}/M`;
158
+ const output = `${money(p.output ?? 0)}/M`;
159
+ console.log(` ${chalk.cyan(m.id.padEnd(44))} ${input.padEnd(11)} ${output.padEnd(11)} ${chalk.dim(formatContext(m.context_window))}`);
160
+ }
161
+ console.log('');
162
+ }
163
+ for (const group of BILLING_GROUPS) {
164
+ const inGroup = models.filter(m => m.billing_mode === group.mode);
165
+ printSection(group.heading, inGroup, group.render);
55
166
  }
167
+ // Anything the gateway starts billing a way this build doesn't know about
168
+ // must still be listed — silently dropping a model is how the $0.00/M bug
169
+ // stayed invisible. Show it with its raw pricing rather than a wrong unit.
170
+ const known = new Set(['free', 'paid', ...BILLING_GROUPS.map(g => g.mode)]);
171
+ const unknown = models.filter(m => !known.has(m.billing_mode));
172
+ printSection('Other billing modes (not yet modelled by this Franklin build)', unknown, m => chalk.dim(`${m.billing_mode}: ${JSON.stringify(m.pricing)}`));
173
+ const margin = Math.round((GATEWAY_MARGIN - 1) * 100);
174
+ console.log(chalk.dim(`${models.length} models available. Prices are gateway list — x402 settlement adds ~${margin}%.`));
175
+ console.log(`${chalk.dim('Use:')} ${chalk.bold('franklin start --model <model-id>')}`);
56
176
  }
@@ -1,4 +1,4 @@
1
- import type { StreamTurnDone } from '../agent/types.js';
1
+ import type { AgentConfig, StreamTurnDone } from '../agent/types.js';
2
2
  interface StartOptions {
3
3
  model?: string;
4
4
  debug?: boolean;
@@ -16,7 +16,16 @@ interface StartOptions {
16
16
  maxSpend?: string | number;
17
17
  /** Run a single prompt non-interactively, then exit. For batch/scripted use. */
18
18
  prompt?: string;
19
+ /** Non-interactive runs: auto-approve trade plans that fit --max-spend. */
20
+ approveTrades?: boolean;
19
21
  }
20
22
  export declare function startCommand(options: StartOptions): Promise<void>;
21
23
  export declare function oneShotExitCodeForTurnReason(reason: StreamTurnDone['reason']): number;
24
+ /**
25
+ * Headless approval policy. No human is present, so:
26
+ * - without --approve-trades: every trade plan is denied
27
+ * - with it: auto-approve only when the plan total fits what's left of the
28
+ * --max-spend envelope (no flag combination bypasses --max-spend)
29
+ */
30
+ export declare function createHeadlessApprovalFn(approveTrades: boolean, maxSpendUsd?: number): NonNullable<AgentConfig['approvalPromptFn']>;
22
31
  export {};
@@ -4,7 +4,7 @@ import path from 'node:path';
4
4
  import { getOrCreateWallet, getOrCreateSolanaWallet } from '@blockrun/llm';
5
5
  import { BLOCKRUN_DIR, loadChain, API_URLS } from '../config.js';
6
6
  import { retryFetchBalance } from './balance-retry.js';
7
- import { flushStats, loadStats } from '../stats/tracker.js';
7
+ import { flushStats, loadStats, getLiveSpendUsd } from '../stats/tracker.js';
8
8
  import { OPUS_PRICING } from '../pricing.js';
9
9
  import { loadConfig } from './config.js';
10
10
  import { printBanner } from '../banner.js';
@@ -374,6 +374,15 @@ export async function startCommand(options) {
374
374
  ? { maxSpendUsd: Number(options.maxSpend) }
375
375
  : {}),
376
376
  };
377
+ // Non-interactive runs get the headless approval policy: trades fail
378
+ // closed unless --approve-trades was granted, and even then only within
379
+ // the remaining --max-spend envelope. Interactive TUI overrides this
380
+ // below with a real prompt.
381
+ if (options.prompt || !process.stdin.isTTY) {
382
+ agentConfig.approvalPromptFn = createHeadlessApprovalFn(options.approveTrades === true, agentConfig.maxSpendUsd);
383
+ // A goal must never extend a bounded scripted run past its single prompt.
384
+ agentConfig.autoContinueGoals = false;
385
+ }
377
386
  // Bootstrap learnings from existing CLAUDE.md on first run (async, non-blocking)
378
387
  Promise.all([
379
388
  import('../learnings/extractor.js'),
@@ -399,6 +408,34 @@ export async function startCommand(options) {
399
408
  export function oneShotExitCodeForTurnReason(reason) {
400
409
  return reason === 'completed' ? 0 : 1;
401
410
  }
411
+ /**
412
+ * Headless approval policy. No human is present, so:
413
+ * - without --approve-trades: every trade plan is denied
414
+ * - with it: auto-approve only when the plan total fits what's left of the
415
+ * --max-spend envelope (no flag combination bypasses --max-spend)
416
+ */
417
+ export function createHeadlessApprovalFn(approveTrades, maxSpendUsd) {
418
+ return async (req) => {
419
+ if (req.kind !== 'trade-plan') {
420
+ return { choice: 'deny', message: 'non-interactive run' };
421
+ }
422
+ if (!approveTrades) {
423
+ return { choice: 'deny', message: 'non-interactive run without --approve-trades' };
424
+ }
425
+ const plan = req.payload;
426
+ const total = typeof plan?.totalSpendUsd === 'number' ? plan.totalSpendUsd : Number.POSITIVE_INFINITY;
427
+ if (maxSpendUsd != null && maxSpendUsd > 0) {
428
+ const remaining = maxSpendUsd - getLiveSpendUsd();
429
+ if (total > remaining) {
430
+ return {
431
+ choice: 'deny',
432
+ message: `plan total $${total.toFixed(2)} exceeds remaining --max-spend envelope $${Math.max(0, remaining).toFixed(2)}`,
433
+ };
434
+ }
435
+ }
436
+ return { choice: 'approve', message: 'auto' };
437
+ };
438
+ }
402
439
  async function runOneShot(agentConfig, prompt) {
403
440
  let delivered = false;
404
441
  let exitCode = 0;
@@ -482,6 +519,21 @@ async function runWithInkUI(agentConfig, model, workDir, version, walletInfo, on
482
519
  // immediately and auto-denied every permission. Now y/n/a goes through useInput.
483
520
  agentConfig.permissionPromptFn = (toolName, description) => ui.requestPermission(toolName, description);
484
521
  agentConfig.onAskUser = (question, options) => ui.requestAskUser(question, options);
522
+ // Structured approvals (trade plans) render through the ask-user modal:
523
+ // the full plan card as the question, decision keywords as the options.
524
+ // A free-text reply that isn't a listed option is treated as a change
525
+ // request so the user can type feedback directly.
526
+ agentConfig.approvalPromptFn = async (req) => {
527
+ const answer = (await ui.requestAskUser(`${req.description}\n\nDecision?`, req.options)).trim();
528
+ const norm = answer.toLowerCase();
529
+ if (norm === 'approve' || norm === 'deny')
530
+ return { choice: norm };
531
+ if (norm === 'request changes') {
532
+ const msg = await ui.requestAskUser('What should change about this plan?');
533
+ return { choice: 'request changes', message: msg };
534
+ }
535
+ return { choice: 'request changes', message: answer };
536
+ };
485
537
  agentConfig.onModelChange = (model) => ui.updateModel(model);
486
538
  let activeSessionId = agentConfig.resumeSessionId;
487
539
  agentConfig.onSessionStart = (sessionId) => { activeSessionId = sessionId; };
@@ -45,5 +45,42 @@ export interface BudgetExceededEvent extends BaseEvent {
45
45
  blockedAction: string;
46
46
  };
47
47
  }
48
- export type FranklinEvent = SignalDetectedEvent | PostPublishedEvent | MentionReceivedEvent | BudgetExceededEvent;
48
+ export type AgentRunState = 'working' | 'idle' | 'needs-input' | 'completed' | 'failed';
49
+ export interface AgentStateEvent extends BaseEvent {
50
+ type: 'agent.state';
51
+ data: {
52
+ sessionId: string;
53
+ state: AgentRunState;
54
+ label: string;
55
+ model: string;
56
+ };
57
+ }
58
+ export interface AgentTurnEvent extends BaseEvent {
59
+ type: 'agent.turn';
60
+ data: {
61
+ sessionId: string;
62
+ phase: 'start' | 'done';
63
+ reason?: string;
64
+ };
65
+ }
66
+ export interface ApprovalRequestedEvent extends BaseEvent {
67
+ type: 'approval.requested';
68
+ data: {
69
+ sessionId: string;
70
+ requestId: string;
71
+ kind: string;
72
+ title: string;
73
+ options: string[];
74
+ };
75
+ }
76
+ export interface ApprovalResolvedEvent extends BaseEvent {
77
+ type: 'approval.resolved';
78
+ data: {
79
+ sessionId: string;
80
+ requestId: string;
81
+ choice: string;
82
+ by: string;
83
+ };
84
+ }
85
+ export type FranklinEvent = SignalDetectedEvent | PostPublishedEvent | MentionReceivedEvent | BudgetExceededEvent | AgentStateEvent | AgentTurnEvent | ApprovalRequestedEvent | ApprovalResolvedEvent;
49
86
  export declare function makeEvent<T extends FranklinEvent>(props: Omit<T, 'id' | 'ts'>): T;
@@ -13,7 +13,7 @@
13
13
  * so actual charge = base * 1.05 (confirmed against a live 402 response
14
14
  * on seedance-2.0-fast: 5s × $0.15 × 1.05 = $0.7875).
15
15
  */
16
- export type BillingMode = 'paid' | 'free' | 'flat' | 'per_image' | 'per_second' | 'per_track';
16
+ export type BillingMode = 'paid' | 'free' | 'flat' | 'per_image' | 'per_second' | 'per_track' | 'per_character' | 'per_generation';
17
17
  export interface PaidPricing {
18
18
  input: number;
19
19
  output: number;
@@ -32,7 +32,17 @@ export interface PerSecondPricing {
32
32
  export interface PerTrackPricing {
33
33
  per_track: number;
34
34
  }
35
- export type ModelPricing = PaidPricing | FlatPricing | PerImagePricing | PerSecondPricing | PerTrackPricing;
35
+ /** ElevenLabs / ByteDance speech — billed per 1K characters of input text. */
36
+ export interface PerCharacterPricing {
37
+ per_1k_chars: number;
38
+ max_input_chars?: number;
39
+ }
40
+ /** ElevenLabs sound effects — flat charge per generation. */
41
+ export interface PerGenerationPricing {
42
+ per_generation: number;
43
+ max_duration_seconds?: number;
44
+ }
45
+ export type ModelPricing = PaidPricing | FlatPricing | PerImagePricing | PerSecondPricing | PerTrackPricing | PerCharacterPricing | PerGenerationPricing;
36
46
  export interface GatewayModel {
37
47
  id: string;
38
48
  name: string;
@@ -63,6 +73,8 @@ export interface EstimateContext {
63
73
  quantity?: number;
64
74
  /** Clip length in seconds (per_second). Falls back to model's default_duration_seconds, then 8. */
65
75
  duration_seconds?: number;
76
+ /** Input text length (per_character). Required for a meaningful speech estimate. */
77
+ characters?: number;
66
78
  }
67
79
  /**
68
80
  * Estimated USD charge to generate one response from this model under the
@@ -108,6 +108,14 @@ export function estimateCostUsd(model, ctx = {}) {
108
108
  case 'per_track':
109
109
  base = p.per_track ?? 0;
110
110
  break;
111
+ case 'per_character':
112
+ // Priced per 1K characters of input text. Without a length there's no
113
+ // meaningful estimate, so fall through to 0 rather than invent one.
114
+ base = ((p.per_1k_chars ?? 0) * (ctx.characters ?? 0)) / 1000;
115
+ break;
116
+ case 'per_generation':
117
+ base = p.per_generation ?? 0;
118
+ break;
111
119
  case 'flat':
112
120
  base = p.flat ?? 0;
113
121
  break;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Goal-engine role runners: planner, adversarial verifier panel,
3
+ * strategist, summarizer. Role calls are ordinary model completions (all
4
+ * recorded via recordUsage so /cost and --max-spend see them); verifiers
5
+ * additionally run a bounded read-only tool loop so they can AUDIT the
6
+ * implementer's evidence rather than take its word.
7
+ */
8
+ import { ModelClient } from '../agent/llm.js';
9
+ import type { CapabilityHandler } from '../agent/types.js';
10
+ import type { GoalKind, GoalState, VerifierVerdict } from './types.js';
11
+ export interface GoalEngineContext {
12
+ client: ModelClient;
13
+ model: string;
14
+ capabilities: CapabilityHandler[];
15
+ workingDir: string;
16
+ signal: AbortSignal;
17
+ onProgress?: (text: string) => void;
18
+ }
19
+ /** Lightweight kind detection — the plan template diverges per kind. */
20
+ export declare function detectGoalKind(objective: string): GoalKind;
21
+ export declare function runPlanner(ctx: GoalEngineContext, objective: string): Promise<{
22
+ kind: GoalKind;
23
+ planMd: string;
24
+ }>;
25
+ export declare function parseVerdict(text: string): VerifierVerdict | null;
26
+ export interface PanelOutcome {
27
+ refuted: boolean;
28
+ gaps: string[];
29
+ blocking: 'none' | 'contradiction' | 'unverifiable';
30
+ verdicts: VerifierVerdict[];
31
+ }
32
+ export declare function runVerifierPanel(ctx: GoalEngineContext, goal: GoalState, planMd: string, claimMessage: string): Promise<PanelOutcome>;
33
+ /** Whack-a-mole detector: the last three rounds all refuted with materially
34
+ * different gap sets (no shared gap between consecutive rounds). */
35
+ export declare function needsStrategist(goal: GoalState): boolean;
36
+ export declare function runStrategist(ctx: GoalEngineContext, goal: GoalState, planMd: string): Promise<string>;
37
+ export declare function runSummarizer(ctx: GoalEngineContext, goal: GoalState, planMd: string): Promise<string>;
38
+ /** First unchecked checklist item — the per-turn nudge. */
39
+ export declare function mineNextStep(planMd: string): string | undefined;
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Goal-engine role runners: planner, adversarial verifier panel,
3
+ * strategist, summarizer. Role calls are ordinary model completions (all
4
+ * recorded via recordUsage so /cost and --max-spend see them); verifiers
5
+ * additionally run a bounded read-only tool loop so they can AUDIT the
6
+ * implementer's evidence rather than take its word.
7
+ */
8
+ import { recordUsage } from '../stats/tracker.js';
9
+ import { estimateCost } from '../pricing.js';
10
+ import { plannerPrompt, strategistPrompt, summarizerPrompt, verifierPrompt, VERIFIER_LENSES, } from './prompts.js';
11
+ import { goalVerifierCount } from './types.js';
12
+ /** Read-only surface for verifiers — no writes, no shell, no sub-agents, so
13
+ * panels can run unattended without hitting a permission prompt. */
14
+ const VERIFIER_TOOL_ALLOWLIST = new Set([
15
+ 'Read', 'Grep', 'Glob',
16
+ 'WebFetch', 'WebSearch',
17
+ 'ExaSearch', 'ExaAnswer', 'ExaReadUrls',
18
+ 'TradingMarket', 'TradingSignal', 'TradingPortfolio', 'TradingHistory',
19
+ 'PredictionMarket', 'SurfMarket', 'Wallet',
20
+ ]);
21
+ function record(model, usage) {
22
+ try {
23
+ recordUsage(model, usage.inputTokens, usage.outputTokens, estimateCost(model, usage.inputTokens, usage.outputTokens), 0);
24
+ }
25
+ catch { /* stats are best-effort */ }
26
+ }
27
+ async function completeText(ctx, prompt, maxTokens) {
28
+ const { content, usage } = await ctx.client.complete({
29
+ model: ctx.model,
30
+ messages: [{ role: 'user', content: prompt }],
31
+ max_tokens: maxTokens,
32
+ stream: true,
33
+ }, ctx.signal);
34
+ record(ctx.model, usage);
35
+ return content
36
+ .filter((p) => p.type === 'text')
37
+ .map(p => p.text)
38
+ .join('\n')
39
+ .trim();
40
+ }
41
+ // ─── Planner ───────────────────────────────────────────────────────────────
42
+ /** Lightweight kind detection — the plan template diverges per kind. */
43
+ export function detectGoalKind(objective) {
44
+ const text = objective.toLowerCase();
45
+ if (/\b(trade|trading|position|portfolio|swap|bet|long|short|rebalance|dca|stop.?loss|take.?profit|polymarket)\b/.test(text)) {
46
+ return 'trading';
47
+ }
48
+ if (/\b(research|compare|investigate|analy[sz]e|find out|survey|report|summar)\b/.test(text)) {
49
+ return 'research';
50
+ }
51
+ return 'general';
52
+ }
53
+ export async function runPlanner(ctx, objective) {
54
+ const kind = detectGoalKind(objective);
55
+ const planMd = await completeText(ctx, plannerPrompt(objective, kind), 4096);
56
+ return { kind, planMd };
57
+ }
58
+ // ─── Verifier panel ────────────────────────────────────────────────────────
59
+ export function parseVerdict(text) {
60
+ const lines = text.trim().split('\n');
61
+ for (let i = lines.length - 1; i >= 0; i--) {
62
+ const line = lines[i].trim();
63
+ const start = line.indexOf('{');
64
+ if (start === -1)
65
+ continue;
66
+ try {
67
+ const obj = JSON.parse(line.slice(start));
68
+ if (typeof obj?.refuted === 'boolean') {
69
+ return {
70
+ refuted: obj.refuted,
71
+ findings: Array.isArray(obj.findings) ? obj.findings.map(String).slice(0, 8) : [],
72
+ confidence: obj.confidence === 'low' || obj.confidence === 'high' ? obj.confidence : 'medium',
73
+ blocking: obj.blocking === 'contradiction' || obj.blocking === 'unverifiable' ? obj.blocking : 'none',
74
+ };
75
+ }
76
+ }
77
+ catch { /* keep scanning upward */ }
78
+ }
79
+ return null;
80
+ }
81
+ async function runSingleVerifier(ctx, goal, planMd, claimMessage, lens) {
82
+ const tools = ctx.capabilities.filter(c => VERIFIER_TOOL_ALLOWLIST.has(c.spec.name));
83
+ const toolDefs = tools.map(c => c.spec);
84
+ const toolMap = new Map(tools.map(c => [c.spec.name, c]));
85
+ const history = [
86
+ { role: 'user', content: verifierPrompt(goal, planMd, claimMessage, lens) },
87
+ ];
88
+ const deadline = Date.now() + 4 * 60 * 1000;
89
+ let finalText = '';
90
+ for (let turn = 0; turn < 12; turn++) {
91
+ if (Date.now() > deadline || ctx.signal.aborted)
92
+ break;
93
+ const { content, usage } = await ctx.client.complete({ model: ctx.model, messages: history, tools: toolDefs, max_tokens: 8192, stream: true }, ctx.signal);
94
+ record(ctx.model, usage);
95
+ history.push({ role: 'assistant', content });
96
+ const invocations = [];
97
+ for (const part of content) {
98
+ if (part.type === 'text')
99
+ finalText = part.text;
100
+ else if (part.type === 'tool_use')
101
+ invocations.push(part);
102
+ }
103
+ if (invocations.length === 0)
104
+ break;
105
+ const outcomes = [];
106
+ for (const inv of invocations) {
107
+ const handler = toolMap.get(inv.name);
108
+ let result;
109
+ try {
110
+ result = handler
111
+ ? await handler.execute(inv.input, { workingDir: ctx.workingDir, abortSignal: ctx.signal })
112
+ : { output: `Tool ${inv.name} is not available to verifiers (read-only audit surface).`, isError: true };
113
+ }
114
+ catch (err) {
115
+ result = { output: `Error: ${err.message}`, isError: true };
116
+ }
117
+ outcomes.push({
118
+ type: 'tool_result',
119
+ tool_use_id: inv.id,
120
+ content: result.output.slice(0, 20_000),
121
+ is_error: result.isError,
122
+ });
123
+ }
124
+ history.push({ role: 'user', content: outcomes });
125
+ }
126
+ // Unparseable / no verdict = refuted (default-refute doctrine).
127
+ return (parseVerdict(finalText) ?? {
128
+ refuted: true,
129
+ findings: ['verifier produced no parseable verdict — treat as refuted and re-verify'],
130
+ confidence: 'low',
131
+ blocking: 'none',
132
+ });
133
+ }
134
+ export async function runVerifierPanel(ctx, goal, planMd, claimMessage) {
135
+ const n = goalVerifierCount();
136
+ const lenses = Array.from({ length: n }, (_, i) => VERIFIER_LENSES[i % VERIFIER_LENSES.length]);
137
+ ctx.onProgress?.(`goal verification: ${n} adversarial reviewers auditing the completion claim…`);
138
+ const verdicts = await Promise.all(lenses.map(lens => runSingleVerifier(ctx, goal, planMd, claimMessage, lens).catch(() => ({
139
+ refuted: true,
140
+ findings: ['verifier crashed — treat as refuted'],
141
+ confidence: 'low',
142
+ blocking: 'none',
143
+ }))));
144
+ const refutedCount = verdicts.filter(v => v.refuted).length;
145
+ const refuted = refutedCount * 2 > verdicts.length; // strict majority
146
+ const gaps = refuted
147
+ ? [...new Set(verdicts.filter(v => v.refuted).flatMap(v => v.findings))].slice(0, 10)
148
+ : [];
149
+ const blocking = verdicts.find(v => v.refuted && v.blocking === 'contradiction')
150
+ ? 'contradiction'
151
+ : verdicts.find(v => v.refuted && v.blocking === 'unverifiable')
152
+ ? 'unverifiable'
153
+ : 'none';
154
+ return { refuted, gaps, blocking, verdicts };
155
+ }
156
+ // ─── Strategist & summarizer ───────────────────────────────────────────────
157
+ /** Whack-a-mole detector: the last three rounds all refuted with materially
158
+ * different gap sets (no shared gap between consecutive rounds). */
159
+ export function needsStrategist(goal) {
160
+ if (goal.strategistNote)
161
+ return false; // one structural intervention per goal
162
+ const last = goal.rounds.slice(-3);
163
+ if (last.length < 3 || !last.every(r => r.refuted))
164
+ return false;
165
+ for (let i = 1; i < last.length; i++) {
166
+ const prev = new Set(last[i - 1].gaps.map(g => g.toLowerCase()));
167
+ if (last[i].gaps.some(g => prev.has(g.toLowerCase())))
168
+ return false; // overlapping = converging
169
+ }
170
+ return true;
171
+ }
172
+ export async function runStrategist(ctx, goal, planMd) {
173
+ return completeText(ctx, strategistPrompt(goal, planMd), 512);
174
+ }
175
+ export async function runSummarizer(ctx, goal, planMd) {
176
+ return completeText(ctx, summarizerPrompt(goal, planMd), 512);
177
+ }
178
+ /** First unchecked checklist item — the per-turn nudge. */
179
+ export function mineNextStep(planMd) {
180
+ const m = planMd.match(/^- \[ \] (.+)$/m);
181
+ return m?.[1]?.trim();
182
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Goal-engine prompt templates. All roles except the summarizer write for
3
+ * MACHINE readers (the implementer, the verifier panel, the parser) — keep
4
+ * their outputs structured and terse. The summarizer alone writes for the
5
+ * user.
6
+ */
7
+ import type { GoalKind, GoalState } from './types.js';
8
+ export declare function plannerPrompt(objective: string, kind: GoalKind): string;
9
+ export declare function taskDisciplineBlock(): string;
10
+ /** Spend shown as coarse buckets so the directive stays prompt-cache-friendly. */
11
+ export declare function spendBucket(spentUsd: number, maxUsd?: number): string;
12
+ export declare function continuationDirective(goal: GoalState, planMd: string, nextStep?: string): string;
13
+ export declare function verifierPrompt(goal: GoalState, planMd: string, claimMessage: string, lens: string): string;
14
+ export declare const VERIFIER_LENSES: string[];
15
+ export declare function strategistPrompt(goal: GoalState, planMd: string): string;
16
+ export declare function summarizerPrompt(goal: GoalState, planMd: string): string;