@mindot/will 0.9.0 → 0.10.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 (110) hide show
  1. package/README.md +15 -11
  2. package/dist/index.d.ts +188 -141
  3. package/dist/index.js +16660 -15206
  4. package/dist/index.js.map +1 -1
  5. package/dist/{channels → surface/channels}/discord.d.ts +50 -3
  6. package/dist/{channels → surface/channels}/discord.js +102 -7
  7. package/dist/surface/channels/discord.js.map +1 -0
  8. package/dist/{channels → surface/channels}/whatsapp.d.ts +2 -2
  9. package/dist/{channels → surface/channels}/whatsapp.js +7 -4
  10. package/dist/surface/channels/whatsapp.js.map +1 -0
  11. package/dist/{cli.js → surface/cli.js} +4406 -2904
  12. package/dist/surface/cli.js.map +1 -0
  13. package/dist/{mcp → surface/mcp}/effectors.d.ts +1 -1
  14. package/dist/{mcp → surface/mcp}/effectors.js +10 -4
  15. package/dist/surface/mcp/effectors.js.map +1 -0
  16. package/dist/{will-DbDj_TEH.d.ts → will-evj9_vrd.d.ts} +5699 -4854
  17. package/package.json +11 -12
  18. package/src/cognition/agency/consequence.ts +237 -3
  19. package/src/cognition/agency/conversation.aim.ts +32 -0
  20. package/src/cognition/agency/engines/action.selector.ts +59 -3
  21. package/src/cognition/agency/engines/affordance.synthesizer.ts +114 -10
  22. package/src/cognition/agency/engines/deliberation.engine.ts +76 -3
  23. package/src/cognition/agency/engines/motor.schema.executor.ts +362 -27
  24. package/src/cognition/agency/engines/reafference.engine.ts +43 -4
  25. package/src/cognition/agency/execution.primitives.ts +17 -4
  26. package/src/cognition/agency/reconcile.learning.ts +5 -4
  27. package/src/cognition/agency/schemas/innate.ts +96 -1
  28. package/src/cognition/agency/schemas/repertoire.ts +19 -1
  29. package/src/cognition/agency/selection.scoring.ts +16 -0
  30. package/src/cognition/agency/settlement.ts +203 -0
  31. package/src/cognition/agency/types.ts +38 -1
  32. package/src/cognition/config.mirror.entities.ts +0 -1
  33. package/src/cognition/event.schemas.ts +0 -8
  34. package/src/cognition/faculties/affective.blender.ts +21 -4
  35. package/src/cognition/faculties/circadian.oscillator.ts +36 -7
  36. package/src/cognition/faculties/executive.engine/action.record.ts +129 -0
  37. package/src/cognition/faculties/executive.engine/context.ts +41 -35
  38. package/src/cognition/faculties/executive.engine/engine.ts +270 -113
  39. package/src/cognition/faculties/executive.engine/escalation.buffer.ts +126 -59
  40. package/src/cognition/faculties/executive.engine/facet.supervisor.ts +10 -0
  41. package/src/cognition/faculties/executive.engine/parser.ts +100 -38
  42. package/src/cognition/faculties/executive.engine/prompt.factory.ts +168 -23
  43. package/src/cognition/faculties/executive.engine/types.ts +18 -15
  44. package/src/cognition/faculties/exteroception.ts +99 -98
  45. package/src/cognition/faculties/goal.manager.ts +50 -2
  46. package/src/cognition/faculties/known.entity.tracker.ts +22 -3
  47. package/src/cognition/faculties/planning.engine/engine.ts +4 -4
  48. package/src/cognition/faculties/planning.engine/plan.frontier.ts +1 -1
  49. package/src/cognition/faculties/semantic.engine/integrator.ts +1 -1
  50. package/src/cognition/faculties/working.memory.ts +6 -1
  51. package/src/cognition/instruction.handler.ts +1 -1
  52. package/src/cognition/memory/vector.embedder.ts +1 -3
  53. package/src/cognition/percept.entity.ts +122 -0
  54. package/src/cognition/sense.boundary.ts +176 -0
  55. package/src/cognition/senses/audition.engine/engine.ts +97 -16
  56. package/src/cognition/senses/base.sense.engine.ts +104 -6
  57. package/src/cognition/senses/index.ts +71 -13
  58. package/src/cognition/senses/provenance.ts +128 -0
  59. package/src/cognition/senses/somatosensation.engine.ts +117 -9
  60. package/src/cognition/social.identity.ts +23 -0
  61. package/src/cognition/utilities/token.tracker.ts +36 -5
  62. package/src/core/orchestrator.ts +13 -0
  63. package/src/index.ts +39 -5
  64. package/src/llm/gate.ts +48 -0
  65. package/src/llm/index.ts +102 -25
  66. package/src/llm/wire.contracts.ts +38 -0
  67. package/src/pma/index.ts +1 -1
  68. package/src/stem/index.ts +92 -21
  69. package/src/stem/mind.ts +26 -2
  70. package/src/stem/policy/arbiter.ts +10 -0
  71. package/src/stem/profiles/built-in.ts +7 -0
  72. package/src/{profiles → stem/profiles}/companion.ts +1 -1
  73. package/src/{profiles → stem/profiles}/company-brain.ts +1 -1
  74. package/src/{profiles → stem/profiles}/customer-service.ts +1 -1
  75. package/src/{profiles → stem/profiles}/game-npc.ts +1 -1
  76. package/src/{profiles → stem/profiles}/index.ts +1 -1
  77. package/src/{profiles → stem/profiles}/smart-home.ts +1 -1
  78. package/src/stem/tracts/effector/escalation.lifecycle.ts +239 -0
  79. package/src/stem/tracts/effector/policy.enforcement.ts +261 -0
  80. package/src/stem/tracts/effector/types.ts +110 -0
  81. package/src/stem/tracts/effector.controller.ts +112 -401
  82. package/src/stem/tracts/outbox.controller.ts +30 -17
  83. package/src/stem/tracts/sensory.controller.ts +6 -6
  84. package/src/stem/tracts/session.logger.ts +6 -1
  85. package/src/stem/tracts/transport/types.ts +20 -1
  86. package/src/stem/tracts/transport.controller.ts +33 -9
  87. package/src/{channels → surface/channels}/discord.ts +224 -7
  88. package/src/{channels → surface/channels}/roster.ts +1 -1
  89. package/src/{channels → surface/channels}/types.ts +1 -1
  90. package/src/{channels → surface/channels}/whatsapp.ts +9 -6
  91. package/src/{cli.ts → surface/cli.ts} +6 -6
  92. package/src/{host → surface/host}/boot.ts +3 -3
  93. package/src/{host → surface/host}/utterances.ts +2 -2
  94. package/src/{mcp → surface/mcp}/effectors.ts +19 -6
  95. package/src/{mcp → surface/mcp}/server.ts +19 -5
  96. package/src/{sdk → surface/sdk}/will.ts +156 -28
  97. package/src/{serve → surface/serve}/server.ts +11 -4
  98. package/src/types.ts +24 -3
  99. package/dist/channels/discord.js.map +0 -1
  100. package/dist/channels/whatsapp.js.map +0 -1
  101. package/dist/cli.js.map +0 -1
  102. package/dist/mcp/effectors.js.map +0 -1
  103. package/src/extensions/livestream.ext.ts +0 -570
  104. package/src/extensions/time.ext.ts +0 -339
  105. package/src/profiles/built-in.ts +0 -7
  106. package/src/runners/coherence.runner.ts +0 -49
  107. package/src/runners/outreach.runner.ts +0 -155
  108. package/src/runners/social.runner.ts +0 -179
  109. package/src/runners/thin-shim.runner.ts +0 -205
  110. /package/dist/{cli.d.ts → surface/cli.d.ts} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/mcp/effectors.ts"],"names":[],"mappings":";;;;;AAwDA,IAAM,sBAAA,GAAyB,GAAA;AAE/B,IAAM,WAAA,GAAc,GAAA;AAOb,SAAS,gBAAiB,IAAA,EAA4B;AAC3D,EAAA,MAAM,KAAA,GAAW,IAAA,CAAK,WAAA,EAAa,UAAA,IAAc,EAAC;AAClD,EAAA,MAAM,WAAW,IAAI,GAAA,CAAK,KAAK,WAAA,EAAa,QAAA,IAAY,EAAG,CAAA;AAC3D,EAAA,MAAM,QAAA,GAAW,MAAA,CAAO,OAAA,CAAS,KAAM,CAAA,CAAE,GAAA,CAAK,CAAE,CAAE,GAAA,EAAK,CAAE,CAAA,KACvD,CAAA,EAAI,GAAI,CAAA,EAAI,QAAA,CAAS,GAAA,CAAK,GAAI,CAAA,GAAI,EAAA,GAAK,GAAI,CAAA,EAAI,CAAA,CAAE,WAAA,GAAc,CAAA,EAAA,EAAM,CAAA,CAAE,WAAY,CAAA,CAAA,GAAK,EAAG,CAAA,CAAE,CAAA;AAE/F,EAAA,MAAM,IAAA,GAAA,CAAS,IAAA,CAAK,WAAA,IAAe,CAAA,IAAA,EAAQ,IAAA,CAAK,IAAK,CAAA,MAAA,CAAA,EAAU,IAAA,EAAK,CAAE,OAAA,CAAS,MAAA,EAAQ,GAAG,CAAA;AAC1F,EAAA,MAAM,IAAA,GAAO,SAAS,MAAA,GAAS,CAAA,GAAI,iBAAa,QAAA,CAAS,IAAA,CAAK,IAAI,CAAE,CAAA,CAAA,CAAA,GAAM,EAAA;AAC1E,EAAA,MAAM,IAAA,GAAO,CAAA,EAAI,IAAK,CAAA,EAAI,IAAK,CAAA,CAAA;AAC/B,EAAA,OAAO,IAAA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AAAA;AAAA,MAE5C,GAAA,EAAK,EAAE,GAAG,qBAAA,IAAyB,GAAK,MAAA,CAAO,GAAA,IAAO,EAAC;AAAI,KAC3D,CAAE,CAAA;AACN,EAAA,OAAO,EAAE,MAAA,EAAQ,KAAA,EAAO,IAAA,EAAK;AAC/B;AAOA,eAAsB,mBAAA,CACpB,IAAA,EACA,MAAA,EACA,IAAA,GAA8B,EAAC,EAC2B;AAC1D,EAAA,MAAM,EAAE,MAAA,EAAQ,KAAA,EAAM,GAAI,MAAM,QAAS,MAAO,CAAA;AAChD,EAAA,MAAM,EAAE,KAAA,EAAM,GAAI,MAAM,OAAO,SAAA,EAAU;AAEzC,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,MAAM,OAAO,CAAA,EAAI,IAAA,CAAK,UAAU,EAAG,CAAA,EAAI,KAAK,IAAK,CAAA,CAAA;AACjD,IAAA,IAAA,CAAK,SAAU,IAAA,EAAM;AAAA,MACnB,WAAA,EAAa,gBAAiB,IAAK,CAAA;AAAA,MACnC,IAAA,EAAa,KAAK,IAAA,IAAQ,GAAA;AAAA,MAC1B,IAAA,EAAa,CAAE,KAAM,CAAA;AAAA,MACrB,OAAA,EAAa,eAAA,CAAiB,MAAA,EAAQ,IAAK;AAAA,KAC3C,CAAA;AACF,IAAA,KAAA,CAAM,KAAM,IAAK,CAAA;AAAA,EACnB;AAEA,EAAA,OAAO,EAAE,KAAA,EAAO,KAAA,EAAO,YAAY;AAAE,IAAA,IAAI,KAAA,EAAQ,MAAM,MAAA,CAAO,KAAA,EAAM;AAAA,EAAE,CAAA,EAAE;AAC1E","file":"effectors.js","sourcesContent":["// ─────────────────────────────────────────────────────────────\n// src/mcp/effectors.ts — a Will EMPLOYING MCP tools (Seam 1)\n// ─────────────────────────────────────────────────────────────\n//\n// The other direction from server.ts: connect a Will to an external MCP server\n// and register that server's tools as the Will's own ABILITIES. Each tool\n// becomes a learnable affordance — its description (plus a compact hint of the\n// arguments it takes) is the ability's meaning, surfaced to the executive and\n// the deliberator; the WILL decides when to enact one (nothing here dispatches);\n// the tool's result feeds back through reafference, so the Will gets *skilled*\n// at the tools it uses.\n//\n// Arguments come from conscious intent: the executive supplies them via an\n// action's `args`, which ride the ideomotor leg into the invocation (see\n// executive commands.ts). A tool with required arguments enacted habitually\n// (without args) fails informatively — reafference then teaches the Will that\n// this ability wants deliberate articulation.\n//\n// const { names, close } = await connectMcpEffectors( will, {\n// command: 'npx', args: [ '-y', '@modelcontextprotocol/server-filesystem', '/tmp' ],\n// } )\n//\n// Import from '@mindot/will/mcp' — kept off the main entry so non-MCP\n// consumers never load the MCP SDK.\n// ─────────────────────────────────────────────────────────────\n\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport { StdioClientTransport, getDefaultEnvironment } from '@modelcontextprotocol/sdk/client/stdio.js'\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'\nimport type { Will, EffectorHandler, EffectorResult } from '#sdk/will'\n\n/** Where the tools live: spawn a local server, reach a remote one, or bring a connected client. */\nexport type McpToolsSource =\n | { command: string; args?: string[]; env?: Record<string, string> }\n | { url: string }\n | { client: Client }\n\nexport interface McpEffectorsOptions {\n /** Intrinsic effort prior 0..1 seeded on every bridged ability (default 0.2). */\n cost?: number\n /** Prefix for the ability names (e.g. 'fs_') — avoids collisions across servers. */\n prefix?: string\n}\n\n/** Minimal structural view of an MCP tool (the SDK's zod-inferred type, loosened). */\nexport interface McpToolInfo {\n name: string\n description?: string\n inputSchema?: {\n type?: string\n properties?: Record<string, { type?: string; description?: string }>\n required?: string[]\n }\n}\n\n/** Keep tool outcomes bounded — the description feeds reafference + episodic memory. */\nconst RESULT_DESCRIPTION_CAP = 700\n/** Keep ability meanings bounded — they render into the executive prompt. */\nconst MEANING_CAP = 300\n\n/**\n * The ability's *meaning*: the tool's description plus a compact hint of the\n * arguments it takes — so the executive knows what to supply in an action's\n * `args` when it enacts this ability.\n */\nexport function describeMcpTool( tool: McpToolInfo ): string {\n const props = tool.inputSchema?.properties ?? {}\n const required = new Set( tool.inputSchema?.required ?? [] )\n const argHints = Object.entries( props ).map( ( [ key, p ] ) =>\n `${ key }${ required.has( key ) ? '' : '?' }${ p.description ? `: ${ p.description }` : '' }`)\n\n const base = ( tool.description ?? `The ${ tool.name } tool.`).trim().replace( /\\s+/g, ' ')\n const hint = argHints.length > 0 ? ` (args — ${ argHints.join('; ') })` : ''\n const full = `${ base }${ hint }`\n return full.length > MEANING_CAP ? `${ full.slice( 0, MEANING_CAP - 1 ) }…` : full\n}\n\n/**\n * The effector handler for one bridged tool: checks required args (an ability\n * enacted without its needed articulation fails informatively — reafference\n * learns from it), calls the tool, and maps the result onto EffectorResult.\n */\nexport function buildMcpHandler( client: Client, tool: McpToolInfo ): EffectorHandler {\n return async ( args ): Promise<EffectorResult> => {\n const props = tool.inputSchema?.properties\n // Only pass keys the tool declares — invocation params can carry situation\n // extras (targetEntityName, learned priors) the tool never asked for.\n const filtered: Record<string, unknown> = {}\n for( const [ k, v ] of Object.entries( args ?? {} ) )\n if( !props || k in props ) filtered[ k ] = v\n\n const missing = ( tool.inputSchema?.required ?? [] ).filter(\n k => filtered[ k ] === undefined || filtered[ k ] === '')\n if( missing.length > 0 )\n return {\n success: false,\n description: `${ tool.name } needs ${ missing.join(', ') } — enact it deliberately, supplying them in the action's args.`,\n }\n\n try {\n const res = await client.callTool( { name: tool.name, arguments: filtered } ) as\n { content?: Array<{ type: string; text?: string }>; isError?: boolean }\n const text = ( res.content ?? [] )\n .filter( c => c.type === 'text' && typeof c.text === 'string')\n .map( c => c.text as string )\n .join('\\n')\n .trim() || ( res.isError ? 'The tool reported an error.' : 'Done (no output).')\n const bounded = text.length > RESULT_DESCRIPTION_CAP ? `${ text.slice( 0, RESULT_DESCRIPTION_CAP - 1 ) }…` : text\n return { success: !res.isError, description: bounded }\n }\n catch( err ){\n return { success: false, description: `${ tool.name } failed: ${ err instanceof Error ? err.message : String( err ) }` }\n }\n }\n}\n\nasync function connect( source: McpToolsSource ): Promise<{ client: Client; owned: boolean }> {\n if('client' in source ) return { client: source.client, owned: false }\n\n const client = new Client( { name: 'mindot-will', version: '0' } )\n if('url' in source )\n await client.connect( new StreamableHTTPClientTransport( new URL( source.url ) ) )\n else\n await client.connect( new StdioClientTransport( {\n command: source.command,\n ...( source.args ? { args: source.args } : {} ),\n // Merge over the SDK's safe default env so PATH etc. survive a custom env.\n env: { ...getDefaultEnvironment(), ...( source.env ?? {} ) },\n } ) )\n return { client, owned: true }\n}\n\n/**\n * Register an MCP server's tools as the Will's abilities. Returns the ability\n * names registered and a `close()` for the connection (call it when the Will\n * stops; a client passed in via `source.client` is left open).\n */\nexport async function connectMcpEffectors(\n will: Will,\n source: McpToolsSource,\n opts: McpEffectorsOptions = {},\n): Promise<{ names: string[]; close: () => Promise<void> }> {\n const { client, owned } = await connect( source )\n const { tools } = await client.listTools() as unknown as { tools: McpToolInfo[] }\n\n const names: string[] = []\n for( const tool of tools ){\n const name = `${ opts.prefix ?? '' }${ tool.name }`\n will.effector( name, {\n description: describeMcpTool( tool ),\n cost: opts.cost ?? 0.2,\n tags: [ 'mcp' ],\n handler: buildMcpHandler( client, tool ),\n } )\n names.push( name )\n }\n\n return { names, close: async () => { if( owned ) await client.close() } }\n}\n"]}
@@ -1,570 +0,0 @@
1
- // ─────────────────────────────────────────────────────────────
2
- // src/extensions/live.ext.ts
3
- // ─────────────────────────────────────────────────────────────
4
-
5
- /**
6
- * Live streaming extension for dashboards, monitoring, and observability.
7
- * Layers on top of core — not part of the framework itself.
8
- *
9
- * Provides WebSocket (full-duplex) and Server-Sent Events (unidirectional)
10
- * transports for real-time simulation state, metrics, and event streaming.
11
- */
12
-
13
- import { logger } from '#core/logger'
14
- import type { SimulationClock } from '#core/clock'
15
- import type { EventBus } from '#core/event.bus'
16
- import type { MetricCollector } from '#core/metrics'
17
- import type { Orchestrator } from '#core/orchestrator'
18
- import type { StateManager } from '#core/state.manager'
19
- import type {
20
- SimulationContext,
21
- SimulationEvent,
22
- ReadonlySimulationState,
23
- Tick,
24
- Timestamp,
25
- } from '../core/types'
26
-
27
- // ── Transport-agnostic stream message ──────────────────────
28
-
29
- export interface StreamMessage {
30
- type: 'snapshot' | 'tick-summary' | 'event' | 'metric-point' | 'log'
31
- timestamp: Timestamp
32
- tick: Tick
33
- payload: unknown
34
- }
35
-
36
- export interface TickSummary {
37
- tick: Tick
38
- simTime: Timestamp
39
- wallDuration: number // ms this tick took
40
- entityCount: number
41
- metricCount: number
42
- pendingEvents: number
43
- }
44
-
45
- // ── Stream transports ─────────────────────────────────────
46
-
47
- /**
48
- * Pluggable transport for live data.
49
- * Implementations: WebSocketStream, SSEStream, ConsoleStream, NoopStream
50
- */
51
- export interface LiveStreamTransport {
52
- /** Push a single message to connected clients. */
53
- send( message: StreamMessage ): void
54
-
55
- /** Close all connections gracefully. */
56
- close(): void
57
-
58
- /** Called when the transport is registered with the extension. */
59
- onRegister?(): void
60
- }
61
-
62
- // ── Configuration ─────────────────────────────────────────
63
-
64
- export interface LiveStreamConfig {
65
- /** Emit full state snapshot every N ticks (0 = never) */
66
- snapshotIntervalTicks?: number
67
- /** Emit tick summary (entity count, latency) every N ticks (1 = every tick) */
68
- tickSummaryIntervalTicks?: number
69
- /** Forward all events from EventBus */
70
- streamEvents?: boolean
71
- /** Forward metric points */
72
- streamMetrics?: boolean
73
- /** Event types to exclude from streaming (e.g., verbose debug events) */
74
- excludeEventTypes?: string[]
75
- /** Maximum message queue depth before dropping (backpressure) */
76
- maxQueueDepth?: number
77
- }
78
-
79
- // ── Extension implementation ──────────────────────────────
80
-
81
- /**
82
- * FIX 1: Instead of implementing TickMiddleware (which has a call-signature
83
- * constraint), we expose the handler as a property that matches the signature.
84
- * The class no longer `implements TickMiddleware` — it provides an `onTick`
85
- * arrow function that is structurally compatible and can be assigned to
86
- * orchestratorConfig.onAfterTick.
87
- */
88
- export class LiveStreamExtension {
89
- private _transport: LiveStreamTransport
90
- private _config: LiveStreamConfig
91
- private _eventBus: EventBus
92
- private _stateManager: StateManager
93
- private _metricCollector?: MetricCollector
94
- private _clock: SimulationClock
95
- /** FIX 2: Use the concrete DefaultOrchestrator type which has tickLatencies. */
96
- private _orchestrator: Orchestrator
97
- private _getTickLatency: () => number
98
-
99
- private _unsubscribeEventBus?: () => void
100
- private _messageQueue: StreamMessage[] = []
101
- private _maxQueueDepth: number
102
- private _flushInterval: ReturnType<typeof setInterval> | null = null
103
-
104
- constructor(
105
- transport: LiveStreamTransport,
106
- eventBus: EventBus,
107
- stateManager: StateManager,
108
- orchestrator: Orchestrator,
109
- clock: SimulationClock,
110
- config: LiveStreamConfig = {},
111
- metricCollector?: MetricCollector
112
- ){
113
- this._transport = transport
114
- this._eventBus = eventBus
115
- this._stateManager = stateManager
116
- this._orchestrator = orchestrator
117
- this._clock = clock
118
- this._metricCollector = metricCollector
119
- this._config = {
120
- snapshotIntervalTicks: config.snapshotIntervalTicks ?? 0,
121
- tickSummaryIntervalTicks: config.tickSummaryIntervalTicks ?? 1,
122
- streamEvents: config.streamEvents ?? true,
123
- streamMetrics: config.streamMetrics ?? false,
124
- excludeEventTypes: config.excludeEventTypes ?? [],
125
- maxQueueDepth: config.maxQueueDepth ?? 1000,
126
- }
127
- this._maxQueueDepth = this._config.maxQueueDepth!
128
-
129
- /**
130
- * FIX 2: tickLatencies is only available on DefaultOrchestrator, not the
131
- * Orchestrator interface. We probe for it and provide a fallback so the
132
- * extension works with any orchestrator implementation.
133
- */
134
- const orchestratorAny = orchestrator as any
135
- if( Array.isArray( orchestratorAny.tickLatencies ) ){
136
- this._getTickLatency = () => {
137
- const latencies = orchestratorAny.tickLatencies as number[]
138
- return latencies.length > 0 ? ( latencies.at( -1 ) ?? 0 ) : 0
139
- }
140
- }
141
- else {
142
- this._getTickLatency = () => 0
143
- }
144
-
145
- // Wire transport lifecycle
146
- transport.onRegister?.()
147
- }
148
-
149
- // ── Tick handler (assignable to OrchestratorConfig.onAfterTick) ──
150
-
151
- /**
152
- * Arrow function property — structurally matches the TickMiddleware
153
- * call signature `(tick, time, state, context) => void | Promise<void>`.
154
- * Assign this to orchestratorConfig.onAfterTick.
155
- */
156
- readonly onTick = (
157
- tick: Tick,
158
- _time: Timestamp,
159
- state: ReadonlySimulationState,
160
- _context: SimulationContext
161
- ): void => {
162
- // Tick summary
163
- if(
164
- this._config.tickSummaryIntervalTicks! > 0
165
- && tick % this._config.tickSummaryIntervalTicks! === 0
166
- ){
167
- this._enqueue({
168
- type: 'tick-summary',
169
- timestamp: Date.now(),
170
- tick,
171
- payload: {
172
- tick,
173
- simTime: this._clock.now,
174
- wallDuration: this._getTickLatency(),
175
- entityCount: state.entities.size,
176
- metricCount: state.metrics.size,
177
- pendingEvents: this._eventBus.getPendingCount(),
178
- } satisfies TickSummary,
179
- })
180
- }
181
-
182
- // Full snapshot
183
- if(
184
- this._config.snapshotIntervalTicks! > 0
185
- && tick % this._config.snapshotIntervalTicks! === 0
186
- ){
187
- this._enqueue({
188
- type: 'snapshot',
189
- timestamp: Date.now(),
190
- tick,
191
- payload: this._stateManager.snapshot(),
192
- })
193
- }
194
- }
195
-
196
- // ── Lifecycle ───────────────────────────────────────────
197
-
198
- /** Start streaming. Must be called after construction. */
199
- start(): void {
200
- // Subscribe to event bus
201
- if( this._config.streamEvents ){
202
- this._unsubscribeEventBus = this._eventBus.subscribeAll( ( event, _ctx ) => {
203
- if( this._config.excludeEventTypes?.includes( event.type ) ) return
204
- this._enqueue({
205
- type: 'event',
206
- timestamp: Date.now(),
207
- tick: event.tick,
208
- payload: event,
209
- })
210
- })
211
- }
212
-
213
- // Periodic flush (handles metric streaming + drain)
214
- this._flushInterval = setInterval( () => {
215
- // Metric streaming can be wired here if MetricCollector exposes a
216
- // per-point callback. Currently metrics flow through tick summaries.
217
- this._drainQueue()
218
- }, 50 ) // 20 fps flush rate
219
- }
220
-
221
- /** Stop streaming and close transport. */
222
- stop(): void {
223
- this._unsubscribeEventBus?.()
224
- if( this._flushInterval ) clearInterval( this._flushInterval )
225
- this._drainQueue()
226
- this._transport.close()
227
- }
228
-
229
- // ── Backpressure handling ───────────────────────────────
230
-
231
- private _enqueue( message: StreamMessage ): void {
232
- if( this._messageQueue.length >= this._maxQueueDepth ){
233
- // Drop oldest message (circular buffer semantics)
234
- this._messageQueue.shift()
235
- logger.warn(`[LiveStream] Queue full (${this._maxQueueDepth}), dropping oldest message`)
236
- }
237
-
238
- this._messageQueue.push( message )
239
- }
240
-
241
- private _drainQueue(): void {
242
- while( this._messageQueue.length > 0 ){
243
- const message = this._messageQueue.shift()!
244
- try {
245
- this._transport.send( message )
246
- }
247
- catch( error ){
248
- logger.error('[LiveStream] Failed to send message, transport may be closed:', error )
249
- // Stop trying — transport is dead
250
- this._messageQueue.length = 0
251
- break
252
- }
253
- }
254
- }
255
- }
256
-
257
- // ── WebSocket transport (Bun-native) ──────────────────────
258
-
259
- export interface WebSocketConfig {
260
- port: number
261
- path?: string // e.g., '/live'
262
- maxConnections?: number
263
- }
264
-
265
- /**
266
- * FIX 3: Bun.serve().upgrade() requires an options object with `data`.
267
- * The third argument is not rest parameters — it's a single options bag.
268
- */
269
- export class WebSocketTransport implements LiveStreamTransport {
270
- private _server: ReturnType<typeof Bun.serve> | null = null
271
- private _clients: Set<{ send: ( data: string ) => void }> = new Set()
272
- private _config: WebSocketConfig
273
- private _maxConnections: number
274
-
275
- constructor( config: WebSocketConfig ){
276
- this._config = config
277
- this._maxConnections = config.maxConnections ?? 100
278
- }
279
-
280
- send( message: StreamMessage ): void {
281
- const data = JSON.stringify( message )
282
-
283
- for( const client of this._clients )
284
- client.send( data )
285
- }
286
-
287
- close(): void {
288
- this._server?.stop()
289
- this._clients.clear()
290
- }
291
-
292
- onRegister(): void {
293
- this._server = Bun.serve({
294
- port: this._config.port,
295
- fetch: ( req, server ) => {
296
- // Only upgrade on the configured path
297
- const url = new URL( req.url )
298
- if( this._config.path && url.pathname !== this._config.path )
299
- return new Response('Not found', { status: 404 } )
300
-
301
- // Connection limit
302
- if( this._clients.size >= this._maxConnections )
303
- return new Response('Too many connections', { status: 503 } )
304
-
305
- // FIX 3: upgrade() requires { data } as second argument per Bun types
306
- const upgraded = server.upgrade( req, { data: {} } )
307
- if( !upgraded )
308
- return new Response('WebSocket upgrade failed', { status: 400 } )
309
-
310
- return undefined // Bun handles the upgrade response
311
- },
312
- websocket: {
313
- open: ( ws ) => {
314
- this._clients.add( ws )
315
- logger.info(`[WebSocket] Client connected (${this._clients.size} total)`)
316
- },
317
- close: ( ws ) => {
318
- this._clients.delete( ws )
319
- logger.info(`[WebSocket] Client disconnected (${this._clients.size} total)`)
320
- },
321
- message: ( _ws, _message ) => {
322
- // Clients can send commands here (pause, resume, set speed, etc.)
323
- // For now, read-only streaming
324
- },
325
- },
326
- })
327
-
328
- logger.info(`[WebSocket] Server listening on ws://localhost:${this._config.port}${this._config.path ?? '/'}`)
329
- }
330
- }
331
-
332
- // ── Server-Sent Events transport ──────────────────────────
333
-
334
- export interface SSEConfig {
335
- port: number
336
- path?: string
337
- }
338
-
339
- /**
340
- * FIX 4 & 5: ReadableStreamDefaultController (from Bun.serve fetch) is not
341
- * a WritableStreamDefaultWriter. SSE uses a ReadableStream to push events
342
- * to the client. We need to store the controller and use controller.enqueue()
343
- * instead of writer.write().
344
- */
345
- export class SSETransport implements LiveStreamTransport {
346
- private _server: ReturnType<typeof Bun.serve> | null = null
347
- private _clients: Set<ReadableStreamDefaultController<Uint8Array>> = new Set()
348
- private _config: SSEConfig
349
- private _encoder = new TextEncoder()
350
-
351
- constructor( config: SSEConfig ){
352
- this._config = config
353
- }
354
-
355
- send( message: StreamMessage ): void {
356
- const
357
- eventLine = `event: ${message.type}\n`,
358
- dataLine = `data: ${JSON.stringify( message )}\n\n`,
359
- encoded = this._encoder.encode( eventLine + dataLine )
360
-
361
- for( const controller of this._clients )
362
- controller.enqueue( encoded )
363
- }
364
-
365
- close(): void {
366
- this._server?.stop()
367
- for( const controller of this._clients ){
368
- try { controller.close() } catch {}
369
- }
370
- this._clients.clear()
371
- }
372
-
373
- onRegister(): void {
374
- this._server = Bun.serve({
375
- port: this._config.port,
376
- fetch: async ( req ) => {
377
- const url = new URL( req.url )
378
- if( this._config.path && url.pathname !== this._config.path )
379
- return new Response('Not found', { status: 404 } )
380
-
381
- /**
382
- * FIX 4 & 5: ReadableStream with start(controller) gives us a
383
- * ReadableStreamDefaultController. We store the controller directly
384
- * and use controller.enqueue() to push SSE data. The client's
385
- * abort signal handles disconnection cleanup.
386
- */
387
- let streamController: ReadableStreamDefaultController<Uint8Array> | null = null
388
-
389
- const stream = new ReadableStream<Uint8Array>({
390
- start: ( controller ) => {
391
- streamController = controller
392
- this._clients.add( controller )
393
-
394
- // Send initial comment to establish connection
395
- controller.enqueue( this._encoder.encode(': connected\n\n') )
396
-
397
- req.signal.addEventListener('abort', () => {
398
- if( streamController ){
399
- this._clients.delete( streamController )
400
- logger.info(`[SSE] Client disconnected (${this._clients.size} total)`)
401
- streamController = null
402
- }
403
- })
404
- },
405
- cancel: () => {
406
- if( streamController ){
407
- this._clients.delete( streamController )
408
- streamController = null
409
- }
410
- },
411
- })
412
-
413
- return new Response( stream, {
414
- headers: {
415
- 'Content-Type': 'text/event-stream',
416
- 'Cache-Control': 'no-cache',
417
- 'Connection': 'keep-alive',
418
- },
419
- })
420
- },
421
- })
422
-
423
- logger.info(`[SSE] Server listening on http://localhost:${this._config.port}${this._config.path ?? '/'}`)
424
- }
425
- }
426
-
427
- // ── Console transport (for development) ───────────────────
428
-
429
- export class ConsoleTransport implements LiveStreamTransport {
430
- private _verbose: boolean
431
-
432
- constructor( verbose: boolean = false ){
433
- this._verbose = verbose
434
- }
435
-
436
- send( message: StreamMessage ): void {
437
- if( !this._verbose && message.type === 'tick-summary'){
438
- // Only log every 100 ticks for summary
439
- const summary = message.payload as TickSummary
440
- if( summary.tick % 100 === 0 ){
441
- logger.info(
442
- `[Live] Tick ${summary.tick}: ${summary.entityCount} entities, ${summary.wallDuration}ms`
443
- )
444
- }
445
- return
446
- }
447
-
448
- logger.info(`[Live] ${message.type}:`, message.payload )
449
- }
450
-
451
- close(): void {
452
- // No-op for console
453
- }
454
- }
455
-
456
- // ── Factory helpers ───────────────────────────────────────
457
-
458
- export class LiveStreamFactory {
459
- /**
460
- * Create a WebSocket-backed live stream wired into a running simulation.
461
- * Wire `stream.onTick` as `orchestratorConfig.onAfterTick`.
462
- */
463
- static createWebSocket(
464
- sim: {
465
- eventBus: EventBus
466
- stateManager: StateManager
467
- orchestrator: Orchestrator
468
- clock: SimulationClock
469
- metrics: MetricCollector
470
- },
471
- config: LiveStreamConfig & WebSocketConfig
472
- ): LiveStreamExtension {
473
- const transport = new WebSocketTransport({
474
- port: config.port,
475
- path: config.path,
476
- maxConnections: config.maxConnections,
477
- })
478
-
479
- return new LiveStreamExtension(
480
- transport,
481
- sim.eventBus,
482
- sim.stateManager,
483
- sim.orchestrator,
484
- sim.clock,
485
- config,
486
- sim.metrics
487
- )
488
- }
489
-
490
- /**
491
- * Create an SSE-backed live stream.
492
- */
493
- static createSSE(
494
- sim: {
495
- eventBus: EventBus
496
- stateManager: StateManager
497
- orchestrator: Orchestrator
498
- clock: SimulationClock
499
- metrics: MetricCollector
500
- },
501
- config: LiveStreamConfig & SSEConfig
502
- ): LiveStreamExtension {
503
- const transport = new SSETransport({
504
- port: config.port,
505
- path: config.path,
506
- })
507
-
508
- return new LiveStreamExtension(
509
- transport,
510
- sim.eventBus,
511
- sim.stateManager,
512
- sim.orchestrator,
513
- sim.clock,
514
- config,
515
- sim.metrics
516
- )
517
- }
518
-
519
- /**
520
- * Quick console logger for development.
521
- */
522
- static createConsole(
523
- sim: {
524
- eventBus: EventBus
525
- stateManager: StateManager
526
- orchestrator: Orchestrator
527
- clock: SimulationClock
528
- metrics: MetricCollector
529
- },
530
- config: LiveStreamConfig = {}
531
- ): LiveStreamExtension {
532
- const transport = new ConsoleTransport()
533
-
534
- return new LiveStreamExtension(
535
- transport,
536
- sim.eventBus,
537
- sim.stateManager,
538
- sim.orchestrator,
539
- sim.clock,
540
- config,
541
- sim.metrics
542
- )
543
- }
544
- }
545
-
546
- // ── Usage example ─────────────────────────────────────────
547
-
548
- // import { DefaultSimulation } from '../core/simulation'
549
- // import { LiveStreamFactory } from './live.ext'
550
- //
551
- // const sim = new DefaultSimulation()
552
- // // ... load scenario, add engines ...
553
- //
554
- // const liveStream = LiveStreamFactory.createWebSocket( sim, {
555
- // port: 8080,
556
- // path: '/simulation-live',
557
- // tickSummaryIntervalTicks: 1,
558
- // streamEvents: true,
559
- // snapshotIntervalTicks: 100,
560
- // })
561
- //
562
- // // Wire into orchestrator using updateConfig — works post-construction
563
- // const unsubLive = sim.orchestrator.onAfterTick( liveStream.onTick )
564
- //
565
- // // Later, remove one without affecting the other
566
- // unsubLive()
567
- //
568
- // liveStream.start()
569
- // await sim.run()
570
- // liveStream.stop()