@vibefield/puppeteer-imposter 0.0.0-stage → 0.2.1

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,705 @@
1
+ /**
2
+ * Persona loading (docs/archive/IMPOSTER.md §3.2).
3
+ *
4
+ * Reads the persona's own documents from `personas/<vendor>/`, then resolves
5
+ * its captured ASM out of the neutral Surface package. The ASM is NOT vendored
6
+ * here: it is capture-derived truth and stays Surface-owned, so adapter and
7
+ * imposter projections are measured against the same evidence.
8
+ */
9
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
10
+ import { createRequire } from 'node:module';
11
+ import { dirname, join } from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { isClaimAddressableAsmVersion, loadModel, validatePayload, } from '@vibefield/puppeteer-surface';
14
+ import { OP_NAMES, RUNFLOW_DANGERS, RUNFLOW_KINDS, } from "./types.js";
15
+ import { scenarioSteps } from "../session/scenario.js";
16
+ import { mintPersonaSessionId } from "./session-id.js";
17
+ const PERSONA_NAME = /^[a-z][a-z0-9-]{0,63}$/;
18
+ /** ASM channel kind -> the delivery mechanism the op layer addresses it by. */
19
+ const DELIVERY_KIND = {
20
+ 'hook-http': 'hook',
21
+ 'hook-command': 'hook',
22
+ 'hook-callback': 'hook',
23
+ 'webhook-http': 'hook',
24
+ transcript: 'transcript',
25
+ statusline: 'statusline',
26
+ jsonrpc: 'jsonrpc',
27
+ 'jsonrpc-stdio': 'jsonrpc',
28
+ 'app-server': 'jsonrpc',
29
+ acp: 'jsonrpc',
30
+ http: 'http',
31
+ sse: 'sse',
32
+ 'native-log': 'native-log',
33
+ 'native-state': 'native-state',
34
+ 'native-index': 'native-index',
35
+ };
36
+ /** `personas/` sits beside `dist/` when published and beside `src/` in-repo. */
37
+ function personasRoot() {
38
+ return join(dirname(dirname(dirname(fileURLToPath(import.meta.url)))), 'personas');
39
+ }
40
+ export function personaDirectory(vendor) {
41
+ if (!PERSONA_NAME.test(vendor)) {
42
+ throw new Error(`persona name must be lowercase letters, digits, and hyphens (got "${vendor}")`);
43
+ }
44
+ return join(personasRoot(), vendor);
45
+ }
46
+ /** Persona directory names, sorted. Cheap: one readdir, no JSON parsed. */
47
+ export function availablePersonas(root = personasRoot()) {
48
+ try {
49
+ return readdirSync(root, { withFileTypes: true })
50
+ .filter((entry) => entry.isDirectory() && PERSONA_NAME.test(entry.name))
51
+ .map((entry) => entry.name)
52
+ .sort();
53
+ }
54
+ catch {
55
+ return [];
56
+ }
57
+ }
58
+ /**
59
+ * Shim name → vendor, e.g. `claude` → `claude`. Built by reading each
60
+ * persona.json, so argv0 dispatch (§6) is answered by the same declaration a
61
+ * `ln -s` would be made from — the imposter installs nothing itself (§11.1).
62
+ */
63
+ export function shimNameMap(root = personasRoot()) {
64
+ const map = new Map();
65
+ for (const vendor of availablePersonas(root)) {
66
+ try {
67
+ const document = parsePersonaDocument(join(root, vendor, 'persona.json'), readJson(join(root, vendor, 'persona.json')));
68
+ for (const name of document.shimNames)
69
+ map.set(name, vendor);
70
+ }
71
+ catch {
72
+ // A malformed persona must not make every other persona unreachable.
73
+ }
74
+ }
75
+ return map;
76
+ }
77
+ function readJson(path) {
78
+ try {
79
+ return JSON.parse(readFileSync(path, 'utf8'));
80
+ }
81
+ catch (error) {
82
+ throw new Error(`imposter: cannot read ${path}: ${error.message}`);
83
+ }
84
+ }
85
+ function requireRecord(path, value, what) {
86
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
87
+ throw new Error(`imposter: ${path} ${what} must be an object`);
88
+ }
89
+ return value;
90
+ }
91
+ function requireString(path, record, field) {
92
+ const value = record[field];
93
+ if (typeof value !== 'string' || value.length === 0) {
94
+ throw new Error(`imposter: ${path} field "${field}" must be a non-empty string`);
95
+ }
96
+ return value;
97
+ }
98
+ function rejectUnknownFields(path, record, allowed) {
99
+ const unknown = Object.keys(record).filter((field) => !allowed.includes(field));
100
+ if (unknown.length > 0)
101
+ throw new Error(`imposter: ${path} has unknown field(s): ${unknown.join(', ')}`);
102
+ }
103
+ function stringList(path, value, field, maximum = 32) {
104
+ if (!Array.isArray(value) ||
105
+ value.length > maximum ||
106
+ value.some((entry) => typeof entry !== 'string' || entry.length === 0 || entry.length > 128)) {
107
+ throw new Error(`imposter: ${path} field "${field}" must be an array of at most ${maximum} non-empty strings`);
108
+ }
109
+ const values = value;
110
+ if (new Set(values).size !== values.length) {
111
+ throw new Error(`imposter: ${path} field "${field}" must not contain duplicates`);
112
+ }
113
+ return values;
114
+ }
115
+ const RUNFLOW_ID = /^[a-z][a-z0-9-]{0,63}$/;
116
+ const RUNFLOW_INTENT = /^[a-z][a-z0-9.-]{0,127}$/;
117
+ function actionFromStep(step) {
118
+ if (step === null || typeof step !== 'object' || Array.isArray(step))
119
+ return undefined;
120
+ const record = step;
121
+ const action = Object.hasOwn(record, 'do') ? record.do : record;
122
+ return action !== null && typeof action === 'object' && !Array.isArray(action)
123
+ ? action
124
+ : undefined;
125
+ }
126
+ /** Load the optional curated catalog and derive its executable facts. */
127
+ function loadRunflows(directory, eventChannels) {
128
+ const path = join(directory, 'runflows.json');
129
+ if (!existsSync(path))
130
+ return [];
131
+ const document = requireRecord(path, readJson(path), 'runflow catalog');
132
+ rejectUnknownFields(path, document, ['version', 'flows']);
133
+ if (document.version !== 1)
134
+ throw new Error(`imposter: ${path} field "version" must be 1`);
135
+ if (!Array.isArray(document.flows) || document.flows.length > 64) {
136
+ throw new Error(`imposter: ${path} field "flows" must be an array of at most 64 entries`);
137
+ }
138
+ const ids = new Set();
139
+ return document.flows.map((rawFlow, index) => {
140
+ const flow = requireRecord(path, rawFlow, `flow[${index}]`);
141
+ rejectUnknownFields(path, flow, [
142
+ 'id',
143
+ 'intent',
144
+ 'scenario',
145
+ 'title',
146
+ 'summary',
147
+ 'kind',
148
+ 'danger',
149
+ 'tags',
150
+ 'defaultStimulus',
151
+ 'defaultSpeed',
152
+ ]);
153
+ const id = requireString(path, flow, 'id');
154
+ if (!RUNFLOW_ID.test(id))
155
+ throw new Error(`imposter: ${path} runflow id "${id}" is invalid`);
156
+ if (ids.has(id))
157
+ throw new Error(`imposter: ${path} declares duplicate runflow id "${id}"`);
158
+ ids.add(id);
159
+ const intent = requireString(path, flow, 'intent');
160
+ if (!RUNFLOW_INTENT.test(intent))
161
+ throw new Error(`imposter: ${path} runflow intent "${intent}" is invalid`);
162
+ const scenario = requireString(path, flow, 'scenario');
163
+ if (!RUNFLOW_ID.test(scenario))
164
+ throw new Error(`imposter: ${path} scenario name "${scenario}" is invalid`);
165
+ const kind = requireString(path, flow, 'kind');
166
+ if (!RUNFLOW_KINDS.includes(kind)) {
167
+ throw new Error(`imposter: ${path} runflow "${id}" has unsupported kind "${kind}"`);
168
+ }
169
+ const danger = flow.danger === undefined ? 'safe' : requireString(path, flow, 'danger');
170
+ if (!RUNFLOW_DANGERS.includes(danger)) {
171
+ throw new Error(`imposter: ${path} runflow "${id}" has unsupported danger "${danger}"`);
172
+ }
173
+ const title = requireString(path, flow, 'title');
174
+ const summary = requireString(path, flow, 'summary');
175
+ if (title.length > 160 || summary.length > 1000) {
176
+ throw new Error(`imposter: ${path} runflow "${id}" title or summary is too long`);
177
+ }
178
+ const tags = flow.tags === undefined ? [] : stringList(path, flow.tags, 'tags', 16);
179
+ const defaultStimulus = flow.defaultStimulus === undefined
180
+ ? { text: 'triggered by adaptation devkit' }
181
+ : requireRecord(path, flow.defaultStimulus, `runflow "${id}" defaultStimulus`);
182
+ const defaultSpeed = flow.defaultSpeed === undefined ? 4 : flow.defaultSpeed;
183
+ if (typeof defaultSpeed !== 'number' || !Number.isFinite(defaultSpeed) || defaultSpeed <= 0 || defaultSpeed > 100) {
184
+ throw new Error(`imposter: ${path} runflow "${id}" defaultSpeed must be greater than 0 and at most 100`);
185
+ }
186
+ const scenarioPath = join(directory, 'scenarios', `${scenario}.json`);
187
+ if (!existsSync(scenarioPath)) {
188
+ throw new Error(`imposter: ${path} runflow "${id}" references missing scenario "${scenario}"`);
189
+ }
190
+ const scenarioDocument = requireRecord(scenarioPath, readJson(scenarioPath), 'scenario');
191
+ if (scenarioDocument.name !== scenario) {
192
+ throw new Error(`imposter: ${scenarioPath} must declare name "${scenario}"`);
193
+ }
194
+ const steps = scenarioSteps(scenarioDocument);
195
+ if (steps.length === 0 || steps.length > 10_000) {
196
+ throw new Error(`imposter: ${scenarioPath} must contain 1..10000 steps`);
197
+ }
198
+ const events = new Set();
199
+ const channels = new Set();
200
+ let requiresClient = false;
201
+ for (const step of steps) {
202
+ const emit = actionFromStep(step)?.emit;
203
+ if (!emit || typeof emit.event !== 'string')
204
+ continue;
205
+ events.add(emit.event);
206
+ for (const channel of eventChannels.get(emit.event) ?? [])
207
+ channels.add(channel);
208
+ if (typeof emit.channel === 'string')
209
+ channels.add(emit.channel);
210
+ if (emit.request === true)
211
+ requiresClient = true;
212
+ }
213
+ return {
214
+ id,
215
+ intent,
216
+ scenario,
217
+ title,
218
+ summary,
219
+ kind: kind,
220
+ danger: danger,
221
+ tags,
222
+ defaultStimulus,
223
+ defaultSpeed,
224
+ steps: steps.length,
225
+ events: [...events],
226
+ channels: [...channels],
227
+ requiresClient,
228
+ };
229
+ });
230
+ }
231
+ /**
232
+ * Surface exports only runtime APIs and its manifest, so a model is reached by
233
+ * resolving the package manifest and joining the declared persona path.
234
+ */
235
+ function resolveAsmDirectory(document, from, personaDir) {
236
+ // No package means the model is persona-local: there is no real vendor and
237
+ // therefore no evidence for Surface to own (the synthetic test persona).
238
+ if (!document.asm.package)
239
+ return join(personaDir, document.asm.path);
240
+ const require = createRequire(from);
241
+ let manifest;
242
+ try {
243
+ manifest = require.resolve(`${document.asm.package}/package.json`);
244
+ }
245
+ catch {
246
+ throw new Error(`imposter: persona "${document.vendor}" needs ${document.asm.package}, which is not installed. ` +
247
+ `Real-vendor ASMs stay Surface-owned, so the Surface package must be resolvable.`);
248
+ }
249
+ return join(dirname(manifest), document.asm.path);
250
+ }
251
+ function parsePersonaDocument(path, value) {
252
+ const record = requireRecord(path, value, 'persona');
253
+ const vendor = requireString(path, record, 'vendor');
254
+ const asm = requireRecord(path, record.asm, 'field "asm"');
255
+ const shimNames = record.shimNames;
256
+ if (!Array.isArray(shimNames) ||
257
+ shimNames.length === 0 ||
258
+ shimNames.some((name) => typeof name !== 'string' || name.length === 0)) {
259
+ throw new Error(`imposter: ${path} field "shimNames" must be a non-empty array of strings`);
260
+ }
261
+ const boot = record.boot;
262
+ if (!Array.isArray(boot))
263
+ throw new Error(`imposter: ${path} field "boot" must be an array`);
264
+ for (const [index, entry] of boot.entries()) {
265
+ const invocation = requireRecord(path, entry, `boot[${index}]`);
266
+ requireString(path, invocation, 'op');
267
+ }
268
+ const envelope = requireRecord(path, record.envelope, 'field "envelope"');
269
+ if (record.eventNameField !== undefined)
270
+ requireString(path, record, 'eventNameField');
271
+ if (record.jsonrpcEventMethod !== undefined)
272
+ requireString(path, record, 'jsonrpcEventMethod');
273
+ if (record.sessionIdTemplate !== undefined)
274
+ requireString(path, record, 'sessionIdTemplate');
275
+ // Every field is copied out by name rather than spread, so a persona cannot
276
+ // smuggle in a key this loader has never validated. The cost is that adding
277
+ // one to the type is not enough — `bindings` was silently dropped until it
278
+ // was named here too (2026-08-09).
279
+ const personaBindings = record.bindings === undefined ? undefined : requireRecord(path, record.bindings, '"bindings"');
280
+ for (const name of Object.keys(personaBindings ?? {})) {
281
+ if (!name.startsWith('$')) {
282
+ throw new Error(`imposter: ${path} binding "${name}" must start with $, or nothing will ever substitute it`);
283
+ }
284
+ }
285
+ const nativeStoreRecord = record.nativeStore === undefined ? undefined : requireRecord(path, record.nativeStore, '"nativeStore"');
286
+ let nativeStore;
287
+ if (nativeStoreRecord) {
288
+ const sessionPath = nativeStoreRecord.sessionPath;
289
+ if (!Array.isArray(sessionPath) ||
290
+ sessionPath.length === 0 ||
291
+ sessionPath.some((component) => typeof component !== 'string' || component.length === 0)) {
292
+ throw new Error(`imposter: ${path} nativeStore.sessionPath must be a non-empty array of strings`);
293
+ }
294
+ const updatesFile = nativeStoreRecord.updatesFile === undefined ? undefined : requireString(path, nativeStoreRecord, 'updatesFile');
295
+ const updatesPath = nativeStoreRecord.updatesPath;
296
+ if ((updatesFile === undefined) === (updatesPath === undefined)) {
297
+ throw new Error(`imposter: ${path} nativeStore must declare exactly one of updatesFile or updatesPath`);
298
+ }
299
+ if (updatesFile &&
300
+ (updatesFile.includes('/') || updatesFile.includes('\\') || updatesFile === '.' || updatesFile === '..')) {
301
+ throw new Error(`imposter: ${path} nativeStore.updatesFile must be a filename`);
302
+ }
303
+ if (updatesPath !== undefined &&
304
+ (!Array.isArray(updatesPath) ||
305
+ updatesPath.length === 0 ||
306
+ updatesPath.length > 16 ||
307
+ updatesPath.some((component) => typeof component !== 'string' || component.length === 0))) {
308
+ throw new Error(`imposter: ${path} nativeStore.updatesPath must be an array of 1..16 non-empty strings`);
309
+ }
310
+ const indexPath = nativeStoreRecord.indexPath;
311
+ if (indexPath !== undefined &&
312
+ (!Array.isArray(indexPath) ||
313
+ indexPath.length === 0 ||
314
+ indexPath.length > 16 ||
315
+ indexPath.some((component) => typeof component !== 'string' || component.length === 0))) {
316
+ throw new Error(`imposter: ${path} nativeStore.indexPath must be an array of 1..16 non-empty strings`);
317
+ }
318
+ const recordFormat = nativeStoreRecord.recordFormat;
319
+ if (recordFormat !== undefined && !['method-params', 'flat-record'].includes(String(recordFormat))) {
320
+ throw new Error(`imposter: ${path} nativeStore.recordFormat must be method-params or flat-record`);
321
+ }
322
+ const fieldName = (value, label) => {
323
+ if (typeof value !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(value)) {
324
+ throw new Error(`imposter: ${path} nativeStore.${label} must be a safe field name`);
325
+ }
326
+ return value;
327
+ };
328
+ const stringArray = (value, label) => {
329
+ if (value === undefined)
330
+ return undefined;
331
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string' || entry.length === 0)) {
332
+ throw new Error(`imposter: ${path} nativeStore.${label} must be an array of non-empty strings`);
333
+ }
334
+ return value;
335
+ };
336
+ const recordTypeField = nativeStoreRecord.recordTypeField === undefined
337
+ ? undefined
338
+ : fieldName(nativeStoreRecord.recordTypeField, 'recordTypeField');
339
+ const recordPayloadField = nativeStoreRecord.recordPayloadField === undefined
340
+ ? undefined
341
+ : fieldName(nativeStoreRecord.recordPayloadField, 'recordPayloadField');
342
+ const timestampRecord = nativeStoreRecord.recordTimestamp === undefined
343
+ ? undefined
344
+ : requireRecord(path, nativeStoreRecord.recordTimestamp, 'nativeStore.recordTimestamp');
345
+ let recordTimestamp;
346
+ if (timestampRecord) {
347
+ const format = requireString(path, timestampRecord, 'format');
348
+ if (!['epoch-ms', 'iso'].includes(format)) {
349
+ throw new Error(`imposter: ${path} nativeStore.recordTimestamp.format must be epoch-ms or iso`);
350
+ }
351
+ const omitFor = stringArray(timestampRecord.omitFor, 'recordTimestamp.omitFor');
352
+ recordTimestamp = {
353
+ field: fieldName(timestampRecord.field, 'recordTimestamp.field'),
354
+ format: format,
355
+ ...(omitFor === undefined ? {} : { omitFor }),
356
+ };
357
+ }
358
+ const sequenceRecord = nativeStoreRecord.recordSequence === undefined
359
+ ? undefined
360
+ : requireRecord(path, nativeStoreRecord.recordSequence, 'nativeStore.recordSequence');
361
+ let recordSequence;
362
+ if (sequenceRecord) {
363
+ if (sequenceRecord.start !== undefined &&
364
+ (!Number.isInteger(sequenceRecord.start) || sequenceRecord.start < 0)) {
365
+ throw new Error(`imposter: ${path} nativeStore.recordSequence.start must be a non-negative integer`);
366
+ }
367
+ recordSequence = {
368
+ field: fieldName(sequenceRecord.field, 'recordSequence.field'),
369
+ ...(sequenceRecord.start === undefined ? {} : { start: sequenceRecord.start }),
370
+ };
371
+ }
372
+ const identityRecord = nativeStoreRecord.recordIdentity === undefined
373
+ ? undefined
374
+ : requireRecord(path, nativeStoreRecord.recordIdentity, 'nativeStore.recordIdentity');
375
+ let recordIdentity;
376
+ if (identityRecord) {
377
+ const omitParentFor = stringArray(identityRecord.omitParentFor, 'recordIdentity.omitParentFor');
378
+ recordIdentity = {
379
+ idField: fieldName(identityRecord.idField, 'recordIdentity.idField'),
380
+ ...(identityRecord.parentField === undefined
381
+ ? {}
382
+ : { parentField: fieldName(identityRecord.parentField, 'recordIdentity.parentField') }),
383
+ ...(omitParentFor === undefined ? {} : { omitParentFor }),
384
+ };
385
+ }
386
+ const singletonEvents = stringArray(nativeStoreRecord.singletonEvents, 'singletonEvents');
387
+ if (nativeStoreRecord.mirrorJsonRpc !== undefined && typeof nativeStoreRecord.mirrorJsonRpc !== 'boolean') {
388
+ throw new Error(`imposter: ${path} nativeStore.mirrorJsonRpc must be a boolean`);
389
+ }
390
+ nativeStore = {
391
+ ...(nativeStoreRecord.rootEnv === undefined
392
+ ? {}
393
+ : { rootEnv: requireString(path, nativeStoreRecord, 'rootEnv') }),
394
+ sessionPath: sessionPath,
395
+ ...(updatesFile === undefined ? {} : { updatesFile }),
396
+ ...(updatesPath === undefined ? {} : { updatesPath: updatesPath }),
397
+ ...(indexPath === undefined ? {} : { indexPath: indexPath }),
398
+ ...(recordFormat === undefined
399
+ ? {}
400
+ : { recordFormat: recordFormat }),
401
+ ...(recordTypeField === undefined ? {} : { recordTypeField }),
402
+ ...(recordPayloadField === undefined ? {} : { recordPayloadField }),
403
+ ...(recordTimestamp === undefined ? {} : { recordTimestamp }),
404
+ ...(recordSequence === undefined ? {} : { recordSequence }),
405
+ ...(recordIdentity === undefined ? {} : { recordIdentity }),
406
+ ...(singletonEvents === undefined ? {} : { singletonEvents }),
407
+ ...(nativeStoreRecord.mirrorJsonRpc === undefined
408
+ ? {}
409
+ : { mirrorJsonRpc: nativeStoreRecord.mirrorJsonRpc }),
410
+ };
411
+ }
412
+ return {
413
+ vendor,
414
+ asm: {
415
+ ...(asm.package === undefined ? {} : { package: requireString(path, asm, 'package') }),
416
+ path: requireString(path, asm, 'path'),
417
+ },
418
+ shimNames: shimNames,
419
+ envelope,
420
+ ...(record.eventNameField === undefined ? {} : { eventNameField: record.eventNameField }),
421
+ ...(record.jsonrpcEventMethod === undefined ? {} : { jsonrpcEventMethod: record.jsonrpcEventMethod }),
422
+ ...(record.sessionIdTemplate === undefined ? {} : { sessionIdTemplate: record.sessionIdTemplate }),
423
+ ...(personaBindings === undefined ? {} : { bindings: personaBindings }),
424
+ ...(nativeStore === undefined ? {} : { nativeStore }),
425
+ boot: boot,
426
+ };
427
+ }
428
+ function parseOpsDocument(path, value, eventChannels, channelByKind) {
429
+ const record = requireRecord(path, value, 'ops');
430
+ const ops = {};
431
+ for (const [op, rawBindings] of Object.entries(record)) {
432
+ if (!OP_NAMES.includes(op)) {
433
+ throw new Error(`imposter: ${path} declares unknown op "${op}" (known: ${OP_NAMES.join(', ')})`);
434
+ }
435
+ if (!Array.isArray(rawBindings) || rawBindings.length === 0) {
436
+ throw new Error(`imposter: ${path} op "${op}" must be a non-empty array of bindings`);
437
+ }
438
+ ops[op] = rawBindings.map((rawBinding, index) => {
439
+ const binding = requireRecord(path, rawBinding, `op "${op}" binding ${index}`);
440
+ const channel = requireString(path, binding, 'channel');
441
+ if (!['hook', 'transcript', 'statusline', 'jsonrpc', 'sse', 'native-log', 'native-state', 'native-index'].includes(channel)) {
442
+ throw new Error(`imposter: ${path} op "${op}" has unsupported channel "${channel}"`);
443
+ }
444
+ if (binding.event !== undefined && (typeof binding.event !== 'string' || binding.event.length === 0)) {
445
+ throw new Error(`imposter: ${path} op "${op}" field "event" must be a non-empty string`);
446
+ }
447
+ if (binding.with !== undefined)
448
+ requireRecord(path, binding.with, `op "${op}" field "with"`);
449
+ if (binding.await !== undefined && typeof binding.await !== 'boolean') {
450
+ throw new Error(`imposter: ${path} op "${op}" field "await" must be a boolean`);
451
+ }
452
+ if (binding.await === true && channel !== 'jsonrpc' && channel !== 'sse') {
453
+ throw new Error(`imposter: ${path} op "${op}" sets "await" on the ${channel} channel, which cannot reply`);
454
+ }
455
+ // An op bound to a hook event the ASM has never seen would emit an
456
+ // unmodeled payload, which is exactly what §7.3 item 3 forbids.
457
+ if ((channel === 'hook' ||
458
+ channel === 'jsonrpc' ||
459
+ channel === 'sse' ||
460
+ channel === 'native-log' ||
461
+ channel === 'native-state' ||
462
+ channel === 'native-index') &&
463
+ typeof binding.event === 'string' &&
464
+ !eventChannels.has(binding.event)) {
465
+ throw new Error(`imposter: ${path} op "${op}" binds ${channel} event "${binding.event}", which is not in the ASM`);
466
+ }
467
+ if (typeof binding.event === 'string' && eventChannels.has(binding.event)) {
468
+ const nativeChannel = channelByKind.get(channel);
469
+ if (nativeChannel === undefined) {
470
+ throw new Error(`imposter: ${path} op "${op}" uses ${channel}, but the ASM declares no such channel kind`);
471
+ }
472
+ if (!eventChannels.get(binding.event).includes(nativeChannel)) {
473
+ throw new Error(`imposter: ${path} op "${op}" binds ${binding.event} to ${nativeChannel}, ` +
474
+ `but the ASM declares it on ${eventChannels.get(binding.event).join(', ')}`);
475
+ }
476
+ }
477
+ if (binding.await !== undefined && typeof binding.await !== 'boolean') {
478
+ throw new Error(`imposter: ${path} op "${op}" field "await" must be a boolean`);
479
+ }
480
+ return {
481
+ channel: channel,
482
+ ...(binding.await === undefined ? {} : { await: binding.await }),
483
+ ...(binding.event === undefined ? {} : { event: binding.event }),
484
+ ...(binding.with === undefined ? {} : { with: binding.with }),
485
+ };
486
+ });
487
+ }
488
+ return ops;
489
+ }
490
+ const HTTP_ACTIONS = new Set([
491
+ 'event.subscribe',
492
+ 'session.create',
493
+ 'session.list',
494
+ 'session.get',
495
+ 'session.messages',
496
+ 'session.status',
497
+ 'session.prompt',
498
+ 'session.abort',
499
+ 'session.children',
500
+ 'session.diff',
501
+ 'session.delete',
502
+ 'session.update',
503
+ 'session.fork',
504
+ 'permission.list',
505
+ 'permission.reply',
506
+ 'question.list',
507
+ 'question.reply',
508
+ 'question.reject',
509
+ 'vcs.diff',
510
+ ]);
511
+ function parseHttpServeDocument(path, value) {
512
+ const document = requireRecord(path, value, 'HTTP serve document');
513
+ rejectUnknownFields(path, document, ['$server', 'routes']);
514
+ const server = requireRecord(path, document.$server, 'field "$server"');
515
+ rejectUnknownFields(path, server, [
516
+ 'command',
517
+ 'hostnameFlag',
518
+ 'portFlag',
519
+ 'defaultHostname',
520
+ 'defaultPort',
521
+ 'directoryQuery',
522
+ 'directoryHeader',
523
+ 'auth',
524
+ 'attach',
525
+ ]);
526
+ const auth = requireRecord(path, server.auth, '$server.auth');
527
+ rejectUnknownFields(path, auth, ['usernameEnv', 'passwordEnv', 'defaultUsername']);
528
+ const attach = requireRecord(path, server.attach, '$server.attach');
529
+ rejectUnknownFields(path, attach, ['command', 'sessionFlag', 'directoryFlag']);
530
+ if (!Number.isInteger(server.defaultPort) ||
531
+ server.defaultPort < 0 ||
532
+ server.defaultPort > 65535) {
533
+ throw new Error(`imposter: ${path} $server.defaultPort must be an integer from 0 to 65535`);
534
+ }
535
+ if (!Array.isArray(document.routes) || document.routes.length === 0 || document.routes.length > 256) {
536
+ throw new Error(`imposter: ${path} field "routes" must be an array of 1..256 routes`);
537
+ }
538
+ const signatures = new Set();
539
+ const routes = document.routes.map((rawRoute, index) => {
540
+ const route = requireRecord(path, rawRoute, `routes[${index}]`);
541
+ rejectUnknownFields(path, route, ['event', 'method', 'path', 'action']);
542
+ const method = requireString(path, route, 'method').toUpperCase();
543
+ const routePath = requireString(path, route, 'path');
544
+ const action = requireString(path, route, 'action');
545
+ if (!/^[A-Z]+$/.test(method))
546
+ throw new Error(`imposter: ${path} route method "${method}" is invalid`);
547
+ if (!routePath.startsWith('/'))
548
+ throw new Error(`imposter: ${path} route path "${routePath}" must start with /`);
549
+ if (!HTTP_ACTIONS.has(action))
550
+ throw new Error(`imposter: ${path} route action "${action}" is unsupported`);
551
+ const signature = `${method} ${routePath}`;
552
+ if (signatures.has(signature))
553
+ throw new Error(`imposter: ${path} declares duplicate route ${signature}`);
554
+ signatures.add(signature);
555
+ return { event: requireString(path, route, 'event'), method, path: routePath, action };
556
+ });
557
+ return {
558
+ $server: {
559
+ command: requireString(path, server, 'command'),
560
+ hostnameFlag: requireString(path, server, 'hostnameFlag'),
561
+ portFlag: requireString(path, server, 'portFlag'),
562
+ defaultHostname: requireString(path, server, 'defaultHostname'),
563
+ defaultPort: server.defaultPort,
564
+ directoryQuery: requireString(path, server, 'directoryQuery'),
565
+ directoryHeader: requireString(path, server, 'directoryHeader').toLowerCase(),
566
+ auth: {
567
+ usernameEnv: requireString(path, auth, 'usernameEnv'),
568
+ passwordEnv: requireString(path, auth, 'passwordEnv'),
569
+ defaultUsername: requireString(path, auth, 'defaultUsername'),
570
+ },
571
+ attach: {
572
+ command: requireString(path, attach, 'command'),
573
+ sessionFlag: requireString(path, attach, 'sessionFlag'),
574
+ directoryFlag: requireString(path, attach, 'directoryFlag'),
575
+ },
576
+ },
577
+ routes,
578
+ };
579
+ }
580
+ export function loadPersona(vendor, options = {}) {
581
+ const directory = options.directory ?? personaDirectory(vendor);
582
+ const personaPath = join(directory, 'persona.json');
583
+ const document = parsePersonaDocument(personaPath, readJson(personaPath));
584
+ if (document.vendor !== vendor) {
585
+ throw new Error(`imposter: ${personaPath} declares vendor "${document.vendor}" but lives in "${vendor}"`);
586
+ }
587
+ const model = loadModel(resolveAsmDirectory(document, options.resolveFrom ?? import.meta.url, directory));
588
+ const events = new Map(model.events.map((event) => [event.event, event]));
589
+ const schemas = new Map(model.events.map((event) => [event.event, event.payloadSchema]));
590
+ const resultSchemas = new Map(model.events.map((event) => [event.event, event.resultSchema]));
591
+ const recordSchemas = new Map(model.events.map((event) => [event.event, event.recordSchema]));
592
+ const recordChannels = new Map(model.events.map((event) => [event.event, event.recordChannel]));
593
+ const eventChannels = new Map(model.events.map((event) => [event.event, event.channels]));
594
+ // The ASM records what each channel *is*; the op layer addresses channels by
595
+ // what they *do*. First declaration of a kind wins, which is why the ASM
596
+ // lists a channel's primary transport in `kind` and its fallback separately.
597
+ const channelByKind = new Map();
598
+ for (const [name, channel] of Object.entries(model.channels.channels)) {
599
+ const kind = DELIVERY_KIND[channel.kind ?? ''];
600
+ if (kind && !channelByKind.has(kind))
601
+ channelByKind.set(kind, name);
602
+ }
603
+ // serve.json is optional: only the JSON-RPC family serves anything.
604
+ const servePath = join(directory, 'serve.json');
605
+ const serve = existsSync(servePath)
606
+ ? requireRecord(servePath, readJson(servePath), 'serve document')
607
+ : undefined;
608
+ const httpServePath = join(directory, 'http-serve.json');
609
+ const httpServe = existsSync(httpServePath)
610
+ ? parseHttpServeDocument(httpServePath, readJson(httpServePath))
611
+ : undefined;
612
+ if (serve && httpServe) {
613
+ throw new Error(`imposter: ${directory} cannot declare both serve.json and http-serve.json`);
614
+ }
615
+ if (serve && isClaimAddressableAsmVersion(model.manifest.asmVersion)) {
616
+ for (const [method, rawEntry] of Object.entries(serve)) {
617
+ if (method === '$server')
618
+ continue;
619
+ requireRecord(servePath, rawEntry, `method "${method}"`);
620
+ const event = events.get(method);
621
+ if (!event)
622
+ throw new Error(`imposter: ${servePath} serves ${method}, but that method is not in the ASM`);
623
+ if (event.direction !== 'client-to-agent' || event.transport !== 'jsonrpc-request') {
624
+ throw new Error(`imposter: ${servePath} serves ${method}, but the ASM does not declare it as a client-to-agent JSON-RPC request`);
625
+ }
626
+ if (!event.resultSchema) {
627
+ throw new Error(`imposter: ${servePath} serves ${method}, but the ASM has no result schema for it`);
628
+ }
629
+ }
630
+ }
631
+ if (httpServe && isClaimAddressableAsmVersion(model.manifest.asmVersion)) {
632
+ for (const route of httpServe.routes) {
633
+ const event = events.get(route.event);
634
+ if (!event)
635
+ throw new Error(`imposter: ${httpServePath} serves ${route.event}, but it is not in the ASM`);
636
+ if (event.direction !== 'client-to-agent' || event.transport !== 'http') {
637
+ throw new Error(`imposter: ${httpServePath} serves ${route.event}, but the ASM does not declare it as client-to-agent HTTP`);
638
+ }
639
+ if (!event.resultSchema) {
640
+ throw new Error(`imposter: ${httpServePath} serves ${route.event}, but the ASM has no result schema for it`);
641
+ }
642
+ const method = event.resultSchema.properties?.method?.enum;
643
+ const path = event.resultSchema.properties?.route?.enum;
644
+ if (method && !method.includes(route.method)) {
645
+ throw new Error(`imposter: ${httpServePath} declares ${route.method} for ${route.event}, but the ASM declares ${method.join(', ')}`);
646
+ }
647
+ if (path && !path.includes(route.path)) {
648
+ throw new Error(`imposter: ${httpServePath} declares ${route.path} for ${route.event}, but the ASM declares ${path.join(', ')}`);
649
+ }
650
+ }
651
+ }
652
+ const opsPath = join(directory, 'ops.json');
653
+ const ops = parseOpsDocument(opsPath, readJson(opsPath), eventChannels, channelByKind);
654
+ const runflows = loadRunflows(directory, eventChannels);
655
+ const flagTable = {
656
+ ...(model.detection.launchFlags && typeof model.detection.launchFlags === 'object'
657
+ ? model.detection.launchFlags
658
+ : {}),
659
+ ...(model.detection.probedFlags && typeof model.detection.probedFlags === 'object'
660
+ ? model.detection.probedFlags
661
+ : {}),
662
+ };
663
+ return {
664
+ vendor,
665
+ ...(serve === undefined ? {} : { serve }),
666
+ ...(httpServe === undefined ? {} : { httpServe }),
667
+ version: model.manifest.vendorVersion,
668
+ document,
669
+ model,
670
+ ops,
671
+ runflows,
672
+ channels: Object.keys(model.channels.channels),
673
+ channelFor: (kind) => channelByKind.get(kind),
674
+ schemaFor: (event) => schemas.get(event),
675
+ resultSchemaFor: (event) => resultSchemas.get(event),
676
+ recordSchemaFor: (event) => recordSchemas.get(event),
677
+ validate(event, payload) {
678
+ const schema = schemas.get(event);
679
+ return schema ? validatePayload(schema, payload) : [];
680
+ },
681
+ validateResult(event, result) {
682
+ const schema = resultSchemas.get(event);
683
+ return schema ? validatePayload(schema, result) : [];
684
+ },
685
+ validateRecord(event, record, channel) {
686
+ const schema = recordSchemas.get(event);
687
+ const scopedChannel = recordChannels.get(event);
688
+ if (scopedChannel !== undefined && channel !== scopedChannel)
689
+ return [];
690
+ return schema ? validatePayload(schema, record) : [];
691
+ },
692
+ flagsFor(key, fallback) {
693
+ const raw = flagTable[key];
694
+ return (typeof raw === 'string' ? raw : fallback)
695
+ .split(',')
696
+ .map((flag) => flag.trim())
697
+ .filter(Boolean);
698
+ },
699
+ };
700
+ }
701
+ /** Resolve and apply the persona-owned native session identity convention. */
702
+ export function createPersonaSessionId(vendor, options = {}) {
703
+ return mintPersonaSessionId(loadPersona(vendor, options));
704
+ }
705
+ //# sourceMappingURL=load.js.map