@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.
- package/LICENSE +21 -0
- package/bin/ai.mjs +17 -0
- package/dist/cli/argv.d.ts +40 -0
- package/dist/cli/argv.d.ts.map +1 -0
- package/dist/cli/argv.js +62 -0
- package/dist/cli/argv.js.map +1 -0
- package/dist/cli/http-persona.d.ts +15 -0
- package/dist/cli/http-persona.d.ts.map +1 -0
- package/dist/cli/http-persona.js +216 -0
- package/dist/cli/http-persona.js.map +1 -0
- package/dist/cli/main.d.ts +11 -0
- package/dist/cli/main.d.ts.map +1 -0
- package/dist/cli/main.js +671 -0
- package/dist/cli/main.js.map +1 -0
- package/dist/cli/prompt-line.d.ts +27 -0
- package/dist/cli/prompt-line.d.ts.map +1 -0
- package/dist/cli/prompt-line.js +93 -0
- package/dist/cli/prompt-line.js.map +1 -0
- package/dist/control/client.d.ts +51 -0
- package/dist/control/client.d.ts.map +1 -0
- package/dist/control/client.js +206 -0
- package/dist/control/client.js.map +1 -0
- package/dist/control/index.d.ts +10 -0
- package/dist/control/index.d.ts.map +1 -0
- package/dist/control/index.js +10 -0
- package/dist/control/index.js.map +1 -0
- package/dist/control/peer.d.ts +42 -0
- package/dist/control/peer.d.ts.map +1 -0
- package/dist/control/peer.js +174 -0
- package/dist/control/peer.js.map +1 -0
- package/dist/control/protocol.d.ts +207 -0
- package/dist/control/protocol.d.ts.map +1 -0
- package/dist/control/protocol.js +535 -0
- package/dist/control/protocol.js.map +1 -0
- package/dist/index.d.ts +36 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +36 -0
- package/dist/index.js.map +1 -0
- package/dist/persona/launch.d.ts +7 -0
- package/dist/persona/launch.d.ts.map +1 -0
- package/dist/persona/launch.js +26 -0
- package/dist/persona/launch.js.map +1 -0
- package/dist/persona/load.d.ts +28 -0
- package/dist/persona/load.d.ts.map +1 -0
- package/dist/persona/load.js +705 -0
- package/dist/persona/load.js.map +1 -0
- package/dist/persona/session-id.d.ts +4 -0
- package/dist/persona/session-id.d.ts.map +1 -0
- package/dist/persona/session-id.js +12 -0
- package/dist/persona/session-id.js.map +1 -0
- package/dist/persona/types.d.ts +265 -0
- package/dist/persona/types.d.ts.map +1 -0
- package/dist/persona/types.js +38 -0
- package/dist/persona/types.js.map +1 -0
- package/dist/session/channels/hook.d.ts +31 -0
- package/dist/session/channels/hook.d.ts.map +1 -0
- package/dist/session/channels/hook.js +114 -0
- package/dist/session/channels/hook.js.map +1 -0
- package/dist/session/channels/http-sse.d.ts +67 -0
- package/dist/session/channels/http-sse.d.ts.map +1 -0
- package/dist/session/channels/http-sse.js +212 -0
- package/dist/session/channels/http-sse.js.map +1 -0
- package/dist/session/channels/jsonrpc.d.ts +56 -0
- package/dist/session/channels/jsonrpc.d.ts.map +1 -0
- package/dist/session/channels/jsonrpc.js +196 -0
- package/dist/session/channels/jsonrpc.js.map +1 -0
- package/dist/session/channels/leader-ipc.d.ts +27 -0
- package/dist/session/channels/leader-ipc.d.ts.map +1 -0
- package/dist/session/channels/leader-ipc.js +314 -0
- package/dist/session/channels/leader-ipc.js.map +1 -0
- package/dist/session/channels/native-store.d.ts +31 -0
- package/dist/session/channels/native-store.d.ts.map +1 -0
- package/dist/session/channels/native-store.js +275 -0
- package/dist/session/channels/native-store.js.map +1 -0
- package/dist/session/channels/statusline.d.ts +20 -0
- package/dist/session/channels/statusline.d.ts.map +1 -0
- package/dist/session/channels/statusline.js +48 -0
- package/dist/session/channels/statusline.js.map +1 -0
- package/dist/session/channels/terminal.d.ts +27 -0
- package/dist/session/channels/terminal.d.ts.map +1 -0
- package/dist/session/channels/terminal.js +108 -0
- package/dist/session/channels/terminal.js.map +1 -0
- package/dist/session/channels/transcript.d.ts +16 -0
- package/dist/session/channels/transcript.d.ts.map +1 -0
- package/dist/session/channels/transcript.js +24 -0
- package/dist/session/channels/transcript.js.map +1 -0
- package/dist/session/channels/ws-unix.d.ts +57 -0
- package/dist/session/channels/ws-unix.d.ts.map +1 -0
- package/dist/session/channels/ws-unix.js +396 -0
- package/dist/session/channels/ws-unix.js.map +1 -0
- package/dist/session/http-session-server.d.ts +31 -0
- package/dist/session/http-session-server.d.ts.map +1 -0
- package/dist/session/http-session-server.js +508 -0
- package/dist/session/http-session-server.js.map +1 -0
- package/dist/session/scenario-driver.d.ts +105 -0
- package/dist/session/scenario-driver.d.ts.map +1 -0
- package/dist/session/scenario-driver.js +211 -0
- package/dist/session/scenario-driver.js.map +1 -0
- package/dist/session/scenario.d.ts +119 -0
- package/dist/session/scenario.d.ts.map +1 -0
- package/dist/session/scenario.js +299 -0
- package/dist/session/scenario.js.map +1 -0
- package/dist/session/serve.d.ts +124 -0
- package/dist/session/serve.d.ts.map +1 -0
- package/dist/session/serve.js +136 -0
- package/dist/session/serve.js.map +1 -0
- package/dist/session/session.d.ts +125 -0
- package/dist/session/session.d.ts.map +1 -0
- package/dist/session/session.js +781 -0
- package/dist/session/session.js.map +1 -0
- package/dist/session/template.d.ts +35 -0
- package/dist/session/template.d.ts.map +1 -0
- package/dist/session/template.js +133 -0
- package/dist/session/template.js.map +1 -0
- package/dist/session/timeline.d.ts +81 -0
- package/dist/session/timeline.d.ts.map +1 -0
- package/dist/session/timeline.js +155 -0
- package/dist/session/timeline.js.map +1 -0
- package/dist/tui/app.d.ts +30 -0
- package/dist/tui/app.d.ts.map +1 -0
- package/dist/tui/app.js +72 -0
- package/dist/tui/app.js.map +1 -0
- package/dist/tui/mount.d.ts +37 -0
- package/dist/tui/mount.d.ts.map +1 -0
- package/dist/tui/mount.js +88 -0
- package/dist/tui/mount.js.map +1 -0
- package/dist/tui/store.d.ts +38 -0
- package/dist/tui/store.d.ts.map +1 -0
- package/dist/tui/store.js +56 -0
- package/dist/tui/store.js.map +1 -0
- package/dist/tui/theme.d.ts +40 -0
- package/dist/tui/theme.d.ts.map +1 -0
- package/dist/tui/theme.js +54 -0
- package/dist/tui/theme.js.map +1 -0
- package/package.json +67 -3
- package/personas/antigravity/behavior/happy-turn.json +9 -0
- package/personas/antigravity/ops.json +14 -0
- package/personas/antigravity/persona.json +15 -0
- package/personas/antigravity/runflows.json +6 -0
- package/personas/antigravity/scenarios/happy-turn.json +25 -0
- package/personas/claude/behavior/happy-turn.json +19 -0
- package/personas/claude/ops.json +128 -0
- package/personas/claude/persona.json +29 -0
- package/personas/claude/runflows.json +45 -0
- package/personas/claude/scenarios/channel-disconnect.json +19 -0
- package/personas/claude/scenarios/crash-mid-turn.json +42 -0
- package/personas/claude/scenarios/cross-layer-implementation.json +488 -0
- package/personas/claude/scenarios/deep-research.json +494 -0
- package/personas/claude/scenarios/duplicate-out-of-order.json +57 -0
- package/personas/claude/scenarios/flood.json +11 -0
- package/personas/claude/scenarios/happy-turn.json +57 -0
- package/personas/claude/scenarios/incident-investigation.json +465 -0
- package/personas/claude/scenarios/late-after-exit.json +27 -0
- package/personas/claude/scenarios/permission-allow.json +55 -0
- package/personas/claude/scenarios/permission-deny.json +71 -0
- package/personas/claude/scenarios/token-usage-refresh.json +33 -0
- package/personas/claude/scenarios/unknown-event.json +14 -0
- package/personas/codex/behavior/approval-turn.json +15 -0
- package/personas/codex/behavior/happy-turn.json +10 -0
- package/personas/codex/ops.json +159 -0
- package/personas/codex/persona.json +36 -0
- package/personas/codex/runflows.json +45 -0
- package/personas/codex/scenarios/channel-disconnect.json +31 -0
- package/personas/codex/scenarios/crash-mid-turn.json +30 -0
- package/personas/codex/scenarios/cross-layer-implementation.json +725 -0
- package/personas/codex/scenarios/deep-research.json +684 -0
- package/personas/codex/scenarios/duplicate-out-of-order.json +87 -0
- package/personas/codex/scenarios/flood.json +22 -0
- package/personas/codex/scenarios/happy-turn.json +81 -0
- package/personas/codex/scenarios/incident-investigation.json +695 -0
- package/personas/codex/scenarios/late-after-exit.json +59 -0
- package/personas/codex/scenarios/permission-allow.json +110 -0
- package/personas/codex/scenarios/permission-deny.json +83 -0
- package/personas/codex/scenarios/token-usage-refresh.json +49 -0
- package/personas/codex/scenarios/unknown-event.json +17 -0
- package/personas/codex/serve.json +124 -0
- package/personas/copilot/behavior/happy-turn.json +9 -0
- package/personas/copilot/ops.json +28 -0
- package/personas/copilot/persona.json +17 -0
- package/personas/copilot/runflows.json +6 -0
- package/personas/copilot/scenarios/happy-turn.json +50 -0
- package/personas/grok/behavior/approval-turn.json +16 -0
- package/personas/grok/behavior/happy-turn.json +13 -0
- package/personas/grok/ops.json +330 -0
- package/personas/grok/persona.json +24 -0
- package/personas/grok/runflows.json +25 -0
- package/personas/grok/scenarios/agent-team-lifecycle.json +74 -0
- package/personas/grok/scenarios/compact-lifecycle.json +61 -0
- package/personas/grok/serve.json +57 -0
- package/personas/hermes/behavior/approval-turn.json +11 -0
- package/personas/hermes/behavior/happy-turn.json +9 -0
- package/personas/hermes/ops.json +227 -0
- package/personas/hermes/persona.json +15 -0
- package/personas/hermes/runflows.json +50 -0
- package/personas/hermes/scenarios/happy-turn.json +25 -0
- package/personas/hermes/scenarios/late-after-exit.json +21 -0
- package/personas/hermes/scenarios/permission-deny.json +54 -0
- package/personas/hermes/scenarios/unknown-event.json +14 -0
- package/personas/hermes/serve.json +54 -0
- package/personas/kimi/behavior/happy-turn.json +9 -0
- package/personas/kimi/ops.json +357 -0
- package/personas/kimi/persona.json +23 -0
- package/personas/kimi/runflows.json +84 -0
- package/personas/kimi/scenarios/compaction-lifecycle.json +20 -0
- package/personas/kimi/scenarios/duplicate-out-of-order.json +60 -0
- package/personas/kimi/scenarios/happy-turn.json +66 -0
- package/personas/kimi/scenarios/late-after-end.json +28 -0
- package/personas/kimi/scenarios/tool-failure.json +43 -0
- package/personas/kimi/scenarios/tool-success.json +57 -0
- package/personas/kimi/scenarios/unknown-record.json +15 -0
- package/personas/opencode/README.md +32 -0
- package/personas/opencode/behavior/happy-turn.json +9 -0
- package/personas/opencode/behavior/permission-turn.json +18 -0
- package/personas/opencode/http-serve.json +72 -0
- package/personas/opencode/ops.json +250 -0
- package/personas/opencode/persona.json +22 -0
- package/personas/opencode/runflows.json +45 -0
- package/personas/opencode/scenarios/duplicate-event.json +27 -0
- package/personas/opencode/scenarios/failure.json +30 -0
- package/personas/opencode/scenarios/happy-turn.json +86 -0
- package/personas/opencode/scenarios/late-event.json +29 -0
- package/personas/opencode/scenarios/out-of-order.json +42 -0
- package/personas/opencode/scenarios/permission-allow.json +31 -0
- package/personas/opencode/scenarios/permission-deny.json +31 -0
- package/personas/opencode/scenarios/question-reject.json +37 -0
- package/personas/opencode/scenarios/question-reply.json +38 -0
- package/personas/opencode/scenarios/reconnect.json +22 -0
- package/personas/opencode/scenarios/resume.json +30 -0
- package/personas/opencode/scenarios/unknown-event.json +15 -0
- package/personas/pi/behavior/happy-turn.json +9 -0
- package/personas/pi/ops.json +19 -0
- package/personas/pi/persona.json +16 -0
- package/personas/pi/runflows.json +6 -0
- package/personas/pi/scenarios/happy-turn.json +52 -0
- package/personas/synthetic/behavior/happy-turn.json +12 -0
- package/personas/synthetic/groundtruth.html +164 -0
- package/personas/synthetic/groundtruth.json +380 -0
- package/personas/synthetic/model/behavior.json +27 -0
- package/personas/synthetic/model/channels.json +16 -0
- package/personas/synthetic/model/detection.json +13 -0
- package/personas/synthetic/model/events/agent.action.json +16 -0
- package/personas/synthetic/model/events/agent.boot.json +16 -0
- package/personas/synthetic/model/events/agent.halt.json +16 -0
- package/personas/synthetic/model/events/agent.prompt.json +16 -0
- package/personas/synthetic/model/events/agent.reply.json +16 -0
- package/personas/synthetic/model/events/agent.settled.json +16 -0
- package/personas/synthetic/model/manifest.json +7 -0
- package/personas/synthetic/ops.json +18 -0
- package/personas/synthetic/persona.json +11 -0
- package/README.md +0 -3
package/dist/cli/main.js
ADDED
|
@@ -0,0 +1,671 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `ai` entry point (docs/archive/IMPOSTER.md §6).
|
|
3
|
+
*
|
|
4
|
+
* Answers the vendor's detection surface from the ASM (`--version`, `--help`),
|
|
5
|
+
* then brings up a session on the vendor's real channels. The TUI is not here:
|
|
6
|
+
* presentation is a sink the session writes frames to, and until phase I4 that
|
|
7
|
+
* sink is a plain append-only stdout log. Headless is not a fallback — CI runs
|
|
8
|
+
* it (§4.2).
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
11
|
+
import { dirname, join } from 'node:path';
|
|
12
|
+
import { connectControl } from "../control/client.js";
|
|
13
|
+
import { ControlError, nativeEventsFromModel, NOT_FOUND, opsFromPersona } from "../control/protocol.js";
|
|
14
|
+
import { loadPersona, personaDirectory, shimNameMap } from "../persona/load.js";
|
|
15
|
+
import { createAppServerChannel, METHOD_NOT_FOUND, RpcError, } from "../session/channels/jsonrpc.js";
|
|
16
|
+
import { connectUnixWebSocket, listenUnixWebSocket } from "../session/channels/ws-unix.js";
|
|
17
|
+
import { connectLeaderAcp, listenLeaderRelay } from "../session/channels/leader-ipc.js";
|
|
18
|
+
import { installPromptLine } from "./prompt-line.js";
|
|
19
|
+
import { createServeDispatcher, matchesInvocation } from "../session/serve.js";
|
|
20
|
+
import { createImposterSession } from "../session/session.js";
|
|
21
|
+
import { substitute } from "../session/template.js";
|
|
22
|
+
import { createPresentation } from "../tui/mount.js";
|
|
23
|
+
import { flagValue, hasFlag, PersonaSelectionError, selectPersona } from "./argv.js";
|
|
24
|
+
import { runHttpPersonaAttached, runHttpPersonaServer } from "./http-persona.js";
|
|
25
|
+
const SAFE_NAME = /^[a-z0-9][a-z0-9-]{0,127}$/i;
|
|
26
|
+
function safeName(name, what) {
|
|
27
|
+
if (!SAFE_NAME.test(name))
|
|
28
|
+
throw new Error(`${what} must contain only letters, numbers, and hyphens`);
|
|
29
|
+
return name;
|
|
30
|
+
}
|
|
31
|
+
function loadBehavior(persona, name) {
|
|
32
|
+
const path = join(personaDirectory(persona.vendor), 'behavior', `${safeName(name, 'behavior name')}.json`);
|
|
33
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
34
|
+
}
|
|
35
|
+
/** Named scenarios are persona-owned data; the control channel addresses them by name. */
|
|
36
|
+
function loadScenario(persona, name) {
|
|
37
|
+
const path = join(personaDirectory(persona.vendor), 'scenarios', `${safeName(name, 'scenario name')}.json`);
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (error.code === 'ENOENT') {
|
|
43
|
+
throw new ControlError(NOT_FOUND, `no scenario named ${name}`);
|
|
44
|
+
}
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function detectionText(persona, field, fallback) {
|
|
49
|
+
const value = persona.model.detection[field];
|
|
50
|
+
return typeof value === 'string' ? value : fallback;
|
|
51
|
+
}
|
|
52
|
+
/** Address schemes this build can actually serve. A persona may declare only these. */
|
|
53
|
+
const IMPLEMENTED_TRANSPORTS = new Set(['unix']);
|
|
54
|
+
/**
|
|
55
|
+
* Own the coordination socket used by a leader-based vendor.
|
|
56
|
+
*
|
|
57
|
+
* Grok's controller and TUI both connect using the public leader framing. The
|
|
58
|
+
* relay namespaces viewer request ids and routes them to the one controller
|
|
59
|
+
* that owns the materialized session; it does not create another timeline.
|
|
60
|
+
*/
|
|
61
|
+
async function runLeader(persona, argv, log) {
|
|
62
|
+
const spec = persona.serve?.$server?.leader;
|
|
63
|
+
if (!spec)
|
|
64
|
+
return 2;
|
|
65
|
+
const socketPath = flagValue(argv, [spec.socketFlag]);
|
|
66
|
+
if (!socketPath) {
|
|
67
|
+
process.stderr.write(`${spec.socketFlag} requires a socket path\n`);
|
|
68
|
+
return 2;
|
|
69
|
+
}
|
|
70
|
+
if (process.platform === 'win32') {
|
|
71
|
+
process.stderr.write(`persona ${persona.vendor} leader sockets are not implemented on Windows\n`);
|
|
72
|
+
return 2;
|
|
73
|
+
}
|
|
74
|
+
if (!existsSync(dirname(socketPath))) {
|
|
75
|
+
process.stderr.write(`leader socket directory does not exist: ${dirname(socketPath)}\n`);
|
|
76
|
+
return 2;
|
|
77
|
+
}
|
|
78
|
+
// The adapter gives every backend a private directory, so an existing name
|
|
79
|
+
// means the invocation is malformed or stale. Refuse it: deleting a
|
|
80
|
+
// caller-supplied socket could disconnect an unrelated local service.
|
|
81
|
+
if (existsSync(socketPath)) {
|
|
82
|
+
process.stderr.write(`leader socket path already exists: ${socketPath}\n`);
|
|
83
|
+
return 2;
|
|
84
|
+
}
|
|
85
|
+
const relay = await listenLeaderRelay(socketPath, persona.version, log);
|
|
86
|
+
log(`leader listening on ${socketPath}`);
|
|
87
|
+
const close = () => {
|
|
88
|
+
void relay.close().finally(() => process.exit(0));
|
|
89
|
+
};
|
|
90
|
+
process.once('SIGTERM', close);
|
|
91
|
+
process.once('SIGINT', close);
|
|
92
|
+
await new Promise(() => { });
|
|
93
|
+
return 0;
|
|
94
|
+
}
|
|
95
|
+
/** A Grok terminal is an ACP client of the leader, never a second session. */
|
|
96
|
+
async function runLeaderViewer(persona, socketPath, sessionId, log) {
|
|
97
|
+
let connection;
|
|
98
|
+
try {
|
|
99
|
+
connection = await connectLeaderAcp(socketPath, 'viewer', sessionId, persona.version, log);
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
process.stderr.write(`could not join leader at ${socketPath}: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
103
|
+
return 1;
|
|
104
|
+
}
|
|
105
|
+
const screen = await createPresentation({
|
|
106
|
+
vendor: persona.vendor,
|
|
107
|
+
version: persona.version,
|
|
108
|
+
sessionId,
|
|
109
|
+
channels: [persona.channelFor('jsonrpc') ?? 'acp', 'leader', 'terminal'],
|
|
110
|
+
});
|
|
111
|
+
let closing = false;
|
|
112
|
+
let finish;
|
|
113
|
+
const finished = new Promise((resolve) => {
|
|
114
|
+
finish = resolve;
|
|
115
|
+
});
|
|
116
|
+
const shutdown = async (exitCode = 0) => {
|
|
117
|
+
if (closing)
|
|
118
|
+
return;
|
|
119
|
+
closing = true;
|
|
120
|
+
if (screen.interactive && process.stdin.isTTY)
|
|
121
|
+
process.stdout.write('\x1b[?2004l');
|
|
122
|
+
connection.close();
|
|
123
|
+
await screen.stop();
|
|
124
|
+
finish(exitCode);
|
|
125
|
+
};
|
|
126
|
+
process.once('SIGTERM', () => void shutdown());
|
|
127
|
+
process.once('SIGINT', () => void shutdown());
|
|
128
|
+
const channel = createAppServerChannel({
|
|
129
|
+
input: connection.input,
|
|
130
|
+
output: connection.output,
|
|
131
|
+
jsonrpc: '2.0',
|
|
132
|
+
serve: (method) => Promise.reject(new RpcError(METHOD_NOT_FOUND, `a viewer cannot answer ${method}`)),
|
|
133
|
+
notified: (method, params) => screen.frame({ at: new Date().toISOString(), op: method, with: params }),
|
|
134
|
+
onClose: () => void shutdown(),
|
|
135
|
+
log,
|
|
136
|
+
});
|
|
137
|
+
const failed = (what, error) => {
|
|
138
|
+
const message = `${what}: ${error instanceof Error ? error.message : String(error)}`;
|
|
139
|
+
screen.notice(message);
|
|
140
|
+
log(message);
|
|
141
|
+
};
|
|
142
|
+
try {
|
|
143
|
+
await channel.request('initialize', {
|
|
144
|
+
protocolVersion: 1,
|
|
145
|
+
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } },
|
|
146
|
+
});
|
|
147
|
+
await channel.request('session/load', { sessionId, cwd: process.cwd(), mcpServers: [] });
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
failed('leader attach failed', error);
|
|
151
|
+
await shutdown(1);
|
|
152
|
+
return finished;
|
|
153
|
+
}
|
|
154
|
+
screen.scenario('leader-attached');
|
|
155
|
+
installPromptLine({
|
|
156
|
+
interactive: screen.interactive,
|
|
157
|
+
staged: (text) => screen.staged(text),
|
|
158
|
+
submit: (text) => {
|
|
159
|
+
log(`session/prompt on ${sessionId} (${text.length} chars)`);
|
|
160
|
+
void channel
|
|
161
|
+
.request('session/prompt', { sessionId, prompt: [{ type: 'text', text }] })
|
|
162
|
+
.catch((error) => failed('turn failed', error));
|
|
163
|
+
},
|
|
164
|
+
interrupt: () => void shutdown(),
|
|
165
|
+
end: () => void shutdown(),
|
|
166
|
+
log,
|
|
167
|
+
});
|
|
168
|
+
return finished;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Where a serving invocation should listen, read from the persona's own
|
|
172
|
+
* declaration rather than a hardcoded flag (serve.ts `ServeServer.listen`).
|
|
173
|
+
*
|
|
174
|
+
* No flag means stdio, which is the vendor's own default. An address the
|
|
175
|
+
* imposter cannot honour is an error and never a quiet fallback to stdio: the
|
|
176
|
+
* adapter waits for a socket file that would never appear, and "hung" is a much
|
|
177
|
+
* worse thing to debug than "refused".
|
|
178
|
+
*/
|
|
179
|
+
function listenTarget(persona, argv) {
|
|
180
|
+
const spec = persona.serve?.$server?.listen;
|
|
181
|
+
if (!spec)
|
|
182
|
+
return {};
|
|
183
|
+
const address = flagValue(argv, [spec.flag]);
|
|
184
|
+
if (address === undefined)
|
|
185
|
+
return {};
|
|
186
|
+
const match = /^([a-z][a-z0-9+.-]*):\/\/(.+)$/i.exec(address);
|
|
187
|
+
if (!match) {
|
|
188
|
+
return { error: `${spec.flag} expects an address like ${spec.transports[0] ?? 'unix'}:///path/to.sock` };
|
|
189
|
+
}
|
|
190
|
+
const scheme = match[1].toLowerCase();
|
|
191
|
+
if (!spec.transports.includes(scheme)) {
|
|
192
|
+
return {
|
|
193
|
+
error: `persona ${persona.vendor} does not serve over ${scheme}:// (declares ${spec.transports.join(', ')})`,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
if (!IMPLEMENTED_TRANSPORTS.has(scheme)) {
|
|
197
|
+
return { error: `the imposter cannot serve over ${scheme}:// yet (has ${[...IMPLEMENTED_TRANSPORTS].join(', ')})` };
|
|
198
|
+
}
|
|
199
|
+
return { socketPath: match[2] };
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Join a session another process owns, and draw it (§11.5).
|
|
203
|
+
*
|
|
204
|
+
* The vendor's own TUI is a CLIENT of its app-server — `codex resume <id>
|
|
205
|
+
* --remote unix://…` renders a thread the server is running. The imposter is
|
|
206
|
+
* the same shape here: no session, no op timeline, no scenario driver. It sends the
|
|
207
|
+
* prompt the person types and draws the notifications that come back, which is
|
|
208
|
+
* exactly as much as the real one does over this connection.
|
|
209
|
+
*
|
|
210
|
+
* Nothing is inferred from what arrives. A notification is drawn under the
|
|
211
|
+
* method name the server used, and the ADAPTER — which has its own connection
|
|
212
|
+
* to the same server — remains the only thing deriving semantics (ADR-003).
|
|
213
|
+
*/
|
|
214
|
+
async function runAttached(persona, argv, address, log) {
|
|
215
|
+
const match = /^([a-z][a-z0-9+.-]*):\/\/(.+)$/i.exec(address);
|
|
216
|
+
if (!match || match[1].toLowerCase() !== 'unix') {
|
|
217
|
+
process.stderr.write(`the imposter can only attach over unix:// (got "${address}")\n`);
|
|
218
|
+
return 2;
|
|
219
|
+
}
|
|
220
|
+
// `resume <id>` — the id the server already owns. Bare `--remote` would ask
|
|
221
|
+
// for a new thread, which is the mistake tui-session.ts calls out: it creates
|
|
222
|
+
// a second, unmaterialized thread nobody is observing.
|
|
223
|
+
const threadId = flagValue(argv, persona.flagsFor('resume', 'resume')) ?? '(unnamed thread)';
|
|
224
|
+
let connection;
|
|
225
|
+
try {
|
|
226
|
+
connection = await connectUnixWebSocket(match[2]);
|
|
227
|
+
}
|
|
228
|
+
catch (error) {
|
|
229
|
+
process.stderr.write(`could not attach to ${address}: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
230
|
+
return 1;
|
|
231
|
+
}
|
|
232
|
+
const screen = await createPresentation({
|
|
233
|
+
vendor: persona.vendor,
|
|
234
|
+
version: persona.version,
|
|
235
|
+
sessionId: threadId,
|
|
236
|
+
channels: [persona.channelFor('jsonrpc') ?? 'jsonrpc', 'terminal'],
|
|
237
|
+
});
|
|
238
|
+
let closing = false;
|
|
239
|
+
const shutdown = async (exitCode = 0) => {
|
|
240
|
+
if (closing)
|
|
241
|
+
await new Promise(() => { });
|
|
242
|
+
closing = true;
|
|
243
|
+
if (screen.interactive && process.stdin.isTTY)
|
|
244
|
+
process.stdout.write('\x1b[?2004l');
|
|
245
|
+
connection.close();
|
|
246
|
+
await screen.stop();
|
|
247
|
+
process.exit(exitCode);
|
|
248
|
+
};
|
|
249
|
+
process.once('SIGTERM', () => void shutdown());
|
|
250
|
+
process.once('SIGINT', () => void shutdown());
|
|
251
|
+
const channel = createAppServerChannel({
|
|
252
|
+
input: connection.input,
|
|
253
|
+
output: connection.output,
|
|
254
|
+
// A viewer answers nothing. Approvals belong to the client that drives the
|
|
255
|
+
// session, and the server sends them there (see `driver` below); an error
|
|
256
|
+
// is the honest reply if one ever arrives here anyway.
|
|
257
|
+
serve: (method) => Promise.reject(new RpcError(METHOD_NOT_FOUND, `a viewer cannot answer ${method}`)),
|
|
258
|
+
notified: (method, params) => screen.frame({ at: new Date().toISOString(), op: method, with: params }),
|
|
259
|
+
onClose: () => void shutdown(),
|
|
260
|
+
log,
|
|
261
|
+
});
|
|
262
|
+
// Both, not either. A notice reaches whoever is looking at the pane; the log
|
|
263
|
+
// reaches whoever is debugging one they cannot see — and for a viewer inside
|
|
264
|
+
// a Godview pane, the second is the only one anybody can read.
|
|
265
|
+
const failed = (what, error) => {
|
|
266
|
+
const message = `${what}: ${error instanceof Error ? error.message : String(error)}`;
|
|
267
|
+
screen.notice(message);
|
|
268
|
+
log(message);
|
|
269
|
+
};
|
|
270
|
+
screen.scenario('attached');
|
|
271
|
+
log(`attaching to ${threadId} on ${match[2]}`);
|
|
272
|
+
await channel.request('thread/resume', { threadId }).catch((error) => failed('resume failed', error));
|
|
273
|
+
installPromptLine({
|
|
274
|
+
interactive: screen.interactive,
|
|
275
|
+
staged: (text) => screen.staged(text),
|
|
276
|
+
// The same request the adapter's own driver sends, field for field: the
|
|
277
|
+
// server cannot tell the two apart, which is what makes a prompt typed in
|
|
278
|
+
// the pane and one injected by puppeteer the same event.
|
|
279
|
+
submit: (text) => {
|
|
280
|
+
log(`turn/start on ${threadId} (${text.length} chars)`);
|
|
281
|
+
void channel
|
|
282
|
+
.request('turn/start', {
|
|
283
|
+
threadId,
|
|
284
|
+
input: [{ type: 'text', text }],
|
|
285
|
+
clientUserMessageId: `imposter-tui-${Date.now()}`,
|
|
286
|
+
})
|
|
287
|
+
.catch((error) => failed('turn failed', error));
|
|
288
|
+
},
|
|
289
|
+
interrupt: () => void shutdown(),
|
|
290
|
+
end: () => void shutdown(),
|
|
291
|
+
log,
|
|
292
|
+
});
|
|
293
|
+
await new Promise(() => { });
|
|
294
|
+
return 0;
|
|
295
|
+
}
|
|
296
|
+
export async function main(argv, argv0) {
|
|
297
|
+
// `ai` has no subcommands of its own. Everything after persona selection
|
|
298
|
+
// belongs to the vendor, which is what lets the adapter's real launch recipe
|
|
299
|
+
// through untouched — and is why the tool has nothing to collide with.
|
|
300
|
+
const shims = shimNameMap();
|
|
301
|
+
let selection;
|
|
302
|
+
try {
|
|
303
|
+
selection = selectPersona(argv, { argv0, env: process.env, shims });
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
if (error instanceof PersonaSelectionError) {
|
|
307
|
+
process.stderr.write(`${error.message}\n`);
|
|
308
|
+
return 2;
|
|
309
|
+
}
|
|
310
|
+
throw error;
|
|
311
|
+
}
|
|
312
|
+
const persona = loadPersona(selection.vendor);
|
|
313
|
+
const rest = selection.rest;
|
|
314
|
+
// Detection surface, answered from the ASM so it cannot drift from what the
|
|
315
|
+
// adapter's probe expects (ADAPTING-AN-AGENT step 4).
|
|
316
|
+
const versionFlag = detectionText(persona, 'versionFlag', '--version');
|
|
317
|
+
const helpFlag = detectionText(persona, 'helpFlag', '--help');
|
|
318
|
+
if (hasFlag(rest, versionFlag)) {
|
|
319
|
+
process.stdout.write(`${detectionText(persona, 'versionOutput', `${persona.version} (imposter)`)}\n`);
|
|
320
|
+
return 0;
|
|
321
|
+
}
|
|
322
|
+
if (hasFlag(rest, helpFlag)) {
|
|
323
|
+
const flags = ['sessionId', 'resume', 'settings', 'name', 'permissionMode', 'model'];
|
|
324
|
+
process.stdout.write(`Usage: ${persona.vendor} [options]\n`);
|
|
325
|
+
for (const key of flags) {
|
|
326
|
+
const aliases = persona.flagsFor(key, '');
|
|
327
|
+
if (aliases.length > 0)
|
|
328
|
+
process.stdout.write(` ${aliases.join(', ')} <value>\n`);
|
|
329
|
+
}
|
|
330
|
+
return 0;
|
|
331
|
+
}
|
|
332
|
+
const behaviorName = flagValue(rest, ['--behavior']) ?? 'happy-turn';
|
|
333
|
+
const log = (message) => {
|
|
334
|
+
if (process.env.PUPPETEER_IMPOSTER_DEBUG)
|
|
335
|
+
process.stderr.write(`[imposter] ${message}\n`);
|
|
336
|
+
};
|
|
337
|
+
const httpServer = persona.httpServe?.$server;
|
|
338
|
+
if (httpServer && rest[0] === httpServer.command) {
|
|
339
|
+
return runHttpPersonaServer({
|
|
340
|
+
persona,
|
|
341
|
+
argv: rest,
|
|
342
|
+
behavior: loadBehavior(persona, behaviorName),
|
|
343
|
+
env: process.env,
|
|
344
|
+
cwd: process.cwd(),
|
|
345
|
+
log,
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
if (httpServer && rest[0] === httpServer.attach.command) {
|
|
349
|
+
return runHttpPersonaAttached({
|
|
350
|
+
persona,
|
|
351
|
+
argv: rest,
|
|
352
|
+
behavior: loadBehavior(persona, behaviorName),
|
|
353
|
+
env: process.env,
|
|
354
|
+
cwd: process.cwd(),
|
|
355
|
+
log,
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
const leader = persona.serve?.$server?.leader;
|
|
359
|
+
if (leader && matchesInvocation(rest, leader))
|
|
360
|
+
return runLeader(persona, rest, log);
|
|
361
|
+
// ATTACH comes before everything else, because it is the one invocation that
|
|
362
|
+
// owns no session at all (§11.5). `codex resume <id> --remote unix://…` is a
|
|
363
|
+
// window onto a thread another process owns, and an imposter that started its
|
|
364
|
+
// own session here would put a second, unobserved authored flow on the screen
|
|
365
|
+
// while the adapter watched the first — the screen contradicting the wire,
|
|
366
|
+
// which is the single thing §2 exists to prevent.
|
|
367
|
+
//
|
|
368
|
+
// The flag is the ASM's, not ours: `launchFlags.remote` is captured vendor
|
|
369
|
+
// truth, so this cannot drift from what the adapter actually spawns.
|
|
370
|
+
const attachAddress = flagValue(rest, persona.flagsFor('remote', '--remote'));
|
|
371
|
+
if (attachAddress !== undefined)
|
|
372
|
+
return runAttached(persona, rest, attachAddress, log);
|
|
373
|
+
// `control` and `screen` are assigned below, after the session exists; the
|
|
374
|
+
// callbacks close over them and stay inert until then. Nothing is emitted
|
|
375
|
+
// before boot, which is after both.
|
|
376
|
+
let control;
|
|
377
|
+
let screen;
|
|
378
|
+
let closing = false;
|
|
379
|
+
/** Torn down on the way out, after the session has said its last word. */
|
|
380
|
+
const closers = [];
|
|
381
|
+
// The trigger fork (§9.3). For claude the trigger is stdin bytes; for codex
|
|
382
|
+
// it is inbound RPC. Everything downstream — the op timeline and its sinks —
|
|
383
|
+
// is genuinely shared, which is the whole claim the two families test.
|
|
384
|
+
//
|
|
385
|
+
// Which fork is taken comes from ARGV, not from whether the persona owns a
|
|
386
|
+
// serve table: `codex` opens a screen and `codex app-server` speaks the
|
|
387
|
+
// protocol, so an imposter that always served would be unfaithful in the
|
|
388
|
+
// most visible way there is — you could not run it by hand.
|
|
389
|
+
const serverSpec = persona.serve?.$server;
|
|
390
|
+
const serveCommand = serverSpec?.command;
|
|
391
|
+
const viewing = serverSpec?.viewer ? matchesInvocation(rest, serverSpec.viewer) : false;
|
|
392
|
+
const serving = persona.serve !== undefined &&
|
|
393
|
+
(serverSpec?.match
|
|
394
|
+
? matchesInvocation(rest, serverSpec.match)
|
|
395
|
+
: serveCommand === undefined || rest[0] === serveCommand);
|
|
396
|
+
if (viewing && leader && serverSpec?.viewer) {
|
|
397
|
+
const socketPath = flagValue(rest, [leader.socketFlag]);
|
|
398
|
+
if (!socketPath) {
|
|
399
|
+
process.stderr.write(`${leader.socketFlag} requires a socket path\n`);
|
|
400
|
+
return 2;
|
|
401
|
+
}
|
|
402
|
+
const sessionId = flagValue(rest, [serverSpec.viewer.sessionFlag]);
|
|
403
|
+
if (!sessionId) {
|
|
404
|
+
process.stderr.write(`${serverSpec.viewer.sessionFlag} requires a session id\n`);
|
|
405
|
+
return 2;
|
|
406
|
+
}
|
|
407
|
+
return runLeaderViewer(persona, socketPath, sessionId, log);
|
|
408
|
+
}
|
|
409
|
+
// A socket server has MANY clients where stdio has exactly one: the adapter
|
|
410
|
+
// brings up a controller connection, and the native TUI joins the same server
|
|
411
|
+
// beside it. Notifications fan out to all of them.
|
|
412
|
+
//
|
|
413
|
+
// Server-initiated requests do NOT fan out — an approval answered twice is
|
|
414
|
+
// not an approval. They go to the first client to speak, which is always the
|
|
415
|
+
// controller: the adapter owns the thread and connects before the TUI it then
|
|
416
|
+
// launches, and it is the side with an approval policy at all. A viewer that
|
|
417
|
+
// later starts a turn still does not inherit the decision, which is the point
|
|
418
|
+
// (over stdio there is one client and it is trivially first).
|
|
419
|
+
const clients = new Set();
|
|
420
|
+
let driver;
|
|
421
|
+
const session = createImposterSession({
|
|
422
|
+
persona,
|
|
423
|
+
argv: rest,
|
|
424
|
+
env: process.env,
|
|
425
|
+
cwd: process.cwd(),
|
|
426
|
+
behavior: loadBehavior(persona, behaviorName),
|
|
427
|
+
present: (frame) => screen?.frame(frame),
|
|
428
|
+
...(serving
|
|
429
|
+
? {
|
|
430
|
+
jsonrpc: {
|
|
431
|
+
notify: (method, params) => {
|
|
432
|
+
for (const client of clients)
|
|
433
|
+
client.notify(method, params);
|
|
434
|
+
},
|
|
435
|
+
request: (method, params) => {
|
|
436
|
+
const target = driver ?? [...clients][0];
|
|
437
|
+
return target
|
|
438
|
+
? target.request(method, params)
|
|
439
|
+
: Promise.reject(new Error('app-server channel is not open'));
|
|
440
|
+
},
|
|
441
|
+
},
|
|
442
|
+
}
|
|
443
|
+
: {}),
|
|
444
|
+
onEmitted: (entry) => control?.pushEmitted(entry),
|
|
445
|
+
onChannels: (channels) => {
|
|
446
|
+
control?.pushChannels(channels);
|
|
447
|
+
screen?.channels(channels);
|
|
448
|
+
},
|
|
449
|
+
// Scenario intent has two debug projections (console + TUI), while native
|
|
450
|
+
// truth is independently projected from the versioned Surface model.
|
|
451
|
+
onScenarioDriver: (snapshot) => {
|
|
452
|
+
control?.pushScenarioDriver(snapshot);
|
|
453
|
+
screen?.scenario(snapshot.state);
|
|
454
|
+
},
|
|
455
|
+
onScenarioRun: (progress) => control?.pushScenarioRun(progress),
|
|
456
|
+
halt: (kind, exitCode) => {
|
|
457
|
+
if (kind === 'hang') {
|
|
458
|
+
process.stdin.pause();
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
// setImmediate so the control reply flushes first. A crash sends no
|
|
462
|
+
// goodbye on purpose: a vendor that dies does not say goodbye, and the
|
|
463
|
+
// plane is meant to learn it from the socket closing (§5).
|
|
464
|
+
setImmediate(() => {
|
|
465
|
+
if (kind === 'crash')
|
|
466
|
+
process.exit(exitCode);
|
|
467
|
+
else
|
|
468
|
+
void shutdown(exitCode);
|
|
469
|
+
});
|
|
470
|
+
},
|
|
471
|
+
log,
|
|
472
|
+
});
|
|
473
|
+
const shutdown = async (exitCode = 0) => {
|
|
474
|
+
if (closing)
|
|
475
|
+
await new Promise(() => { });
|
|
476
|
+
closing = true;
|
|
477
|
+
// Leave the terminal as it was found; a shell inheriting bracketed-paste
|
|
478
|
+
// mode from a dead child is a real and confusing mess.
|
|
479
|
+
if (screen?.interactive && process.stdin.isTTY)
|
|
480
|
+
process.stdout.write('\x1b[?2004l');
|
|
481
|
+
await session.end();
|
|
482
|
+
// After session.end, so a listening server is still up to carry the last
|
|
483
|
+
// ops to whoever is connected.
|
|
484
|
+
for (const close of closers)
|
|
485
|
+
await close().catch(() => undefined);
|
|
486
|
+
await control?.close('other');
|
|
487
|
+
await screen?.stop();
|
|
488
|
+
process.exit(exitCode);
|
|
489
|
+
};
|
|
490
|
+
// The TUI is chrome and nothing more (§4): it renders the same lines the
|
|
491
|
+
// headless sink writes, and never reads input.
|
|
492
|
+
//
|
|
493
|
+
// When the persona SERVES, stdout is the protocol — a banner written there
|
|
494
|
+
// would sit in the middle of the adapter's NDJSON stream. So presentation
|
|
495
|
+
// goes to stderr and the TUI never mounts, whatever the terminal looks like.
|
|
496
|
+
// A serve persona run WITHOUT its server subcommand has no client on the
|
|
497
|
+
// other end of that channel, so it is reported detached rather than live. The
|
|
498
|
+
// screen still runs the ops; they simply reach no wire, which is the truth of
|
|
499
|
+
// the mode and visible as such (`ai --codex` is a preview, not a session).
|
|
500
|
+
const detached = !serving
|
|
501
|
+
? persona.serve !== undefined
|
|
502
|
+
? persona.channelFor('jsonrpc')
|
|
503
|
+
: persona.httpServe !== undefined
|
|
504
|
+
? persona.channelFor('sse')
|
|
505
|
+
: undefined
|
|
506
|
+
: undefined;
|
|
507
|
+
if (detached)
|
|
508
|
+
session.dropChannel(detached);
|
|
509
|
+
screen = await createPresentation({
|
|
510
|
+
vendor: persona.vendor,
|
|
511
|
+
version: persona.version,
|
|
512
|
+
sessionId: session.sessionId,
|
|
513
|
+
channels: session.liveChannels,
|
|
514
|
+
...(serving ? { interactive: false, write: (text) => void process.stderr.write(text) } : {}),
|
|
515
|
+
});
|
|
516
|
+
// Joining the control plane MUST complete before the stdin listeners attach:
|
|
517
|
+
// under ELECTRON_RUN_AS_NODE (how apps spawn script recipes) a flowing stdin
|
|
518
|
+
// wedges later async I/O initiation, and the connect never resolves — probed
|
|
519
|
+
// 2026-08-07 against the PoC's register fetch (§7.3 item 1).
|
|
520
|
+
control = await connectControl({
|
|
521
|
+
vendor: persona.vendor,
|
|
522
|
+
version: persona.version,
|
|
523
|
+
sessionId: session.sessionId,
|
|
524
|
+
cwd: process.cwd(),
|
|
525
|
+
nativeBehavior: persona.model.behavior,
|
|
526
|
+
nativeEvents: nativeEventsFromModel(persona.model),
|
|
527
|
+
ops: opsFromPersona(persona),
|
|
528
|
+
runflows: persona.runflows,
|
|
529
|
+
channels: () => session.liveChannels,
|
|
530
|
+
scenarioDriver: () => session.scenarioDriver,
|
|
531
|
+
emitted: () => session.emitted,
|
|
532
|
+
trigger: (event, payload, channel) => session.emit(event, payload, channel),
|
|
533
|
+
runOp: (op, argument) => session.runOp(op, argument),
|
|
534
|
+
runScenario: (request) => session.runScenario(request.script ?? loadScenario(persona, request.name), {
|
|
535
|
+
...(request.stimulus === undefined ? {} : { stimulus: request.stimulus }),
|
|
536
|
+
...(request.name === undefined ? {} : { scenario: request.name }),
|
|
537
|
+
...(request.runflowId === undefined ? {} : { runflowId: request.runflowId }),
|
|
538
|
+
speed: request.speed,
|
|
539
|
+
mode: request.mode,
|
|
540
|
+
}),
|
|
541
|
+
scenarioControl: (action) => session.scenarioControl(action),
|
|
542
|
+
fault: (request) => session.applyFault(request),
|
|
543
|
+
log,
|
|
544
|
+
});
|
|
545
|
+
// Boot is what the vendor does when a PERSON launches it, so it belongs to
|
|
546
|
+
// the interactive fork alone. A server has no session until a client asks for
|
|
547
|
+
// one — codex's own lifecycle starts at `thread/start`, which is why the serve
|
|
548
|
+
// table runs `session.start` from there (§9.3). Booting a server would push
|
|
549
|
+
// `thread/started` at a client that never asked, and the adapter would be
|
|
550
|
+
// learning a lie about when threads come into existence.
|
|
551
|
+
if (!serving)
|
|
552
|
+
await session.boot();
|
|
553
|
+
process.once('SIGTERM', () => void shutdown());
|
|
554
|
+
process.once('SIGINT', () => void shutdown());
|
|
555
|
+
if (serving) {
|
|
556
|
+
// The JSON-RPC family's trigger: inbound RPC, answered synchronously, with
|
|
557
|
+
// any resulting ops scheduled onto the SAME timeline the paste path uses.
|
|
558
|
+
const dispatcher = createServeDispatcher({
|
|
559
|
+
persona,
|
|
560
|
+
document: persona.serve,
|
|
561
|
+
bindings: session.bindings,
|
|
562
|
+
runOps: (invocations) => session.timeline.runAll(invocations),
|
|
563
|
+
runBehavior: (stimulus) => session.turn(typeof stimulus.text === 'string' ? stimulus.text : ''),
|
|
564
|
+
// Inbound params are held to the ASM exactly like outbound payloads, so
|
|
565
|
+
// the imposter is a conformance test of the adapter's client (§9.3).
|
|
566
|
+
validateParams: (method, params) => persona.validate(method, params),
|
|
567
|
+
validateResult: (method, result) => persona.validateResult(method, result),
|
|
568
|
+
log,
|
|
569
|
+
});
|
|
570
|
+
let leaderController;
|
|
571
|
+
let leaderChannel;
|
|
572
|
+
const ensureLeaderController = async () => {
|
|
573
|
+
if (!leader || leaderController)
|
|
574
|
+
return;
|
|
575
|
+
const socketPath = flagValue(rest, [leader.socketFlag]);
|
|
576
|
+
if (!socketPath)
|
|
577
|
+
throw new Error(`${leader.socketFlag} requires a socket path`);
|
|
578
|
+
const sessionId = session.bindings.$sessionId;
|
|
579
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) {
|
|
580
|
+
throw new Error('leader controller cannot register before the session id is bound');
|
|
581
|
+
}
|
|
582
|
+
leaderController = await connectLeaderAcp(socketPath, 'controller', sessionId, persona.version, log);
|
|
583
|
+
leaderChannel = attach({ input: leaderController.input, output: leaderController.output }, () => {
|
|
584
|
+
if (leaderChannel)
|
|
585
|
+
clients.delete(leaderChannel);
|
|
586
|
+
leaderChannel = undefined;
|
|
587
|
+
leaderController = undefined;
|
|
588
|
+
}, false);
|
|
589
|
+
closers.push(async () => leaderController?.close());
|
|
590
|
+
};
|
|
591
|
+
// One channel per client, whatever carried it here. The transport decides
|
|
592
|
+
// where the bytes come from and nothing else: same dispatcher, same serve
|
|
593
|
+
// table, same op timeline behind every connection.
|
|
594
|
+
function attach(streams, onClose, direct = true) {
|
|
595
|
+
let channel;
|
|
596
|
+
channel = createAppServerChannel({
|
|
597
|
+
input: streams.input,
|
|
598
|
+
output: streams.output,
|
|
599
|
+
serve: async (method, params) => {
|
|
600
|
+
if (direct)
|
|
601
|
+
driver ??= channel;
|
|
602
|
+
const result = await dispatcher.serve(method, params, {
|
|
603
|
+
restoreSession: () => session.restore((event, payload) => channel.notify(event, payload)),
|
|
604
|
+
});
|
|
605
|
+
if (method === 'session/new' || method === 'session/load')
|
|
606
|
+
await ensureLeaderController();
|
|
607
|
+
return result;
|
|
608
|
+
},
|
|
609
|
+
notified: dispatcher.notified,
|
|
610
|
+
jsonrpc: persona.serve?.$server?.jsonrpc,
|
|
611
|
+
notificationFields: () => substitute(persona.serve?.$server?.notification ?? {}, { bindings: session.bindings }),
|
|
612
|
+
validateOutbound: (method, record) => persona.validateRecord(method, record, persona.channelFor('jsonrpc')),
|
|
613
|
+
validateResult: (method, result) => persona.validateResult(method, result),
|
|
614
|
+
onClose: () => {
|
|
615
|
+
clients.delete(channel);
|
|
616
|
+
if (driver === channel)
|
|
617
|
+
driver = undefined;
|
|
618
|
+
onClose();
|
|
619
|
+
},
|
|
620
|
+
log,
|
|
621
|
+
});
|
|
622
|
+
clients.add(channel);
|
|
623
|
+
return channel;
|
|
624
|
+
}
|
|
625
|
+
const listener = listenTarget(persona, rest);
|
|
626
|
+
if ('error' in listener) {
|
|
627
|
+
process.stderr.write(`${listener.error}\n`);
|
|
628
|
+
return 2;
|
|
629
|
+
}
|
|
630
|
+
if (listener.socketPath === undefined) {
|
|
631
|
+
// stdio: the client IS the parent process, so its EOF ends the session.
|
|
632
|
+
attach({ input: process.stdin, output: process.stdout }, () => void shutdown());
|
|
633
|
+
await new Promise(() => { });
|
|
634
|
+
return 0;
|
|
635
|
+
}
|
|
636
|
+
// A listening server outlives any one client — the adapter's controller and
|
|
637
|
+
// the native TUI connect and disconnect independently, and a real
|
|
638
|
+
// app-server does not exit when one of them leaves. It ends on the signal
|
|
639
|
+
// its owner sends, which `dispose()` already does.
|
|
640
|
+
const server = await listenUnixWebSocket({
|
|
641
|
+
socketPath: listener.socketPath,
|
|
642
|
+
onConnection: (connection) => attach(connection, () => connection.close()),
|
|
643
|
+
log,
|
|
644
|
+
});
|
|
645
|
+
log(`app-server listening on ${server.socketPath}`);
|
|
646
|
+
screen.notice(`serving ${server.socketPath}`);
|
|
647
|
+
closers.push(() => server.close());
|
|
648
|
+
await new Promise(() => { });
|
|
649
|
+
return 0;
|
|
650
|
+
}
|
|
651
|
+
installPromptLine({
|
|
652
|
+
interactive: screen.interactive,
|
|
653
|
+
staged: (text) => screen?.staged(text),
|
|
654
|
+
submit: (text) => void session.turn(text).catch((error) => {
|
|
655
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
656
|
+
// Both, not either: the notice is for whoever is looking at the pane,
|
|
657
|
+
// and the log is for whoever is debugging one they cannot see.
|
|
658
|
+
screen?.notice(`turn failed: ${message}`);
|
|
659
|
+
log(`turn failed: ${message}`);
|
|
660
|
+
}),
|
|
661
|
+
interrupt: () => void shutdown(),
|
|
662
|
+
end: () => void shutdown(),
|
|
663
|
+
log,
|
|
664
|
+
});
|
|
665
|
+
// Hold the process open; the session ends on signal or stdin EOF.
|
|
666
|
+
await new Promise(() => { });
|
|
667
|
+
return 0;
|
|
668
|
+
}
|
|
669
|
+
// No auto-run on import: `bin/ai.mjs` owns invocation, so tests can import
|
|
670
|
+
// `main` without a module-load side effect spawning a session.
|
|
671
|
+
//# sourceMappingURL=main.js.map
|