hankweave 0.5.7 → 0.6.2

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 (79) hide show
  1. package/README.md +12 -11
  2. package/dist/base-process-manager.d.ts +30 -0
  3. package/dist/budget.d.ts +315 -0
  4. package/dist/checkpoint-git.d.ts +98 -0
  5. package/dist/claude-agent-sdk-manager.d.ts +144 -0
  6. package/dist/claude-log-parser.d.ts +63 -0
  7. package/dist/claude-runtime-extractor.d.ts +73 -0
  8. package/dist/codex-runtime-extractor.d.ts +107 -0
  9. package/dist/codon-runner.d.ts +278 -0
  10. package/dist/config-validation/model-validator.d.ts +16 -0
  11. package/dist/config-validation/sentinel.schema.d.ts +6967 -0
  12. package/dist/config.d.ts +40815 -0
  13. package/dist/cost-tracker.d.ts +72 -0
  14. package/dist/execution-planner.d.ts +62 -0
  15. package/dist/execution-thread.d.ts +71 -0
  16. package/dist/exports/schemas.d.ts +9 -0
  17. package/dist/exports/schemas.js +1019 -0
  18. package/dist/exports/types.d.ts +15 -0
  19. package/dist/exports/types.js +60 -0
  20. package/dist/file-resolver.d.ts +33 -0
  21. package/dist/index.js +380 -293
  22. package/dist/index.js.map +33 -29
  23. package/dist/llm/llm-provider-registry.d.ts +207 -0
  24. package/dist/llm/models-dev-schema.d.ts +679 -0
  25. package/dist/llm/provider-config.d.ts +30 -0
  26. package/dist/prompt-builder.d.ts +75 -0
  27. package/dist/prompt-frontmatter.d.ts +61 -0
  28. package/dist/replay-process-manager.d.ts +82 -0
  29. package/dist/runtime-extractor-base.d.ts +120 -0
  30. package/dist/schemas/event-schemas.d.ts +8389 -0
  31. package/dist/schemas/websocket-log-schemas.d.ts +4502 -0
  32. package/dist/shim-process-manager.d.ts +98 -0
  33. package/dist/shim-runtime-extractor.d.ts +51 -0
  34. package/dist/shims/codex/README.md +129 -0
  35. package/dist/shims/codex/THIRDPARTY.md +18 -0
  36. package/dist/shims/codex/VERSION +1 -0
  37. package/dist/shims/codex/common/package.json +24 -0
  38. package/dist/shims/codex/index.js +1154 -970
  39. package/dist/shims/codex/package.json +46 -0
  40. package/dist/shims/codex/tsup.config.ts +16 -0
  41. package/dist/shims/gemini/README.md +59 -0
  42. package/dist/shims/gemini/THIRDPARTY.md +32 -0
  43. package/dist/shims/gemini/VERSION +1 -0
  44. package/dist/shims/gemini/common/package.json +24 -0
  45. package/dist/shims/gemini/index.js +1359 -30
  46. package/dist/shims/gemini/package.json +37 -0
  47. package/dist/shims/opencode/README.md +82 -0
  48. package/dist/shims/opencode/THIRDPARTY.md +32 -0
  49. package/dist/shims/opencode/VERSION +1 -0
  50. package/dist/shims/opencode/common/package.json +24 -0
  51. package/dist/shims/opencode/index.js +1476 -0
  52. package/dist/shims/opencode/package.json +38 -0
  53. package/dist/shims/pi/README.md +87 -0
  54. package/dist/shims/pi/THIRDPARTY.md +24 -0
  55. package/dist/shims/pi/VERSION +1 -0
  56. package/dist/shims/pi/common/package.json +24 -0
  57. package/dist/shims/pi/index.js +249832 -0
  58. package/dist/shims/pi/package.json +53 -0
  59. package/dist/state-manager.d.ts +161 -0
  60. package/dist/state-transition-guards.d.ts +37 -0
  61. package/dist/telemetry/telemetry-types.d.ts +206 -0
  62. package/dist/typed-event-emitter.d.ts +57 -0
  63. package/dist/types/branded-types.d.ts +15 -0
  64. package/dist/types/budget-types.d.ts +82 -0
  65. package/dist/types/claude-session-schema.d.ts +2430 -0
  66. package/dist/types/error-types.d.ts +44 -0
  67. package/dist/types/input-ai-types.d.ts +1070 -0
  68. package/dist/types/llm-call-types.d.ts +3829 -0
  69. package/dist/types/sentinel-types.d.ts +66 -0
  70. package/dist/types/state-types.d.ts +1099 -0
  71. package/dist/types/tool-types.d.ts +86 -0
  72. package/dist/types/types.d.ts +367 -0
  73. package/dist/types/websocket-log-types.d.ts +7 -0
  74. package/dist/utils.d.ts +452 -0
  75. package/package.json +15 -2
  76. package/schemas/hank.schema.json +158 -3
  77. package/schemas/hankweave.schema.json +17 -1
  78. package/shims/codex/index.js +0 -1583
  79. package/shims/gemini/index.js +0 -31
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "pi-shim",
3
+ "version": "1.0.0",
4
+ "description": "Shim package for the embedded Pi coding agent SDK",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "bin": {
8
+ "pi-shim": "./index.js"
9
+ },
10
+ "main": "./index.js",
11
+ "files": [
12
+ "README.md",
13
+ "bun.lock",
14
+ "tsconfig.json",
15
+ "index.js",
16
+ "dist",
17
+ "src",
18
+ "common",
19
+ "docs",
20
+ "tests",
21
+ "rebuild.sh",
22
+ "VERSION",
23
+ "THIRDPARTY.md"
24
+ ],
25
+ "scripts": {
26
+ "build": "bun build src/index.ts --outfile dist/index.js --target node --bundle && node -e \"const fs=require('fs');const p='dist/index.js';let c=fs.readFileSync(p,'utf8');c=c.replace(/^#!.*\\n/,'');fs.writeFileSync(p,'#!/usr/bin/env node\\n'+c);fs.chmodSync(p,0o755);fs.copyFileSync(p,'index.js');fs.chmodSync('index.js',0o755);\"",
27
+ "dev": "bun run src/index.ts",
28
+ "typecheck": "tsc --noEmit",
29
+ "clean": "rm -rf dist",
30
+ "test": "bun test",
31
+ "rebuild": "./rebuild.sh",
32
+ "self-test": "node index.js --self-test"
33
+ },
34
+ "dependencies": {
35
+ "@mariozechner/pi-coding-agent": "^0.57.1",
36
+ "@shims/common": "file:./common"
37
+ },
38
+ "devDependencies": {
39
+ "@types/bun": "latest",
40
+ "@types/node": "^20.0.0",
41
+ "typescript": "^5.3.0"
42
+ },
43
+ "keywords": [
44
+ "shim",
45
+ "pi",
46
+ "coding-agent",
47
+ "hankweave"
48
+ ],
49
+ "engines": {
50
+ "node": ">=20.0.0",
51
+ "bun": ">=1.1.0"
52
+ }
53
+ }
@@ -0,0 +1,161 @@
1
+ import type { CheckpointGit } from "./checkpoint-git.js";
2
+ import { type ExecutionCodonEntry } from "./execution-planner.js";
3
+ import { type ExecutionThread } from "./execution-thread.js";
4
+ import { type StateManagerEvents, TypedEventEmitter } from "./typed-event-emitter.js";
5
+ import { type CodonId, type RunId } from "./types/branded-types.js";
6
+ import type * as ST from "./types/state-types.js";
7
+ import type { CodonConfig } from "./types/types.js";
8
+ import { type Logger } from "./utils.js";
9
+ export declare class InvalidTransitionError extends Error {
10
+ constructor(from: ST.CodonStatus, to: ST.CodonStatus);
11
+ }
12
+ export declare class PersistenceError extends Error {
13
+ constructor(operation: string, cause: Error);
14
+ }
15
+ /**
16
+ * Result of expanding the next iteration of a loop.
17
+ * If a loop terminated, includes the loop ID and its archiveOnSuccess paths.
18
+ */
19
+ export interface ExpandIterationResult {
20
+ loopTerminated?: {
21
+ loopId: string;
22
+ archiveOnSuccess?: string[];
23
+ completedIterations: number;
24
+ };
25
+ }
26
+ export declare class StateManager extends TypedEventEmitter<StateManagerEvents> implements ST.StateManager {
27
+ private readonly hankweaveDir;
28
+ private readonly codonConfigs?;
29
+ private state;
30
+ private readonly statePath;
31
+ private readonly stateBackupPath;
32
+ private readonly logger;
33
+ private transitionQueue;
34
+ private isProcessing;
35
+ private readonly planner;
36
+ private costCache;
37
+ constructor(hankweaveDir: string, logger: Logger, codonConfigs?: CodonConfig[] | undefined);
38
+ initialize(): Promise<void>;
39
+ /**
40
+ * Load and validate a state file from disk.
41
+ * @throws Error if file is corrupted or cannot be read
42
+ */
43
+ private loadAndValidateStateFile;
44
+ /**
45
+ * Restore state from a parsed and validated state object.
46
+ */
47
+ private restoreStateFromParsed;
48
+ /**
49
+ * Attempt to restore state from backup file.
50
+ */
51
+ private tryRestoreFromBackup;
52
+ getState(): Readonly<ST.HankweaveState>;
53
+ /**
54
+ * Get codon entry from execution plan by codon ID.
55
+ * This handles generated IDs like "review#0", "review#1" from loop expansion.
56
+ *
57
+ * @param codonId - The codon ID to look up
58
+ * @returns The execution codon entry, or null if not found
59
+ */
60
+ getCodonById(codonId: CodonId): ExecutionCodonEntry | null;
61
+ /**
62
+ * Build initial execution plan for a fresh start.
63
+ * Expands only the first iteration of each loop.
64
+ * Automatically validates and stores the plan.
65
+ * Called automatically when RunStarted transition occurs (unless continuation mode).
66
+ */
67
+ private buildInitialPlan;
68
+ /**
69
+ * Expand next iteration of a loop after codon completion.
70
+ * Checks if this completed codon is part of a loop and expands the next iteration if needed.
71
+ * Automatically validates and stores the updated plan.
72
+ *
73
+ * @returns Information about loop termination if a loop ended
74
+ */
75
+ expandNextIterationForCodon(params: {
76
+ codonId: CodonId;
77
+ contextExceeded?: boolean;
78
+ budgetExceeded?: boolean;
79
+ }): Promise<ExpandIterationResult>;
80
+ /**
81
+ * Checks if context exceeded is an acceptable termination condition for the given codon.
82
+ *
83
+ * Returns true only if:
84
+ * - Codon is part of a loop (has loopContext)
85
+ * - That loop terminates on contextExceeded
86
+ *
87
+ * This is a pure query method with no side effects.
88
+ *
89
+ * @param codonId - The codon to check
90
+ * @returns true if context exceeded is acceptable, false otherwise
91
+ */
92
+ isContextExceededAcceptable(codonId: CodonId): boolean;
93
+ transition(event: ST.StateTransition): void;
94
+ private processQueue;
95
+ private updateCostCache;
96
+ private updateExecutionPlan;
97
+ private rebuildCostCache;
98
+ validate(state: unknown): ST.StateValidation;
99
+ private isValidStateStructure;
100
+ getCurrentRunCost(): number;
101
+ getTotalCost(): number;
102
+ getCurrentRun(): ST.Run | null;
103
+ getCurrentlyRunningCodon(): ST.CodonExecution | null;
104
+ getCodonInCurrentRun(codonId: CodonId): ST.CodonExecution | null;
105
+ /**
106
+ * Get the next codon that should be executed based on current state.
107
+ * Uses the execution thread to determine where we are in the workflow.
108
+ *
109
+ * @returns CodonId of next codon to execute, or null if all codons are complete
110
+ */
111
+ getNextCodonToExecute(): Promise<CodonId | null>;
112
+ getRun(runId: RunId): ST.Run | null;
113
+ getCodonHistory(codonId: CodonId): Promise<Array<{
114
+ run: ST.Run;
115
+ codon: ST.CodonExecution;
116
+ }>>;
117
+ getCostSince(runId: RunId): number;
118
+ canContinueFrom(runId: RunId, afterCodon: CodonId | null): boolean;
119
+ getCheckpointForContinuation(runId: RunId, afterCodon: CodonId | null): string | null;
120
+ getRunById(runId: RunId): ST.Run | null;
121
+ private checkpointGit?;
122
+ /**
123
+ * Set the checkpoint git instance for git operations.
124
+ * Called by HankweaveRuntime after initializing CheckpointGit.
125
+ */
126
+ setCheckpointGit(checkpointGit: CheckpointGit): void;
127
+ /**
128
+ * Get the execution thread for the current state.
129
+ * This provides a unified view of codon execution across all runs.
130
+ *
131
+ * @param targetRunId - Optional run ID to start from (defaults to latest)
132
+ * @param includeCheckpointValidation - Whether to validate checkpoints against git
133
+ * @returns Complete execution thread with all metadata
134
+ *
135
+ * NOTE: The codonConfigs fallback exists for initialization timing issues where the plan
136
+ * hasn't been built yet (e.g., during HankweaveRuntime.start() before startNewRun()).
137
+ */
138
+ getExecutionThread(targetRunId?: RunId, includeCheckpointValidation?: boolean): Promise<ExecutionThread>;
139
+ /**
140
+ * Helper to convert checkpoint array to map for execution thread
141
+ */
142
+ private getCheckpointDataMap;
143
+ /**
144
+ * Get all checkpoints with detailed information, ordered by time.
145
+ * This exposes the checkpoint history for advanced use cases.
146
+ *
147
+ * @returns Array of checkpoint information ordered by timestamp (newest first), or null if git unavailable
148
+ */
149
+ getAllCheckpoints(): Promise<Array<{
150
+ sha: string;
151
+ message: string;
152
+ timestamp: string;
153
+ branch: string;
154
+ }> | null>;
155
+ private validateTransition;
156
+ private applyTransition;
157
+ save(): Promise<void>;
158
+ detectCrashedRuns(): Promise<void>;
159
+ recover(): Promise<ST.RecoveryResult>;
160
+ waitForPendingTransitions(): Promise<void>;
161
+ }
@@ -0,0 +1,37 @@
1
+ import type { SessionId } from "./types/branded-types.js";
2
+ import type { BudgetExceededData } from "./types/budget-types.js";
3
+ import type { CodonStatus } from "./types/state-types.js";
4
+ import type { FailureReason } from "./types/types.js";
5
+ export interface InitializingMetadata {
6
+ claudePid: number;
7
+ claudeLogPath: string;
8
+ }
9
+ export interface RunningMetadata {
10
+ claudeSessionId: SessionId;
11
+ }
12
+ export interface CompletedMetadata {
13
+ checkpointSha: string;
14
+ resultMessageReceived?: boolean;
15
+ budgetExceeded?: BudgetExceededData;
16
+ }
17
+ export interface FailedMetadata {
18
+ exitCode: number;
19
+ failureReason: FailureReason;
20
+ failedDuring: CodonStatus;
21
+ checkpointSha?: string;
22
+ }
23
+ export interface SkippedMetadata {
24
+ skippedDuring: CodonStatus;
25
+ checkpointSha?: string;
26
+ }
27
+ export declare function hasInitializingMetadata(metadata: unknown): metadata is InitializingMetadata;
28
+ export declare function hasRunningMetadata(metadata: unknown): metadata is RunningMetadata;
29
+ export declare function hasCompletedMetadata(metadata: unknown): metadata is CompletedMetadata;
30
+ export declare function hasFailedMetadata(metadata: unknown): metadata is FailedMetadata;
31
+ export declare function hasSkippedMetadata(metadata: unknown): metadata is SkippedMetadata;
32
+ export declare class MetadataValidationError extends Error {
33
+ readonly transitionTo: CodonStatus;
34
+ readonly missingFields: string[];
35
+ constructor(transitionTo: CodonStatus, missingFields: string[]);
36
+ }
37
+ export declare function validateTransitionMetadata(to: CodonStatus, metadata: unknown): void;
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Telemetry Types and Schemas
3
+ *
4
+ * Privacy-preserving types for telemetry events.
5
+ * All types follow the principle: content → size, paths → counts, IDs → hashes.
6
+ */
7
+ import { z } from "zod";
8
+ export declare const TELEMETRY_SCHEMA_VERSION = 1;
9
+ export interface PrivacyPreservingCodon {
10
+ type: "codon";
11
+ position: number;
12
+ id_hash: string;
13
+ prompt: {
14
+ source: "inline" | "file" | "files";
15
+ length_chars?: number;
16
+ file_count?: number;
17
+ total_size_bytes?: number;
18
+ };
19
+ system_prompt: {
20
+ source: "inline" | "file" | "files";
21
+ length_chars?: number;
22
+ file_count?: number;
23
+ total_size_bytes?: number;
24
+ } | null;
25
+ description: {
26
+ present: boolean;
27
+ length_chars: number;
28
+ } | null;
29
+ model: string;
30
+ continuation_mode: "fresh" | "continue-previous";
31
+ checkpointed_files: {
32
+ pattern_count: number;
33
+ } | null;
34
+ env_vars: {
35
+ count: number;
36
+ } | null;
37
+ rig_setup: {
38
+ operation_count: number;
39
+ operations: Array<{
40
+ type: "command" | "copy";
41
+ }>;
42
+ } | null;
43
+ sentinels: {
44
+ count: number;
45
+ sources: Array<"inline" | "file">;
46
+ } | null;
47
+ output_files: {
48
+ count: number;
49
+ } | null;
50
+ }
51
+ export interface PrivacyPreservingLoop {
52
+ type: "loop";
53
+ position: number;
54
+ id_hash: string;
55
+ description: {
56
+ present: boolean;
57
+ length_chars: number;
58
+ } | null;
59
+ termination: {
60
+ type: "iterationLimit" | "contextExceeded";
61
+ limit?: number;
62
+ };
63
+ codons: PrivacyPreservingCodon[];
64
+ }
65
+ export type PrivacyPreservingHankItem = PrivacyPreservingCodon | PrivacyPreservingLoop;
66
+ export interface PrivacyPreservingHank {
67
+ hank_hash: string;
68
+ items: PrivacyPreservingHankItem[];
69
+ summary: {
70
+ total_items: number;
71
+ total_codons: number;
72
+ loop_count: number;
73
+ models_used: string[];
74
+ has_sentinels: boolean;
75
+ has_checkpointing: boolean;
76
+ has_rig_setup: boolean;
77
+ has_custom_env: boolean;
78
+ total_prompt_chars: number;
79
+ total_prompt_files: number;
80
+ total_prompt_file_bytes: number;
81
+ };
82
+ }
83
+ export interface PrivacyPreservingTokenUsage {
84
+ input_tokens: number;
85
+ output_tokens: number;
86
+ cache_creation_tokens: number;
87
+ cache_read_tokens: number;
88
+ }
89
+ export interface PrivacyPreservingCodonExecution {
90
+ position: number;
91
+ codon_id_hash: string;
92
+ loop_context: {
93
+ loop_id_hash: string;
94
+ iteration: number;
95
+ position_in_loop: number;
96
+ } | null;
97
+ status: string;
98
+ start_time: string;
99
+ end_time?: string;
100
+ duration_ms?: number;
101
+ failure?: {
102
+ failed_during: string;
103
+ failure_type: string;
104
+ retriable: boolean;
105
+ exit_code?: number;
106
+ };
107
+ skipped?: {
108
+ skipped_during: string;
109
+ };
110
+ tokens: PrivacyPreservingTokenUsage;
111
+ cost_usd: number;
112
+ assistant_message_count?: number;
113
+ sentinels: {
114
+ count: number;
115
+ total_cost_usd: number;
116
+ total_triggers: number;
117
+ total_llm_calls: number;
118
+ failed_llm_calls: number;
119
+ models_used: string[];
120
+ } | null;
121
+ has_rig_setup_checkpoint: boolean;
122
+ has_completion_checkpoint: boolean;
123
+ has_error_checkpoint: boolean;
124
+ has_skip_checkpoint: boolean;
125
+ }
126
+ export interface PrivacyPreservingRun {
127
+ run_id_hash: string;
128
+ start_time: string;
129
+ end_time?: string;
130
+ duration_ms?: number;
131
+ duration_bucket: "<1m" | "1-5m" | "5-15m" | "15m+";
132
+ status: "running" | "completed" | "failed" | "crashed";
133
+ starting_conditions: {
134
+ type: "fresh" | "continuation";
135
+ reason?: "retry" | "rollback" | "continue";
136
+ };
137
+ codons: PrivacyPreservingCodonExecution[];
138
+ metrics: {
139
+ total_codons: number;
140
+ codons_completed: number;
141
+ codons_failed: number;
142
+ codons_skipped: number;
143
+ total_cost_usd: number;
144
+ total_tokens: PrivacyPreservingTokenUsage;
145
+ total_checkpoints: number;
146
+ total_rollbacks: number;
147
+ total_sentinels_loaded: number;
148
+ total_sentinel_cost_usd: number;
149
+ total_sentinel_triggers: number;
150
+ total_sentinel_llm_calls: number;
151
+ };
152
+ }
153
+ export interface PrivacyPreservingProvider {
154
+ provider_id: string;
155
+ shim?: {
156
+ name: string;
157
+ version: string;
158
+ };
159
+ agent: {
160
+ name: string;
161
+ version: string;
162
+ found: boolean;
163
+ };
164
+ self_test?: {
165
+ passed: boolean;
166
+ check_count: number;
167
+ passed_count: number;
168
+ };
169
+ }
170
+ /** Common fields included in every event via PostHog $set */
171
+ export interface TelemetryUserProperties {
172
+ hankweave_version: string;
173
+ os: string;
174
+ os_version: string;
175
+ arch: string;
176
+ node_version: string;
177
+ is_ci: boolean;
178
+ is_compiled: boolean;
179
+ }
180
+ /** All telemetry event names */
181
+ export type TelemetryEventName = "cli_init" | "cli_validate" | "cli_cleanup" | "cli_run" | "cli_help" | "run_started" | "run_completed" | "run_failed" | "run_crashed" | "codon_started" | "codon_completed" | "codon_failed" | "codon_skipped" | "loop_iteration_started" | "loop_iteration_completed" | "rig_setup_completed" | "rig_setup_failed" | "checkpoint_created" | "rollback_completed" | "continuation_started" | "sentinel_triggered" | "budget_set" | "budget_exceeded" | "$ai_generation" | "$ai_trace" | "$ai_span";
182
+ export declare const telemetryConfigSchema: z.ZodObject<{
183
+ enabled: z.ZodOptional<z.ZodBoolean>;
184
+ endpoint: z.ZodOptional<z.ZodString>;
185
+ debug: z.ZodOptional<z.ZodBoolean>;
186
+ }, "strip", z.ZodTypeAny, {
187
+ debug?: boolean | undefined;
188
+ enabled?: boolean | undefined;
189
+ endpoint?: string | undefined;
190
+ }, {
191
+ debug?: boolean | undefined;
192
+ enabled?: boolean | undefined;
193
+ endpoint?: string | undefined;
194
+ }>;
195
+ export type TelemetryConfig = z.infer<typeof telemetryConfigSchema>;
196
+ export interface TelemetryIdentity {
197
+ clientId: string;
198
+ createdAt: string;
199
+ noticeShownAt?: string;
200
+ firstSuccessAt?: string;
201
+ }
202
+ export interface TelemetryEvent {
203
+ event: TelemetryEventName;
204
+ properties: Record<string, unknown>;
205
+ timestamp: string;
206
+ }
@@ -0,0 +1,57 @@
1
+ import type { CodonId, RunId } from "./types/branded-types.js";
2
+ import type { CodonStatus, StateTransition } from "./types/state-types.js";
3
+ import type { ServerEvent } from "./types/types.js";
4
+ /**
5
+ * Type-safe wrapper around Node's EventEmitter.
6
+ * Ensures event names and argument types are consistent at compile time.
7
+ */
8
+ export declare class TypedEventEmitter<T extends Record<string, unknown[]>> {
9
+ private emitter;
10
+ on<K extends keyof T>(event: K, listener: (...args: T[K]) => void): this;
11
+ off<K extends keyof T>(event: K, listener: (...args: T[K]) => void): this;
12
+ emit<K extends keyof T>(event: K, ...args: T[K]): boolean;
13
+ once<K extends keyof T>(event: K, listener: (...args: T[K]) => void): this;
14
+ removeAllListeners<K extends keyof T>(event?: K): this;
15
+ addListener<K extends keyof T>(event: K, listener: (...args: T[K]) => void): this;
16
+ removeListener<K extends keyof T>(event: K, listener: (...args: T[K]) => void): this;
17
+ setMaxListeners(n: number): this;
18
+ getMaxListeners(): number;
19
+ listeners(event: keyof T): Function[];
20
+ rawListeners(event: keyof T): Function[];
21
+ eventNames(): (string | symbol)[];
22
+ listenerCount(event: keyof T): number;
23
+ prependListener<K extends keyof T>(event: K, listener: (...args: T[K]) => void): this;
24
+ prependOnceListener<K extends keyof T>(event: K, listener: (...args: T[K]) => void): this;
25
+ }
26
+ export interface ServerInternalEvents {
27
+ event: [ServerEvent];
28
+ exit: [code: number];
29
+ error: [error: Error];
30
+ stdout: [data: string];
31
+ stderr: [data: string];
32
+ [key: string]: unknown[];
33
+ }
34
+ export interface ProcessEvents {
35
+ exit: [code: number, isContextExceeded: boolean];
36
+ error: [error: Error];
37
+ stdout: [data: string];
38
+ stderr: [data: string];
39
+ [key: string]: unknown[];
40
+ }
41
+ export interface StateManagerEvents {
42
+ stateChanged: [StateTransition];
43
+ codonRunning: [
44
+ {
45
+ runId: RunId;
46
+ codonId: CodonId;
47
+ from: CodonStatus;
48
+ to: "running";
49
+ metadata?: Record<string, unknown>;
50
+ }
51
+ ];
52
+ transitionError: [{
53
+ event: StateTransition;
54
+ error: Error;
55
+ }];
56
+ [key: string]: unknown[];
57
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Branded types for type safety and clarity
3
+ */
4
+ type Branded<T, Brand> = T & {
5
+ __brand: Brand;
6
+ };
7
+ export type CodonId = Branded<string, "CodonId">;
8
+ export declare const CodonId: (id: string) => CodonId;
9
+ export type SessionId = Branded<string, "SessionId">;
10
+ export declare const SessionId: (id: string) => SessionId;
11
+ export type RunId = Branded<string, "RunId">;
12
+ export declare const RunId: (id: string) => RunId;
13
+ export type EventId = Branded<string, "EventId">;
14
+ export declare const EventId: (id: string) => EventId;
15
+ export {};
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Shared budget types used across the codebase.
3
+ *
4
+ * These types are consumed by state management, event schemas, CodonRunner,
5
+ * and the budget module itself.
6
+ */
7
+ /** What happens when a budget limit is exceeded. */
8
+ export type OnExceededPolicy = "complete" | "fail";
9
+ /** Options for constructing a BudgetLimits instance. */
10
+ export interface BudgetLimitsOptions {
11
+ maxDollars?: number;
12
+ maxTimeSeconds?: number;
13
+ maxOutputTokens?: number;
14
+ maxContextTokens?: number;
15
+ onExceeded?: OnExceededPolicy;
16
+ /** Human-readable description of where the cost limit came from. */
17
+ costSource?: string;
18
+ }
19
+ /**
20
+ * Resolved budget limits for a single codon execution.
21
+ */
22
+ export declare class BudgetLimits {
23
+ readonly maxDollars?: number;
24
+ readonly maxTimeSeconds?: number;
25
+ readonly maxOutputTokens?: number;
26
+ readonly maxContextTokens?: number;
27
+ readonly onExceeded?: OnExceededPolicy;
28
+ /** Human-readable description of where the cost limit came from. */
29
+ readonly costSource?: string;
30
+ constructor(opts?: BudgetLimitsOptions);
31
+ /** Whether any numeric limits are configured. */
32
+ hasLimits(): boolean;
33
+ }
34
+ /** The budget currencies tracked by the system. */
35
+ export declare const BUDGET_CURRENCIES: readonly ["cost", "duration", "outputTokens", "contextTokens"];
36
+ export type BudgetCurrency = (typeof BUDGET_CURRENCIES)[number];
37
+ /** Snapshot of a budget limit breach — which currency, what limit, how much was used. */
38
+ export interface BudgetExceededData {
39
+ currency: BudgetCurrency;
40
+ limit: number;
41
+ used: number;
42
+ }
43
+ /** Full info about a budget breach, including a human-readable message. */
44
+ export interface BudgetExceededInfo extends BudgetExceededData {
45
+ message: string;
46
+ }
47
+ /** How budget is distributed among codons in a container. */
48
+ export type AllocationMode = "shared" | "proportional" | "proportional-strict";
49
+ /** Per-codon row in the end-of-run budget summary table. */
50
+ export interface CodonBudgetSummaryRow {
51
+ codonId: string;
52
+ loopContext?: {
53
+ loopId: string;
54
+ iteration: number;
55
+ codonIndexInLoop: number;
56
+ };
57
+ status: "completed" | "failed" | "skipped" | "exceeded" | "running";
58
+ budget: {
59
+ maxDollars?: number;
60
+ maxTimeSeconds?: number;
61
+ maxOutputTokens?: number;
62
+ };
63
+ actual: {
64
+ dollars: number;
65
+ timeSeconds: number;
66
+ outputTokens: number;
67
+ };
68
+ }
69
+ /** Full payload for the budget.summary event emitted at end of run. */
70
+ export interface BudgetSummaryData {
71
+ ceiling: {
72
+ maxDollars?: number;
73
+ maxTimeSeconds?: number;
74
+ };
75
+ allocation: AllocationMode;
76
+ rows: CodonBudgetSummaryRow[];
77
+ totals: {
78
+ budgetDollars?: number;
79
+ actualDollars: number;
80
+ actualTimeSeconds: number;
81
+ };
82
+ }