@vibefield/puppeteer-imposter 0.0.0-stage → 0.2.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 (250) hide show
  1. package/LICENSE +21 -0
  2. package/bin/ai.mjs +17 -0
  3. package/dist/cli/argv.d.ts +40 -0
  4. package/dist/cli/argv.d.ts.map +1 -0
  5. package/dist/cli/argv.js +62 -0
  6. package/dist/cli/argv.js.map +1 -0
  7. package/dist/cli/http-persona.d.ts +15 -0
  8. package/dist/cli/http-persona.d.ts.map +1 -0
  9. package/dist/cli/http-persona.js +216 -0
  10. package/dist/cli/http-persona.js.map +1 -0
  11. package/dist/cli/main.d.ts +11 -0
  12. package/dist/cli/main.d.ts.map +1 -0
  13. package/dist/cli/main.js +671 -0
  14. package/dist/cli/main.js.map +1 -0
  15. package/dist/cli/prompt-line.d.ts +27 -0
  16. package/dist/cli/prompt-line.d.ts.map +1 -0
  17. package/dist/cli/prompt-line.js +93 -0
  18. package/dist/cli/prompt-line.js.map +1 -0
  19. package/dist/control/client.d.ts +51 -0
  20. package/dist/control/client.d.ts.map +1 -0
  21. package/dist/control/client.js +206 -0
  22. package/dist/control/client.js.map +1 -0
  23. package/dist/control/index.d.ts +10 -0
  24. package/dist/control/index.d.ts.map +1 -0
  25. package/dist/control/index.js +10 -0
  26. package/dist/control/index.js.map +1 -0
  27. package/dist/control/peer.d.ts +42 -0
  28. package/dist/control/peer.d.ts.map +1 -0
  29. package/dist/control/peer.js +174 -0
  30. package/dist/control/peer.js.map +1 -0
  31. package/dist/control/protocol.d.ts +207 -0
  32. package/dist/control/protocol.d.ts.map +1 -0
  33. package/dist/control/protocol.js +535 -0
  34. package/dist/control/protocol.js.map +1 -0
  35. package/dist/index.d.ts +36 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +36 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/persona/launch.d.ts +7 -0
  40. package/dist/persona/launch.d.ts.map +1 -0
  41. package/dist/persona/launch.js +26 -0
  42. package/dist/persona/launch.js.map +1 -0
  43. package/dist/persona/load.d.ts +28 -0
  44. package/dist/persona/load.d.ts.map +1 -0
  45. package/dist/persona/load.js +705 -0
  46. package/dist/persona/load.js.map +1 -0
  47. package/dist/persona/session-id.d.ts +4 -0
  48. package/dist/persona/session-id.d.ts.map +1 -0
  49. package/dist/persona/session-id.js +12 -0
  50. package/dist/persona/session-id.js.map +1 -0
  51. package/dist/persona/types.d.ts +265 -0
  52. package/dist/persona/types.d.ts.map +1 -0
  53. package/dist/persona/types.js +38 -0
  54. package/dist/persona/types.js.map +1 -0
  55. package/dist/session/channels/hook.d.ts +31 -0
  56. package/dist/session/channels/hook.d.ts.map +1 -0
  57. package/dist/session/channels/hook.js +114 -0
  58. package/dist/session/channels/hook.js.map +1 -0
  59. package/dist/session/channels/http-sse.d.ts +67 -0
  60. package/dist/session/channels/http-sse.d.ts.map +1 -0
  61. package/dist/session/channels/http-sse.js +212 -0
  62. package/dist/session/channels/http-sse.js.map +1 -0
  63. package/dist/session/channels/jsonrpc.d.ts +56 -0
  64. package/dist/session/channels/jsonrpc.d.ts.map +1 -0
  65. package/dist/session/channels/jsonrpc.js +196 -0
  66. package/dist/session/channels/jsonrpc.js.map +1 -0
  67. package/dist/session/channels/leader-ipc.d.ts +27 -0
  68. package/dist/session/channels/leader-ipc.d.ts.map +1 -0
  69. package/dist/session/channels/leader-ipc.js +314 -0
  70. package/dist/session/channels/leader-ipc.js.map +1 -0
  71. package/dist/session/channels/native-store.d.ts +31 -0
  72. package/dist/session/channels/native-store.d.ts.map +1 -0
  73. package/dist/session/channels/native-store.js +275 -0
  74. package/dist/session/channels/native-store.js.map +1 -0
  75. package/dist/session/channels/statusline.d.ts +20 -0
  76. package/dist/session/channels/statusline.d.ts.map +1 -0
  77. package/dist/session/channels/statusline.js +48 -0
  78. package/dist/session/channels/statusline.js.map +1 -0
  79. package/dist/session/channels/terminal.d.ts +27 -0
  80. package/dist/session/channels/terminal.d.ts.map +1 -0
  81. package/dist/session/channels/terminal.js +108 -0
  82. package/dist/session/channels/terminal.js.map +1 -0
  83. package/dist/session/channels/transcript.d.ts +16 -0
  84. package/dist/session/channels/transcript.d.ts.map +1 -0
  85. package/dist/session/channels/transcript.js +24 -0
  86. package/dist/session/channels/transcript.js.map +1 -0
  87. package/dist/session/channels/ws-unix.d.ts +57 -0
  88. package/dist/session/channels/ws-unix.d.ts.map +1 -0
  89. package/dist/session/channels/ws-unix.js +396 -0
  90. package/dist/session/channels/ws-unix.js.map +1 -0
  91. package/dist/session/http-session-server.d.ts +31 -0
  92. package/dist/session/http-session-server.d.ts.map +1 -0
  93. package/dist/session/http-session-server.js +508 -0
  94. package/dist/session/http-session-server.js.map +1 -0
  95. package/dist/session/scenario-driver.d.ts +105 -0
  96. package/dist/session/scenario-driver.d.ts.map +1 -0
  97. package/dist/session/scenario-driver.js +211 -0
  98. package/dist/session/scenario-driver.js.map +1 -0
  99. package/dist/session/scenario.d.ts +119 -0
  100. package/dist/session/scenario.d.ts.map +1 -0
  101. package/dist/session/scenario.js +299 -0
  102. package/dist/session/scenario.js.map +1 -0
  103. package/dist/session/serve.d.ts +124 -0
  104. package/dist/session/serve.d.ts.map +1 -0
  105. package/dist/session/serve.js +136 -0
  106. package/dist/session/serve.js.map +1 -0
  107. package/dist/session/session.d.ts +125 -0
  108. package/dist/session/session.d.ts.map +1 -0
  109. package/dist/session/session.js +781 -0
  110. package/dist/session/session.js.map +1 -0
  111. package/dist/session/template.d.ts +35 -0
  112. package/dist/session/template.d.ts.map +1 -0
  113. package/dist/session/template.js +133 -0
  114. package/dist/session/template.js.map +1 -0
  115. package/dist/session/timeline.d.ts +81 -0
  116. package/dist/session/timeline.d.ts.map +1 -0
  117. package/dist/session/timeline.js +155 -0
  118. package/dist/session/timeline.js.map +1 -0
  119. package/dist/tui/app.d.ts +30 -0
  120. package/dist/tui/app.d.ts.map +1 -0
  121. package/dist/tui/app.js +72 -0
  122. package/dist/tui/app.js.map +1 -0
  123. package/dist/tui/mount.d.ts +37 -0
  124. package/dist/tui/mount.d.ts.map +1 -0
  125. package/dist/tui/mount.js +88 -0
  126. package/dist/tui/mount.js.map +1 -0
  127. package/dist/tui/store.d.ts +38 -0
  128. package/dist/tui/store.d.ts.map +1 -0
  129. package/dist/tui/store.js +56 -0
  130. package/dist/tui/store.js.map +1 -0
  131. package/dist/tui/theme.d.ts +40 -0
  132. package/dist/tui/theme.d.ts.map +1 -0
  133. package/dist/tui/theme.js +54 -0
  134. package/dist/tui/theme.js.map +1 -0
  135. package/package.json +67 -3
  136. package/personas/antigravity/behavior/happy-turn.json +9 -0
  137. package/personas/antigravity/ops.json +14 -0
  138. package/personas/antigravity/persona.json +15 -0
  139. package/personas/antigravity/runflows.json +6 -0
  140. package/personas/antigravity/scenarios/happy-turn.json +25 -0
  141. package/personas/claude/behavior/happy-turn.json +19 -0
  142. package/personas/claude/ops.json +128 -0
  143. package/personas/claude/persona.json +29 -0
  144. package/personas/claude/runflows.json +45 -0
  145. package/personas/claude/scenarios/channel-disconnect.json +19 -0
  146. package/personas/claude/scenarios/crash-mid-turn.json +42 -0
  147. package/personas/claude/scenarios/cross-layer-implementation.json +488 -0
  148. package/personas/claude/scenarios/deep-research.json +494 -0
  149. package/personas/claude/scenarios/duplicate-out-of-order.json +57 -0
  150. package/personas/claude/scenarios/flood.json +11 -0
  151. package/personas/claude/scenarios/happy-turn.json +57 -0
  152. package/personas/claude/scenarios/incident-investigation.json +465 -0
  153. package/personas/claude/scenarios/late-after-exit.json +27 -0
  154. package/personas/claude/scenarios/permission-allow.json +55 -0
  155. package/personas/claude/scenarios/permission-deny.json +71 -0
  156. package/personas/claude/scenarios/token-usage-refresh.json +33 -0
  157. package/personas/claude/scenarios/unknown-event.json +14 -0
  158. package/personas/codex/behavior/approval-turn.json +15 -0
  159. package/personas/codex/behavior/happy-turn.json +10 -0
  160. package/personas/codex/ops.json +159 -0
  161. package/personas/codex/persona.json +36 -0
  162. package/personas/codex/runflows.json +45 -0
  163. package/personas/codex/scenarios/channel-disconnect.json +31 -0
  164. package/personas/codex/scenarios/crash-mid-turn.json +30 -0
  165. package/personas/codex/scenarios/cross-layer-implementation.json +725 -0
  166. package/personas/codex/scenarios/deep-research.json +684 -0
  167. package/personas/codex/scenarios/duplicate-out-of-order.json +87 -0
  168. package/personas/codex/scenarios/flood.json +22 -0
  169. package/personas/codex/scenarios/happy-turn.json +81 -0
  170. package/personas/codex/scenarios/incident-investigation.json +695 -0
  171. package/personas/codex/scenarios/late-after-exit.json +59 -0
  172. package/personas/codex/scenarios/permission-allow.json +110 -0
  173. package/personas/codex/scenarios/permission-deny.json +83 -0
  174. package/personas/codex/scenarios/token-usage-refresh.json +49 -0
  175. package/personas/codex/scenarios/unknown-event.json +17 -0
  176. package/personas/codex/serve.json +124 -0
  177. package/personas/copilot/behavior/happy-turn.json +9 -0
  178. package/personas/copilot/ops.json +28 -0
  179. package/personas/copilot/persona.json +17 -0
  180. package/personas/copilot/runflows.json +6 -0
  181. package/personas/copilot/scenarios/happy-turn.json +50 -0
  182. package/personas/grok/behavior/approval-turn.json +16 -0
  183. package/personas/grok/behavior/happy-turn.json +13 -0
  184. package/personas/grok/ops.json +330 -0
  185. package/personas/grok/persona.json +24 -0
  186. package/personas/grok/runflows.json +25 -0
  187. package/personas/grok/scenarios/agent-team-lifecycle.json +74 -0
  188. package/personas/grok/scenarios/compact-lifecycle.json +61 -0
  189. package/personas/grok/serve.json +57 -0
  190. package/personas/hermes/behavior/approval-turn.json +11 -0
  191. package/personas/hermes/behavior/happy-turn.json +9 -0
  192. package/personas/hermes/ops.json +227 -0
  193. package/personas/hermes/persona.json +15 -0
  194. package/personas/hermes/runflows.json +50 -0
  195. package/personas/hermes/scenarios/happy-turn.json +25 -0
  196. package/personas/hermes/scenarios/late-after-exit.json +21 -0
  197. package/personas/hermes/scenarios/permission-deny.json +54 -0
  198. package/personas/hermes/scenarios/unknown-event.json +14 -0
  199. package/personas/hermes/serve.json +54 -0
  200. package/personas/kimi/behavior/happy-turn.json +9 -0
  201. package/personas/kimi/ops.json +357 -0
  202. package/personas/kimi/persona.json +23 -0
  203. package/personas/kimi/runflows.json +84 -0
  204. package/personas/kimi/scenarios/compaction-lifecycle.json +20 -0
  205. package/personas/kimi/scenarios/duplicate-out-of-order.json +60 -0
  206. package/personas/kimi/scenarios/happy-turn.json +66 -0
  207. package/personas/kimi/scenarios/late-after-end.json +28 -0
  208. package/personas/kimi/scenarios/tool-failure.json +43 -0
  209. package/personas/kimi/scenarios/tool-success.json +57 -0
  210. package/personas/kimi/scenarios/unknown-record.json +15 -0
  211. package/personas/opencode/README.md +32 -0
  212. package/personas/opencode/behavior/happy-turn.json +9 -0
  213. package/personas/opencode/behavior/permission-turn.json +18 -0
  214. package/personas/opencode/http-serve.json +72 -0
  215. package/personas/opencode/ops.json +250 -0
  216. package/personas/opencode/persona.json +22 -0
  217. package/personas/opencode/runflows.json +45 -0
  218. package/personas/opencode/scenarios/duplicate-event.json +27 -0
  219. package/personas/opencode/scenarios/failure.json +30 -0
  220. package/personas/opencode/scenarios/happy-turn.json +86 -0
  221. package/personas/opencode/scenarios/late-event.json +29 -0
  222. package/personas/opencode/scenarios/out-of-order.json +42 -0
  223. package/personas/opencode/scenarios/permission-allow.json +31 -0
  224. package/personas/opencode/scenarios/permission-deny.json +31 -0
  225. package/personas/opencode/scenarios/question-reject.json +37 -0
  226. package/personas/opencode/scenarios/question-reply.json +38 -0
  227. package/personas/opencode/scenarios/reconnect.json +22 -0
  228. package/personas/opencode/scenarios/resume.json +30 -0
  229. package/personas/opencode/scenarios/unknown-event.json +15 -0
  230. package/personas/pi/behavior/happy-turn.json +9 -0
  231. package/personas/pi/ops.json +19 -0
  232. package/personas/pi/persona.json +16 -0
  233. package/personas/pi/runflows.json +6 -0
  234. package/personas/pi/scenarios/happy-turn.json +52 -0
  235. package/personas/synthetic/behavior/happy-turn.json +12 -0
  236. package/personas/synthetic/groundtruth.html +164 -0
  237. package/personas/synthetic/groundtruth.json +380 -0
  238. package/personas/synthetic/model/behavior.json +27 -0
  239. package/personas/synthetic/model/channels.json +16 -0
  240. package/personas/synthetic/model/detection.json +13 -0
  241. package/personas/synthetic/model/events/agent.action.json +16 -0
  242. package/personas/synthetic/model/events/agent.boot.json +16 -0
  243. package/personas/synthetic/model/events/agent.halt.json +16 -0
  244. package/personas/synthetic/model/events/agent.prompt.json +16 -0
  245. package/personas/synthetic/model/events/agent.reply.json +16 -0
  246. package/personas/synthetic/model/events/agent.settled.json +16 -0
  247. package/personas/synthetic/model/manifest.json +7 -0
  248. package/personas/synthetic/ops.json +18 -0
  249. package/personas/synthetic/persona.json +11 -0
  250. package/README.md +0 -3
@@ -0,0 +1,781 @@
1
+ /**
2
+ * Session assembly: persona + vendor argv -> live channels + op timeline.
3
+ *
4
+ * This is the only module that knows what an "envelope" is. Every delivery
5
+ * path uses the same wire builder, ASM validator, and recorder before reaching
6
+ * its native channel, so there is exactly one policy boundary that can refuse
7
+ * an off-model emission (docs/archive/IMPOSTER.md §7.3 item 3).
8
+ */
9
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
10
+ import { tmpdir } from 'node:os';
11
+ import { join, resolve } from 'node:path';
12
+ import { flagValue } from "../cli/argv.js";
13
+ import { ControlError, REFUSED, } from "../control/protocol.js";
14
+ import { createHookEmitter } from "./channels/hook.js";
15
+ import { createStatusLineInvoker } from "./channels/statusline.js";
16
+ import { createScenarioDriver } from "./scenario-driver.js";
17
+ import { createTranscriptWriter } from "./channels/transcript.js";
18
+ import { createNativeSessionStore } from "./channels/native-store.js";
19
+ import { createScenarioGate, createScenarioRunner, scenarioSteps, } from "./scenario.js";
20
+ import { substitute } from "./template.js";
21
+ import { mintPersonaSessionId } from "../persona/session-id.js";
22
+ import { createOpTimeline } from "./timeline.js";
23
+ const MAX_LOG_ENTRIES = 500;
24
+ const MAX_LOG_BYTES = 2 * 1024 * 1024;
25
+ const MAX_ENTRY_BYTES = 64 * 1024;
26
+ export function createImposterSession(options) {
27
+ const { persona, argv, env, cwd, behavior } = options;
28
+ const log = options.log ?? (() => { });
29
+ const explicitSessionId = flagValue(argv, persona.flagsFor('sessionId', '--session-id')) ??
30
+ flagValue(argv, persona.flagsFor('resume', '--resume'));
31
+ const generatedSessionId = mintPersonaSessionId(persona);
32
+ const sessionId = explicitSessionId ?? generatedSessionId;
33
+ const settingsPath = flagValue(argv, persona.flagsFor('settings', '--settings'));
34
+ const sessionTitle = flagValue(argv, persona.flagsFor('name', '--name')) ?? 'imposter-session';
35
+ const permissionMode = flagValue(argv, persona.flagsFor('permissionMode', '--permission-mode')) ?? 'default';
36
+ // Default to an ephemeral Imposter root. An explicit shared override or the
37
+ // persona's own native-root variable is authoritative; the Grok adapter sets
38
+ // both to one isolated directory so every cooperating process sees one store.
39
+ const declaredNativeRoot = persona.document.nativeStore?.rootEnv
40
+ ? env[persona.document.nativeStore.rootEnv]
41
+ : undefined;
42
+ const configuredRoot = env.PUPPETEER_IMPOSTER_HOME ?? declaredNativeRoot;
43
+ const transcriptRoot = configuredRoot ?? mkdtempSync(join(tmpdir(), `puppeteer-imposter-${persona.vendor}-`));
44
+ if (!configuredRoot) {
45
+ process.once('exit', () => rmSync(transcriptRoot, { recursive: true, force: true }));
46
+ }
47
+ if (env.PUPPETEER_IMPOSTER_HOME &&
48
+ declaredNativeRoot &&
49
+ resolve(env.PUPPETEER_IMPOSTER_HOME) !== resolve(declaredNativeRoot)) {
50
+ throw new Error(`imposter ${persona.vendor} requires PUPPETEER_IMPOSTER_HOME and ${persona.document.nativeStore?.rootEnv} to name the same isolated root`);
51
+ }
52
+ const slug = cwd.replace(/[^a-zA-Z0-9]/g, '-');
53
+ const transcriptPath = join(transcriptRoot, 'projects', slug, `${sessionId}.jsonl`);
54
+ const settings = settingsPath
55
+ ? JSON.parse(readFileSync(settingsPath, 'utf8'))
56
+ : {};
57
+ const hookEmitter = createHookEmitter({ settings, env, log });
58
+ const transcript = createTranscriptWriter(transcriptPath);
59
+ const statusLineInvoker = createStatusLineInvoker(settings.statusLine, { log });
60
+ // Drops are keyed by the VENDOR's channel name — the same name `liveChannels`
61
+ // reports and the console shows — so a channel-drop fault addresses the thing
62
+ // the operator can see. `channelFor` translates delivery kind to that name.
63
+ const droppedChannels = new Set();
64
+ const dropped = (kind) => droppedChannels.has(persona.channelFor(kind) ?? kind);
65
+ const emitted = [];
66
+ let emittedBytes = 0;
67
+ let sequence = 0;
68
+ const record = (event, payload, kind) => {
69
+ sequence += 1;
70
+ const channel = kind === undefined ? undefined : (persona.channelFor(kind) ?? kind);
71
+ let entry = {
72
+ at: new Date().toISOString(),
73
+ sequence,
74
+ event,
75
+ ...(channel === undefined ? {} : { channel }),
76
+ payload,
77
+ };
78
+ let bytes = Buffer.byteLength(JSON.stringify(entry));
79
+ if (bytes > MAX_ENTRY_BYTES) {
80
+ entry = {
81
+ at: entry.at,
82
+ sequence: entry.sequence,
83
+ event: entry.event,
84
+ ...(entry.channel === undefined ? {} : { channel: entry.channel }),
85
+ truncated: true,
86
+ };
87
+ bytes = Buffer.byteLength(JSON.stringify(entry));
88
+ }
89
+ emitted.push(entry);
90
+ emittedBytes += bytes;
91
+ while (emitted.length > MAX_LOG_ENTRIES || emittedBytes > MAX_LOG_BYTES) {
92
+ emittedBytes -= Buffer.byteLength(JSON.stringify(emitted.shift()));
93
+ }
94
+ options.onEmitted?.(entry);
95
+ };
96
+ /**
97
+ * The envelope is persona-owned vocabulary, not a constant: claude sends
98
+ * `session_id`/`transcript_path`, and a vendor that names them differently
99
+ * has to be describable without editing this file (§3.2). `bindings` is
100
+ * declared below but only read when an op actually emits, which is always
101
+ * after initialization.
102
+ */
103
+ const envelope = (fields) => ({
104
+ ...substitute(persona.document.envelope, { bindings }),
105
+ ...fields,
106
+ });
107
+ /**
108
+ * An unknown native name still has to reach the bridge for ADR-008 retention
109
+ * to be testable end to end, but it has no handler of its own — route it
110
+ * through any wired handler, exactly as the PoC did.
111
+ */
112
+ const fallbackRoute = persona.model.events.find((event) => (settings.hooks?.[event.event]?.length ?? 0) > 0)?.event;
113
+ const wireFor = (event, payload) => ({
114
+ ...envelope(payload),
115
+ ...(persona.document.eventNameField ? { [persona.document.eventNameField]: event } : {}),
116
+ });
117
+ const emit = async (event, payload) => {
118
+ const wire = wireFor(event, payload);
119
+ const violations = persona.validate(event, wire);
120
+ if (violations.length > 0) {
121
+ throw new Error(`imposter refused an off-model payload for ${event}: ${violations.join('; ')}`);
122
+ }
123
+ record(event, wire, 'hook');
124
+ if (dropped('hook')) {
125
+ log(`dropped ${event}: hook channel is disconnected`);
126
+ return;
127
+ }
128
+ await hookEmitter.emit(event, wire, persona.schemaFor(event) ? event : fallbackRoute);
129
+ };
130
+ /**
131
+ * The app-server emitters. They funnel through the SAME envelope + ASM
132
+ * validation + record boundary as hooks do, because "exactly one place that
133
+ * can refuse" (§7.3 item 3) is a property of the imposter, not of the hook
134
+ * channel.
135
+ */
136
+ const notifyJsonRpc = (method, payload) => {
137
+ const envelopeMethod = persona.document.jsonrpcEventMethod;
138
+ if (envelopeMethod) {
139
+ const sessionId = (typeof bindings.$liveSessionId === 'string' && bindings.$liveSessionId) ||
140
+ (typeof bindings.$sessionId === 'string' && bindings.$sessionId) ||
141
+ '';
142
+ options.jsonrpc?.notify(envelopeMethod, { type: method, session_id: sessionId, payload });
143
+ return;
144
+ }
145
+ options.jsonrpc?.notify(method, payload);
146
+ };
147
+ const emitRpc = async (method, params) => {
148
+ const wire = wireFor(method, params);
149
+ const violations = persona.validate(method, wire);
150
+ if (violations.length > 0) {
151
+ throw new Error(`imposter refused an off-model payload for ${method}: ${violations.join('; ')}`);
152
+ }
153
+ record(method, wire, 'jsonrpc');
154
+ if (persona.document.nativeStore?.mirrorJsonRpc) {
155
+ if (!nativeStore)
156
+ throw new Error(`${method} needs a native session store, but none is configured`);
157
+ nativeStore.append(method, wire);
158
+ }
159
+ if (dropped('jsonrpc'))
160
+ return log(`dropped ${method}: app-server channel is disconnected`);
161
+ notifyJsonRpc(method, wire);
162
+ };
163
+ const replayRpc = async (method, params, notify) => {
164
+ const wire = wireFor(method, params);
165
+ const violations = persona.validate(method, wire);
166
+ if (violations.length > 0) {
167
+ throw new Error(`imposter refused an off-model replay for ${method}: ${violations.join('; ')}`);
168
+ }
169
+ record(method, wire, 'jsonrpc');
170
+ if (dropped('jsonrpc'))
171
+ return log(`dropped replay ${method}: app-server channel is disconnected`);
172
+ if (notify)
173
+ notify(method, wire);
174
+ else
175
+ notifyJsonRpc(method, wire);
176
+ };
177
+ const requestRpc = async (method, params) => {
178
+ const wire = wireFor(method, params);
179
+ const violations = persona.validate(method, wire);
180
+ if (violations.length > 0) {
181
+ throw new Error(`imposter refused an off-model payload for ${method}: ${violations.join('; ')}`);
182
+ }
183
+ record(method, wire, 'jsonrpc');
184
+ if (!options.jsonrpc)
185
+ throw new Error(`${method} needs a server request, but no app-server channel is wired`);
186
+ return options.jsonrpc.request(method, wire);
187
+ };
188
+ const sseRecord = (event, properties) => ({
189
+ id: `evt_${crypto.randomUUID().replaceAll('-', '')}`,
190
+ type: event,
191
+ properties,
192
+ });
193
+ const checkedSseRecord = (event, properties) => {
194
+ const wire = wireFor(event, properties);
195
+ const violations = persona.validate(event, wire);
196
+ if (violations.length > 0) {
197
+ throw new Error(`imposter refused an off-model payload for ${event}: ${violations.join('; ')}`);
198
+ }
199
+ const carrier = sseRecord(event, wire);
200
+ const carrierViolations = persona.validateRecord(event, carrier, persona.channelFor('sse'));
201
+ if (carrierViolations.length > 0) {
202
+ throw new Error(`imposter refused an off-model SSE carrier for ${event}: ${carrierViolations.join('; ')}`);
203
+ }
204
+ record(event, wire, 'sse');
205
+ return carrier;
206
+ };
207
+ const emitSse = async (event, properties) => {
208
+ const carrier = checkedSseRecord(event, properties);
209
+ if (dropped('sse'))
210
+ return log(`dropped ${event}: SSE channel is disconnected`);
211
+ options.sse?.publish(carrier);
212
+ };
213
+ const requestSse = async (event, properties) => {
214
+ const carrier = checkedSseRecord(event, properties);
215
+ if (!options.sse?.request)
216
+ throw new Error(`${event} needs an HTTP-resolved SSE blocker, but none is wired`);
217
+ if (dropped('sse'))
218
+ throw new Error(`${event} cannot ask while the SSE channel is disconnected`);
219
+ return options.sse.request(carrier);
220
+ };
221
+ /**
222
+ * Route a raw emission to the channel the ASM says the event belongs to.
223
+ *
224
+ * Scenarios and the control centre's trigger address events by NAME, never by
225
+ * channel, so with two families in play something has to decide the wire. The
226
+ * ASM already knows: every event declares its vendor channel, and
227
+ * `channelFor` maps that to a delivery kind. Without this every codex
228
+ * scenario would be posted to a hook channel codex does not have.
229
+ */
230
+ // Initialized after the session bindings exist. Emitters close over it but
231
+ // cannot run before `createImposterSession` has completed assembly.
232
+ let nativeStore;
233
+ const emitNativeLog = async (method, params) => {
234
+ const wire = wireFor(method, params);
235
+ const violations = persona.validate(method, wire);
236
+ if (violations.length > 0) {
237
+ throw new Error(`imposter refused an off-model payload for ${method}: ${violations.join('; ')}`);
238
+ }
239
+ record(method, wire, 'native-log');
240
+ if (dropped('native-log'))
241
+ return log(`dropped ${method}: native log channel is disconnected`);
242
+ if (!nativeStore)
243
+ throw new Error(`${method} needs a native session store, but none is configured`);
244
+ nativeStore.append(method, wire);
245
+ const update = params.update;
246
+ if (method === '_x.ai/session/update' &&
247
+ update !== null &&
248
+ typeof update === 'object' &&
249
+ !Array.isArray(update) &&
250
+ update.sessionUpdate === 'compaction_checkpoint') {
251
+ compactionCount += 1;
252
+ bindings.$compactionCount = compactionCount;
253
+ if (persona.schemaFor('signals.json')) {
254
+ await emitNativeState('signals.json', {
255
+ contextTokensUsed: usedTokens,
256
+ contextWindowTokens: capacityTokens,
257
+ contextWindowUsage: capacityTokens > 0 ? usedTokens / capacityTokens : 0,
258
+ primaryModelId: modelId,
259
+ compactionCount,
260
+ turnCount,
261
+ toolCallCount,
262
+ });
263
+ }
264
+ }
265
+ };
266
+ const emitNativeState = async (name, payload) => {
267
+ const wire = wireFor(name, payload);
268
+ const violations = persona.validate(name, wire);
269
+ if (violations.length > 0) {
270
+ throw new Error(`imposter refused an off-model payload for ${name}: ${violations.join('; ')}`);
271
+ }
272
+ record(name, wire, 'native-state');
273
+ if (dropped('native-state'))
274
+ return log(`dropped ${name}: native state channel is disconnected`);
275
+ if (!nativeStore)
276
+ throw new Error(`${name} needs a native session store, but none is configured`);
277
+ nativeStore.write(name, wire);
278
+ };
279
+ const emitNativeIndex = async (event, payload) => {
280
+ const wire = wireFor(event, payload);
281
+ const violations = persona.validate(event, wire);
282
+ if (violations.length > 0) {
283
+ throw new Error(`imposter refused an off-model payload for ${event}: ${violations.join('; ')}`);
284
+ }
285
+ record(event, wire, 'native-index');
286
+ if (dropped('native-index'))
287
+ return log(`dropped ${event}: native index channel is disconnected`);
288
+ if (!nativeStore)
289
+ throw new Error(`${event} needs a native session store, but none is configured`);
290
+ nativeStore.appendIndex(wire);
291
+ };
292
+ const routeFor = (event, selectedChannel) => {
293
+ const descriptor = persona.model.events.find((entry) => entry.event === event);
294
+ if (selectedChannel !== undefined && !persona.channels.includes(selectedChannel)) {
295
+ throw new Error(`imposter refused ${event} on unknown channel ${selectedChannel}`);
296
+ }
297
+ if (selectedChannel !== undefined && descriptor !== undefined && !descriptor.channels.includes(selectedChannel)) {
298
+ throw new Error(`imposter refused ${event} on ${selectedChannel}: declared rails are ${descriptor.channels.join(', ')}`);
299
+ }
300
+ const declared = selectedChannel ?? descriptor?.channel;
301
+ if (declared !== undefined) {
302
+ if (declared === persona.channelFor('jsonrpc'))
303
+ return 'jsonrpc';
304
+ if (declared === persona.channelFor('http'))
305
+ return 'http';
306
+ if (declared === persona.channelFor('sse'))
307
+ return 'sse';
308
+ if (declared === persona.channelFor('hook'))
309
+ return 'hook';
310
+ if (declared === persona.channelFor('native-log'))
311
+ return 'native-log';
312
+ if (declared === persona.channelFor('native-state'))
313
+ return 'native-state';
314
+ if (declared === persona.channelFor('native-index'))
315
+ return 'native-index';
316
+ }
317
+ // An event the model has never seen still has to reach a wire for ADR-008
318
+ // retention to be testable; send it down whichever one this vendor has.
319
+ if (persona.channelFor('hook') !== undefined)
320
+ return 'hook';
321
+ if (persona.channelFor('sse') !== undefined)
322
+ return 'sse';
323
+ return 'jsonrpc';
324
+ };
325
+ const emitAny = async (event, payload, channel) => {
326
+ const route = routeFor(event, channel);
327
+ if (route === 'jsonrpc')
328
+ return emitRpc(event, payload);
329
+ if (route === 'sse')
330
+ return emitSse(event, payload);
331
+ if (route === 'http')
332
+ throw new Error(`imposter cannot emit client HTTP request event ${event}`);
333
+ if (route === 'native-log')
334
+ return emitNativeLog(event, payload);
335
+ if (route === 'native-state')
336
+ return emitNativeState(event, payload);
337
+ if (route === 'native-index')
338
+ return emitNativeIndex(event, payload);
339
+ return emit(event, payload);
340
+ };
341
+ const status = behavior.statusLine ?? {};
342
+ const modelId = flagValue(argv, persona.flagsFor('model', '--model')) ?? status.modelId ?? `${persona.vendor}-imposter`;
343
+ const capacityTokens = status.capacityTokens ?? 200_000;
344
+ let usedTokens = 0;
345
+ let turnCount = 0;
346
+ let messageCount = 0;
347
+ let toolCallCount = 0;
348
+ let compactionCount = 0;
349
+ let assistantMessageStarted = false;
350
+ const statusPayload = () => {
351
+ const payload = {
352
+ session_id: sessionId,
353
+ transcript_path: transcriptPath,
354
+ cwd,
355
+ model: { id: modelId, display_name: status.modelDisplayName ?? modelId },
356
+ workspace: { current_dir: cwd },
357
+ context_window: usedTokens === 0
358
+ ? { total_input_tokens: 0, context_window_size: capacityTokens, current_usage: null }
359
+ : {
360
+ total_input_tokens: usedTokens,
361
+ context_window_size: capacityTokens,
362
+ used_percentage: Math.round((usedTokens / capacityTokens) * 1000) / 10,
363
+ current_usage: {
364
+ input_tokens: usedTokens,
365
+ cache_creation_input_tokens: 0,
366
+ cache_read_input_tokens: 0,
367
+ },
368
+ },
369
+ };
370
+ if (status.rateLimits) {
371
+ payload.rate_limits = Object.fromEntries(Object.entries(status.rateLimits).map(([id, window]) => [
372
+ id,
373
+ {
374
+ used_percentage: window.used_percentage,
375
+ resets_at: new Date(Date.now() + (window.resetsInSeconds ?? 3600) * 1000).toISOString(),
376
+ },
377
+ ]));
378
+ }
379
+ return payload;
380
+ };
381
+ const invokeStatusLine = async (payload) => {
382
+ if (dropped('statusline')) {
383
+ log('dropped statusline payload: channel is disconnected');
384
+ return;
385
+ }
386
+ await statusLineInvoker?.invoke(payload ?? statusPayload());
387
+ };
388
+ const guardedTranscript = {
389
+ path: transcript.path,
390
+ append: (entry) => {
391
+ if (dropped('transcript'))
392
+ return log('dropped transcript record: channel is disconnected');
393
+ transcript.append(entry);
394
+ },
395
+ appendPartial: (fragment) => {
396
+ if (dropped('transcript'))
397
+ return log('dropped transcript fragment: channel is disconnected');
398
+ transcript.appendPartial(fragment);
399
+ },
400
+ };
401
+ const bindings = {
402
+ $sessionId: sessionId,
403
+ $sessionTitle: sessionTitle,
404
+ $permissionMode: permissionMode,
405
+ $transcriptPath: transcriptPath,
406
+ $imposterHome: transcriptRoot,
407
+ $cwd: cwd,
408
+ $encodedCwd: encodeURIComponent(cwd),
409
+ $vendorVersion: persona.version,
410
+ $platformFamily: process.platform === 'win32' ? 'windows' : 'unix',
411
+ $platformOs: process.platform === 'darwin' ? 'macos' : process.platform === 'win32' ? 'windows' : process.platform,
412
+ $modelId: modelId,
413
+ $capacityTokens: capacityTokens,
414
+ $usedTokens: usedTokens,
415
+ $contextUsage: 0,
416
+ $turnCount: turnCount,
417
+ $turnIndex: 0,
418
+ $turnStep: '0.1',
419
+ $messageCount: messageCount,
420
+ $toolCallCount: toolCallCount,
421
+ $compactionCount: compactionCount,
422
+ $claudeMdPath: join(cwd, 'CLAUDE.md'),
423
+ ...(behavior.reply === undefined ? {} : { $reply: behavior.reply }),
424
+ };
425
+ // Persona-owned session vocabulary, minted once and layered over the base so
426
+ // it can reference it (`$threadCwd: "$cwd"`). The serve table's `bind` may
427
+ // overwrite any of these later, which is the point: codex's thread id is
428
+ // whatever the client's `thread/start` minted, and only interactively is it
429
+ // this one (types.ts `PersonaDocument.bindings`).
430
+ Object.assign(bindings, substitute(persona.document.bindings ?? {}, { bindings, uuids: new Map() }));
431
+ nativeStore = persona.document.nativeStore
432
+ ? createNativeSessionStore(transcriptRoot, persona.document.nativeStore, bindings, persona.document.nativeStore.mirrorJsonRpc
433
+ ? {}
434
+ : {
435
+ validateRecord: (method, carrier) => persona.validateRecord(method, carrier, persona.channelFor('native-log')),
436
+ })
437
+ : undefined;
438
+ if (nativeStore)
439
+ bindings.$nativeSessionDir = nativeStore.directory;
440
+ // One scenario driver per session, advanced by the portable op timeline. It
441
+ // exists to author organic traffic; Surface's native behavior graph is the
442
+ // separate source of truth for what the vendor actually exposes.
443
+ const scenarioDriver = createScenarioDriver();
444
+ const timeline = createOpTimeline({
445
+ persona,
446
+ // Advance FIRST, notify second, and never in one expression: `f?.(g())`
447
+ // does not evaluate `g()` when `f` is nullish, so folding these together
448
+ // left the driver frozen at `starting` for every caller that passed no
449
+ // `onScenarioDriver` — scenario intent silently depending on whether
450
+ // anyone happened to be watching it (found in review, 2026-08-08).
451
+ observe: (invocation) => {
452
+ if (nativeStore)
453
+ bindings.$nativeSessionDir = nativeStore.directory;
454
+ if (invocation.op === 'turn.start') {
455
+ turnCount += 1;
456
+ messageCount += 1;
457
+ assistantMessageStarted = false;
458
+ }
459
+ else if (invocation.op === 'assistant.delta' && !assistantMessageStarted) {
460
+ assistantMessageStarted = true;
461
+ messageCount += 1;
462
+ }
463
+ else if (invocation.op === 'tool.start') {
464
+ toolCallCount += 1;
465
+ }
466
+ if (invocation.op === 'usage.refresh') {
467
+ const nextUsedTokens = invocation.with?.usedTokens;
468
+ const addedTokens = invocation.with?.addedTokens;
469
+ if (typeof addedTokens === 'number' && Number.isFinite(addedTokens) && addedTokens >= 0) {
470
+ usedTokens += addedTokens;
471
+ }
472
+ else if (typeof nextUsedTokens === 'number' && Number.isFinite(nextUsedTokens) && nextUsedTokens >= 0) {
473
+ usedTokens = nextUsedTokens;
474
+ }
475
+ }
476
+ // Native-state templates are evaluated after this callback. Keeping the
477
+ // aggregate values in session bindings lets a persona write faithful
478
+ // cumulative summary/signals files without hard-coding a one-turn
479
+ // snapshot into its behavior document.
480
+ bindings.$usedTokens = usedTokens;
481
+ bindings.$contextUsage = capacityTokens > 0 ? usedTokens / capacityTokens : 0;
482
+ bindings.$turnCount = turnCount;
483
+ bindings.$turnIndex = Math.max(0, turnCount - 1);
484
+ bindings.$turnStep = `${Math.max(0, turnCount - 1)}.1`;
485
+ bindings.$messageCount = messageCount;
486
+ bindings.$toolCallCount = toolCallCount;
487
+ bindings.$compactionCount = compactionCount;
488
+ const { snapshot } = scenarioDriver.send(invocation.op);
489
+ options.onScenarioDriver?.(snapshot);
490
+ },
491
+ emitHook: emit,
492
+ emitJsonRpc: emitRpc,
493
+ emitSse,
494
+ requestJsonRpc: requestRpc,
495
+ requestSse,
496
+ emitNativeLog,
497
+ emitNativeState,
498
+ emitNativeIndex,
499
+ transcript: guardedTranscript,
500
+ statusline: async () => invokeStatusLine(),
501
+ present: options.present,
502
+ bindings,
503
+ statusPayload,
504
+ log,
505
+ });
506
+ const liveChannels = () => persona.channels.filter((channel) => !droppedChannels.has(channel));
507
+ const endSession = async (reason = 'other') => {
508
+ await timeline.run({ op: 'session.end', with: { reason } }).catch((error) => {
509
+ log(`session.end failed: ${error instanceof Error ? error.message : String(error)}`);
510
+ });
511
+ };
512
+ /**
513
+ * Process-level faults default to what a real vendor does when it dies.
514
+ * `setImmediate` is load-bearing: the control reply has to flush before the
515
+ * process goes away, or the console reports a fault as failed when it landed.
516
+ */
517
+ const halt = options.halt ??
518
+ ((kind, exitCode) => {
519
+ if (kind === 'hang') {
520
+ process.stdin.pause();
521
+ return;
522
+ }
523
+ setImmediate(() => {
524
+ if (kind === 'crash')
525
+ process.exit(exitCode);
526
+ else
527
+ void endSession('other').finally(() => process.exit(exitCode));
528
+ });
529
+ });
530
+ const applyFault = async (request) => {
531
+ switch (request.kind) {
532
+ case 'channel-drop': {
533
+ const channel = request.channel ?? 'hook';
534
+ droppedChannels.add(channel);
535
+ options.onChannels?.(liveChannels());
536
+ log(`fault: dropped the ${channel} channel`);
537
+ return;
538
+ }
539
+ case 'flood': {
540
+ // There is no vendor-neutral default payload, so the caller supplies
541
+ // one and the ASM refuses it if it is off-model — the same gate every
542
+ // trigger goes through (§7.3 item 3).
543
+ const event = request.event ?? persona.model.events[0]?.event;
544
+ if (!event)
545
+ throw new ControlError(REFUSED, 'flood requires an event');
546
+ for (let index = 0; index < (request.count ?? 100); index += 1)
547
+ await emitAny(event, request.with ?? {});
548
+ return;
549
+ }
550
+ case 'crash':
551
+ halt('crash', request.exitCode ?? 137);
552
+ return;
553
+ case 'exit':
554
+ halt('exit', request.exitCode ?? 0);
555
+ return;
556
+ case 'hang':
557
+ halt('hang', 0);
558
+ return;
559
+ }
560
+ };
561
+ const runner = createScenarioRunner({
562
+ emit: emitAny,
563
+ request: async (event, payload) => {
564
+ const route = routeFor(event);
565
+ if (route === 'jsonrpc')
566
+ return requestRpc(event, payload);
567
+ if (route === 'sse')
568
+ return requestSse(event, payload);
569
+ throw new Error(`scenario request ${event} is not carried by a reply-capable channel`);
570
+ },
571
+ transcript: guardedTranscript,
572
+ statusline: (payload) => invokeStatusLine(payload),
573
+ // Pre-flight validation sees exactly the wire payload `emit` will build,
574
+ // envelope included, so a scenario cannot pass here and be refused there.
575
+ validate: (event, payload) => persona.validate(event, wireFor(event, payload)),
576
+ fault: applyFault,
577
+ bindings,
578
+ log,
579
+ });
580
+ let activeScenario;
581
+ const pushScenarioRun = (progress) => {
582
+ try {
583
+ options.onScenarioRun?.({ ...progress });
584
+ }
585
+ catch (error) {
586
+ log(`scenario progress observer failed: ${error instanceof Error ? error.message : String(error)}`);
587
+ }
588
+ };
589
+ return {
590
+ sessionId,
591
+ transcriptPath,
592
+ transcriptRoot,
593
+ get liveChannels() {
594
+ return liveChannels();
595
+ },
596
+ emitted,
597
+ timeline,
598
+ bindings,
599
+ transcript: guardedTranscript,
600
+ get scenarioDriver() {
601
+ return scenarioDriver.snapshot();
602
+ },
603
+ emit: emitAny,
604
+ async restore(notify) {
605
+ if (!nativeStore || !nativeStore.exists()) {
606
+ throw new Error(`native session ${String(bindings.$sessionId)} does not exist`);
607
+ }
608
+ const signals = nativeStore.read('signals.json');
609
+ if (signals) {
610
+ const restoredTokens = signals.contextTokensUsed;
611
+ if (typeof restoredTokens === 'number' && Number.isFinite(restoredTokens) && restoredTokens >= 0) {
612
+ usedTokens = restoredTokens;
613
+ }
614
+ const restoredTurns = signals.turnCount;
615
+ if (typeof restoredTurns === 'number' && Number.isInteger(restoredTurns) && restoredTurns >= 0) {
616
+ turnCount = restoredTurns;
617
+ }
618
+ const restoredToolCalls = signals.toolCallCount;
619
+ if (typeof restoredToolCalls === 'number' && Number.isInteger(restoredToolCalls) && restoredToolCalls >= 0) {
620
+ toolCallCount = restoredToolCalls;
621
+ }
622
+ const restoredCompactions = signals.compactionCount;
623
+ if (typeof restoredCompactions === 'number' &&
624
+ Number.isInteger(restoredCompactions) &&
625
+ restoredCompactions >= 0) {
626
+ compactionCount = restoredCompactions;
627
+ }
628
+ }
629
+ const summary = nativeStore.read('summary.json');
630
+ const restoredMessages = [summary?.num_messages, summary?.num_chat_messages].find((value) => typeof value === 'number' && Number.isInteger(value) && value >= 0);
631
+ if (typeof restoredMessages === 'number' && Number.isInteger(restoredMessages) && restoredMessages >= 0) {
632
+ messageCount = restoredMessages;
633
+ }
634
+ if (typeof summary?.created_at === 'string' || typeof summary?.created_at === 'number') {
635
+ bindings.$sessionCreatedAt = summary.created_at;
636
+ }
637
+ bindings.$usedTokens = usedTokens;
638
+ bindings.$contextUsage = capacityTokens > 0 ? usedTokens / capacityTokens : 0;
639
+ bindings.$turnCount = turnCount;
640
+ bindings.$turnIndex = Math.max(0, turnCount - 1);
641
+ bindings.$turnStep = `${Math.max(0, turnCount - 1)}.1`;
642
+ bindings.$messageCount = messageCount;
643
+ bindings.$toolCallCount = toolCallCount;
644
+ bindings.$compactionCount = compactionCount;
645
+ for (const update of nativeStore.readUpdates()) {
646
+ const durableUpdate = update.params.update;
647
+ if (update.method === '_x.ai/session/update' &&
648
+ durableUpdate !== null &&
649
+ typeof durableUpdate === 'object' &&
650
+ !Array.isArray(durableUpdate) &&
651
+ durableUpdate.sessionUpdate === 'compaction_checkpoint') {
652
+ // Grok persists this checkpoint for its own reconstruction but does
653
+ // not expose it on the live extension method. Replaying it would
654
+ // fabricate a wire event the ASM intentionally marks persist-only.
655
+ continue;
656
+ }
657
+ const method = update.method === '_x.ai/session/update' ? '_x.ai/session_notification' : update.method;
658
+ await replayRpc(method, update.params, notify);
659
+ }
660
+ },
661
+ async runOp(op, argument = {}) {
662
+ // Resolved the same way a behavior pack's arguments are, so an op fired
663
+ // by hand and an op fired by a turn reach the timeline identically.
664
+ const resolved = substitute(argument, { bindings, uuids: new Map() });
665
+ await timeline.run({ op, with: resolved });
666
+ },
667
+ statusPayload,
668
+ invokeStatusLine,
669
+ dropChannel(channel) {
670
+ droppedChannels.add(channel);
671
+ options.onChannels?.(liveChannels());
672
+ },
673
+ applyFault,
674
+ async runScenario(document, runOptions = {}) {
675
+ if (activeScenario) {
676
+ throw new ControlError(REFUSED, `scenario ${activeScenario.progress.scenario ?? activeScenario.progress.runId} is already running`);
677
+ }
678
+ const mode = runOptions.mode ?? 'play';
679
+ const active = createScenarioGate(mode);
680
+ const runId = crypto.randomUUID();
681
+ let progress = {
682
+ runId,
683
+ ...(runOptions.scenario === undefined ? {} : { scenario: runOptions.scenario }),
684
+ ...(runOptions.runflowId === undefined ? {} : { runflowId: runOptions.runflowId }),
685
+ mode,
686
+ status: active.paused ? 'paused' : 'running',
687
+ step: 0,
688
+ steps: 0,
689
+ fromSequence: sequence + 1,
690
+ };
691
+ // prepare() validates the whole script and touches nothing, so a bad
692
+ // scenario fails the caller before the gate is ever published.
693
+ const prepared = runner.prepare(scenarioSteps(document), runOptions.stimulus ?? {}, {
694
+ speed: runOptions.speed ?? 1,
695
+ gate: active,
696
+ onProgress: ({ step, steps }) => {
697
+ if (activeScenario?.progress.runId !== runId)
698
+ return;
699
+ progress = { ...progress, step, steps, status: active.paused ? 'paused' : 'running' };
700
+ activeScenario.progress = progress;
701
+ pushScenarioRun(progress);
702
+ },
703
+ });
704
+ progress = { ...progress, steps: prepared.steps };
705
+ activeScenario = { gate: active, progress };
706
+ pushScenarioRun(progress);
707
+ const play = async () => {
708
+ try {
709
+ await prepared.play();
710
+ progress = { ...progress, status: 'completed', throughSequence: sequence };
711
+ if (activeScenario?.progress.runId === runId)
712
+ activeScenario.progress = progress;
713
+ pushScenarioRun(progress);
714
+ }
715
+ catch (error) {
716
+ const reason = (error instanceof Error ? error.message : String(error)) || 'scenario failed';
717
+ progress = {
718
+ ...progress,
719
+ status: 'failed',
720
+ throughSequence: sequence,
721
+ error: reason.slice(0, 2048),
722
+ };
723
+ if (activeScenario?.progress.runId === runId)
724
+ activeScenario.progress = progress;
725
+ pushScenarioRun(progress);
726
+ throw error;
727
+ }
728
+ finally {
729
+ if (activeScenario?.progress.runId === runId)
730
+ activeScenario = undefined;
731
+ }
732
+ };
733
+ if (mode === 'play') {
734
+ await play();
735
+ return;
736
+ }
737
+ void play().catch((error) => log(`scenario failed: ${error instanceof Error ? error.message : String(error)}`));
738
+ },
739
+ scenarioControl(action) {
740
+ if (!activeScenario)
741
+ throw new ControlError(REFUSED, 'no scenario is running');
742
+ if (action === 'pause')
743
+ activeScenario.gate.pause();
744
+ else if (action === 'step')
745
+ activeScenario.gate.step();
746
+ else
747
+ activeScenario.gate.resume();
748
+ activeScenario.progress = {
749
+ ...activeScenario.progress,
750
+ status: activeScenario.gate.paused ? 'paused' : 'running',
751
+ };
752
+ pushScenarioRun(activeScenario.progress);
753
+ },
754
+ async boot() {
755
+ await timeline.runAll(persona.document.boot);
756
+ },
757
+ async turn(text) {
758
+ const ops = behavior.ops ?? [];
759
+ if (ops.length === 0) {
760
+ log(`persona ${persona.vendor} has no behavior ops; the turn is a no-op`);
761
+ return;
762
+ }
763
+ timeline.beginTurn();
764
+ // Behavior templates resolve against the stimulus FIRST, so the timeline
765
+ // receives concrete op arguments and ops.json only ever sees `$op.*`.
766
+ const uuids = new Map();
767
+ for (const invocation of ops) {
768
+ const resolved = substitute(invocation.with ?? {}, {
769
+ scopes: { stimulus: { text } },
770
+ bindings,
771
+ uuids,
772
+ });
773
+ await timeline.run({ op: invocation.op, with: resolved });
774
+ }
775
+ usedTokens += status.tokensPerTurn ?? 0;
776
+ await invokeStatusLine();
777
+ },
778
+ end: endSession,
779
+ };
780
+ }
781
+ //# sourceMappingURL=session.js.map