quick-acp 0.0.0-stage → 0.1.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/README.md +405 -2
- package/dist/acp/agent.js +371 -0
- package/dist/acp-smoke.js +163 -0
- package/dist/concurrent-test.js +101 -0
- package/dist/doctor.js +86 -0
- package/dist/e2e.js +206 -0
- package/dist/fresh-machine-e2e.js +151 -0
- package/dist/inject-turn-test.js +119 -0
- package/dist/login-cli.js +86 -0
- package/dist/main.js +77 -0
- package/dist/no-outpost-e2e.js +86 -0
- package/dist/probe.js +308 -0
- package/dist/quick/auth.js +371 -0
- package/dist/quick/codec.js +499 -0
- package/dist/quick/credstore.js +439 -0
- package/dist/quick/gateway-contract.js +104 -0
- package/dist/quick/login.js +522 -0
- package/dist/quick/oidc.js +152 -0
- package/dist/quick/session-direct.js +200 -0
- package/dist/quick/session.js +385 -0
- package/dist/quick/transport.js +343 -0
- package/dist/tools/registry.js +411 -0
- package/dist/tools/strategies.js +188 -0
- package/dist/wss-smoke.js +230 -0
- package/package.json +53 -4
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session resolution that does NOT use the outpost.
|
|
3
|
+
*
|
|
4
|
+
* WHY
|
|
5
|
+
* ---
|
|
6
|
+
* The outpost was originally the only way to get a session, and it needs the
|
|
7
|
+
* Electron main process (or a binary started with the right env). That means a
|
|
8
|
+
* machine with no Quick install cannot use this bridge at all — which defeats
|
|
9
|
+
* the point.
|
|
10
|
+
*
|
|
11
|
+
* Probing the stored login showed everything the gateway handshake needs is
|
|
12
|
+
* already in the credential blob:
|
|
13
|
+
*
|
|
14
|
+
* tenant_url https://qbs-xxxx.dp.appintegrations.us-east-1.prod.plato.ai...
|
|
15
|
+
* issuer_url https://identitycenter.amazonaws.com/ssoins-xxxx
|
|
16
|
+
* external_id / role / aws_account_id (actor identity)
|
|
17
|
+
*
|
|
18
|
+
* and `ws_host` reported by the outpost is exactly `tenant_url` minus its
|
|
19
|
+
* scheme. So: refresh the token ourselves (oidc.ts), strip the scheme off
|
|
20
|
+
* tenant_url, and dial. No outpost, no instance token, no Electron.
|
|
21
|
+
*
|
|
22
|
+
* WHAT IS STILL UNKNOWN WITHOUT THE OUTPOST
|
|
23
|
+
* -----------------------------------------
|
|
24
|
+
* `actor_arn` comes back EMPTY from the outpost too on this deployment
|
|
25
|
+
* (`"actor_arn": ""`), so it is not something we can lose. `outpost_device_id`
|
|
26
|
+
* is replaced by the local device id from ~/.quickwork/device_id when present,
|
|
27
|
+
* otherwise a stable random one.
|
|
28
|
+
*/
|
|
29
|
+
import { randomUUID } from 'node:crypto';
|
|
30
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
31
|
+
import { homedir } from 'node:os';
|
|
32
|
+
import { join } from 'node:path';
|
|
33
|
+
import { readStoredLogin } from './credstore.js';
|
|
34
|
+
import { refreshIdToken } from './oidc.js';
|
|
35
|
+
import { DEFAULT_WS_PATH, surfaceForPlatform } from './auth.js';
|
|
36
|
+
function quickworkHome() {
|
|
37
|
+
return process.env.QUICK_ACP_QUICKWORK_HOME ?? join(homedir(), '.quickwork');
|
|
38
|
+
}
|
|
39
|
+
/** The device id the app generates once and reuses. */
|
|
40
|
+
function readDeviceId() {
|
|
41
|
+
const p = join(quickworkHome(), 'device_id');
|
|
42
|
+
if (!existsSync(p))
|
|
43
|
+
return '';
|
|
44
|
+
try {
|
|
45
|
+
return readFileSync(p, 'utf8').trim();
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return '';
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* `ws_host` is the tenant URL without its scheme. Verified: the outpost reports
|
|
53
|
+
* exactly this transformation for the same account.
|
|
54
|
+
*/
|
|
55
|
+
export function wsHostFromTenant(tenantUrl) {
|
|
56
|
+
return tenantUrl.replace(/^https?:\/\//i, '').replace(/\/+$/, '');
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Build a session from the stored login alone.
|
|
60
|
+
*
|
|
61
|
+
* Returns a failure rather than throwing so the caller can fall back to the
|
|
62
|
+
* outpost and report both reasons.
|
|
63
|
+
*
|
|
64
|
+
* SOURCE ORDER: our own `login.json` first, then the desktop app's keychain
|
|
65
|
+
* entry. That order matters — a sign-in done through `login-cli.js` is by
|
|
66
|
+
* definition the newest credential on the machine, while the app's entry can be
|
|
67
|
+
* stale (and a stale-but-unexpired access token is the one thing the gateway
|
|
68
|
+
* rejects with 401 while everything looks healthy).
|
|
69
|
+
*/
|
|
70
|
+
export async function sessionDirect(opts = {}) {
|
|
71
|
+
const bridge = await readBridgeLogin();
|
|
72
|
+
if (bridge) {
|
|
73
|
+
const r = await sessionFromLogin(bridge, opts);
|
|
74
|
+
if (r.ok)
|
|
75
|
+
return r;
|
|
76
|
+
if (process.env.QUICK_ACP_DEBUG === '1') {
|
|
77
|
+
console.error(`[session] bridge login failed (${r.step}): ${r.reason}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const read = await readStoredLogin();
|
|
81
|
+
if (!read.ok) {
|
|
82
|
+
if (bridge) {
|
|
83
|
+
return {
|
|
84
|
+
ok: false,
|
|
85
|
+
step: 'credential',
|
|
86
|
+
reason: 'the quick-acp login file did not yield a session and there is no app login either',
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
return { ok: false, step: 'credential', reason: read.reason };
|
|
90
|
+
}
|
|
91
|
+
return sessionFromLogin(read.login, opts);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Login written by `login-cli.js` (`~/.quick-acp/login.json`).
|
|
95
|
+
*
|
|
96
|
+
* That file holds everything the OAuth flow produced EXCEPT the gateway host,
|
|
97
|
+
* which the token response does not include. We therefore merge in `tenant_url`
|
|
98
|
+
* from the app's profile when one exists, and otherwise expect the user to have
|
|
99
|
+
* supplied it — a session cannot be dialled without it.
|
|
100
|
+
*/
|
|
101
|
+
async function readBridgeLogin() {
|
|
102
|
+
const p = join(homedir(), '.quick-acp', 'login.json');
|
|
103
|
+
if (!existsSync(p))
|
|
104
|
+
return null;
|
|
105
|
+
try {
|
|
106
|
+
const j = JSON.parse(readFileSync(p, 'utf8'));
|
|
107
|
+
const tenantUrl = typeof j['tenant_url'] === 'string' ? j['tenant_url'] : '';
|
|
108
|
+
if (!tenantUrl)
|
|
109
|
+
return null;
|
|
110
|
+
return {
|
|
111
|
+
issuer_url: j['issuer_url'],
|
|
112
|
+
tenant_url: tenantUrl,
|
|
113
|
+
client_id: j['client_id'],
|
|
114
|
+
client_secret: j['client_secret'],
|
|
115
|
+
access_token: j['access_token'],
|
|
116
|
+
access_token_expiry: j['expires_at'],
|
|
117
|
+
refresh_token: j['refresh_token'],
|
|
118
|
+
role: j['role'],
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Exposed so the outpost path can reuse it once it has a login in hand.
|
|
127
|
+
*
|
|
128
|
+
* TOKEN SELECTION — the non-obvious part
|
|
129
|
+
* --------------------------------------
|
|
130
|
+
* The default is to REFRESH, even when the stored access token has not expired
|
|
131
|
+
* yet. Reason: a locally-unexpired token is not proof of anything. During
|
|
132
|
+
* development the keychain held an access token with 18 minutes left that the
|
|
133
|
+
* gateway rejected with 401 on every attempt — the clock said fine, the server
|
|
134
|
+
* said no. Refreshing costs one HTTP round trip and removes that whole class of
|
|
135
|
+
* "everything looks healthy but nothing works".
|
|
136
|
+
*
|
|
137
|
+
* `preferAccessToken: true` exists for callers that must avoid the extra call
|
|
138
|
+
* (offline diagnostics). It falls back to the cached token only if the refresh
|
|
139
|
+
* itself fails.
|
|
140
|
+
*/
|
|
141
|
+
export async function sessionFromLogin(login, opts = {}) {
|
|
142
|
+
const tenantUrl = typeof login.tenant_url === 'string' && login.tenant_url ? login.tenant_url : '';
|
|
143
|
+
if (!tenantUrl) {
|
|
144
|
+
return {
|
|
145
|
+
ok: false,
|
|
146
|
+
step: 'tenant',
|
|
147
|
+
reason: 'the stored login has no tenant_url, which is the gateway host. ' +
|
|
148
|
+
'This deployment records it in profiles.json — check that file.',
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
const accessToken = typeof login.access_token === 'string' ? login.access_token : '';
|
|
152
|
+
const accessExpiry = typeof login.access_token_expiry === 'number' ? login.access_token_expiry : 0;
|
|
153
|
+
const stillValid = Boolean(accessToken) && accessExpiry > Date.now() / 1000 + 60;
|
|
154
|
+
let jwt = '';
|
|
155
|
+
let expiresAt = accessExpiry;
|
|
156
|
+
let source = 'credential';
|
|
157
|
+
if (opts.preferAccessToken === true && stillValid) {
|
|
158
|
+
// Explicitly asked to skip the refresh.
|
|
159
|
+
jwt = accessToken;
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
const refreshed = await refreshIdToken(login);
|
|
163
|
+
if (refreshed) {
|
|
164
|
+
jwt = refreshed.accessToken;
|
|
165
|
+
expiresAt = refreshed.expiresAt;
|
|
166
|
+
}
|
|
167
|
+
else if (stillValid) {
|
|
168
|
+
// Refresh refused; the cached token may still be accepted.
|
|
169
|
+
jwt = accessToken;
|
|
170
|
+
source = 'cached';
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
return {
|
|
174
|
+
ok: false,
|
|
175
|
+
step: 'refresh',
|
|
176
|
+
reason: 'the stored refresh token was rejected by AWS and the cached access token has ' +
|
|
177
|
+
'expired. Sign in again — either through the desktop app, or with ' +
|
|
178
|
+
'`node dist/login-cli.js --start-url <portal URL>`.',
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
const deviceId = readDeviceId();
|
|
183
|
+
return {
|
|
184
|
+
ok: true,
|
|
185
|
+
session: {
|
|
186
|
+
jwt,
|
|
187
|
+
wsHost: wsHostFromTenant(tenantUrl),
|
|
188
|
+
wsPath: DEFAULT_WS_PATH,
|
|
189
|
+
tenantUrl,
|
|
190
|
+
surface: surfaceForPlatform(),
|
|
191
|
+
outpostId: deviceId || randomUUID(),
|
|
192
|
+
workingSessionId: randomUUID(),
|
|
193
|
+
actorArn: '',
|
|
194
|
+
provider: typeof login.role === 'string' ? login.role : '',
|
|
195
|
+
source,
|
|
196
|
+
expiresAt: expiresAt || Math.floor(Date.now() / 1000) + 3600,
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
//# sourceMappingURL=session-direct.js.map
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quick conversation session.
|
|
3
|
+
*
|
|
4
|
+
* Verified against the live gateway. The inbound frame shapes handled here are
|
|
5
|
+
* the ones actually observed, not the ones guessed from the renderer:
|
|
6
|
+
*
|
|
7
|
+
* message_start {payload:{role}, message_id, thread_id}
|
|
8
|
+
* title_generated {payload:{conversation_id,title}}
|
|
9
|
+
* thinking_start {payload:{type, kernel_thread_id}}
|
|
10
|
+
* thinking_delta {payload:{type, delta, kernel_thread_id}}
|
|
11
|
+
* thinking_complete {payload:{...}}
|
|
12
|
+
* text_delta {payload:{delta, kernel_thread_id}, message_id, thread_id}
|
|
13
|
+
* turn_usage {payload:{input_tokens,output_tokens,cache_read_tokens,
|
|
14
|
+
* cache_write_tokens,resolved_model_id}}
|
|
15
|
+
* text_complete {payload:{text}, message_id, thread_id}
|
|
16
|
+
* message_complete {payload:{text, tool_calls, initiator}}
|
|
17
|
+
* tool_start / tool_arguments / tool_progress / tool_result (server-side tools)
|
|
18
|
+
*
|
|
19
|
+
* CORRECTION: an earlier version of this header asserted "There is NO
|
|
20
|
+
* `thinking_delta` in the observed chat flow". That was wrong, and the way it
|
|
21
|
+
* was wrong is instructive: the tests behind it asked for single-word answers,
|
|
22
|
+
* which never engage reasoning, so the frames never appeared. With a prompt that
|
|
23
|
+
* invites thinking, the gateway streams `thinking_start` + many `thinking_delta`
|
|
24
|
+
* frames. Treating their absence as a protocol fact silently discarded every
|
|
25
|
+
* reasoning token.
|
|
26
|
+
*
|
|
27
|
+
* The usage frame really is called `turn_usage` (not `token_usage`), and the
|
|
28
|
+
* server-side tool frame really is `tool_result` (not `tool_end`) — both names
|
|
29
|
+
* matter.
|
|
30
|
+
*
|
|
31
|
+
* STRUCTURAL CONSTRAINT (unchanged): the wire protocol sends an incremental
|
|
32
|
+
* turn against a server-held `thread_id`. It does not accept a message history.
|
|
33
|
+
* A fresh UUID thread is accepted and creates a new conversation, which is what
|
|
34
|
+
* makes one-turn-at-a-time operation possible without a prior session_list.
|
|
35
|
+
*/
|
|
36
|
+
import { randomUUID } from 'node:crypto';
|
|
37
|
+
import { HOUSEKEEPING_FRAME_TYPES, TURN_END_FRAME_TYPES, } from './gateway-contract.js';
|
|
38
|
+
export class QuickChatSession {
|
|
39
|
+
opts;
|
|
40
|
+
state = null;
|
|
41
|
+
connected = false;
|
|
42
|
+
activeMessageId = null;
|
|
43
|
+
activeHandler = null;
|
|
44
|
+
debug;
|
|
45
|
+
constructor(opts) {
|
|
46
|
+
this.opts = opts;
|
|
47
|
+
this.debug = opts.debug ?? process.env.QUICK_ACP_DEBUG === '1';
|
|
48
|
+
}
|
|
49
|
+
log(...args) {
|
|
50
|
+
if (this.debug)
|
|
51
|
+
console.error('[quick-acp:session]', ...args);
|
|
52
|
+
}
|
|
53
|
+
/** Open the gateway and perform session_connect. */
|
|
54
|
+
async open() {
|
|
55
|
+
if (this.connected)
|
|
56
|
+
return;
|
|
57
|
+
this.opts.transport.on((ev) => {
|
|
58
|
+
if (ev.type === 'message')
|
|
59
|
+
this.handleBody(ev.body);
|
|
60
|
+
else if (ev.type === 'error')
|
|
61
|
+
this.failActive('transport_error', ev.body);
|
|
62
|
+
else if (ev.type === 'close') {
|
|
63
|
+
this.failActive('transport_closed', `closed ${ev.code} ${ev.reason}`);
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
await this.opts.transport.connect();
|
|
67
|
+
// surfaceType and outpostId are what the app's tf() puts here. The server
|
|
68
|
+
// acknowledges with session_established.
|
|
69
|
+
this.opts.transport.send({
|
|
70
|
+
type: 'session_connect',
|
|
71
|
+
payload: {
|
|
72
|
+
actor_id: this.opts.actorArn ?? '',
|
|
73
|
+
surfaceType: this.opts.transport.surface,
|
|
74
|
+
outpostId: this.opts.transport.outpostId,
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
this.opts.transport.startAppHeartbeat();
|
|
78
|
+
this.connected = true;
|
|
79
|
+
}
|
|
80
|
+
get threadId() {
|
|
81
|
+
return this.state?.threadId ?? null;
|
|
82
|
+
}
|
|
83
|
+
/** Forget the thread, so the next turn starts a fresh conversation. */
|
|
84
|
+
resetThread() {
|
|
85
|
+
this.state = null;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Send one user turn and stream the assistant reply.
|
|
89
|
+
*
|
|
90
|
+
* No `session_list` or explicit conversation creation is needed: a fresh
|
|
91
|
+
* UUID thread_id is accepted and the server creates the conversation (it
|
|
92
|
+
* even emits `title_generated` with the new id). That was verified end to end
|
|
93
|
+
* — the model replied.
|
|
94
|
+
*/
|
|
95
|
+
async *sendTurn(history, opts = {}) {
|
|
96
|
+
if (!this.connected)
|
|
97
|
+
throw new Error('session not open');
|
|
98
|
+
const safeHistory = normalizeHistory(history);
|
|
99
|
+
const lastUser = [...safeHistory].reverse().find((t) => t.role === 'user');
|
|
100
|
+
if (!lastUser)
|
|
101
|
+
throw new Error('no user turn to send');
|
|
102
|
+
if (!this.state || opts.threadId) {
|
|
103
|
+
this.state = { threadId: opts.threadId ?? randomUUID(), sentTurns: [] };
|
|
104
|
+
}
|
|
105
|
+
this.state.sentTurns.push(lastUser);
|
|
106
|
+
const messageId = `msg-${randomUUID().slice(0, 8)}`;
|
|
107
|
+
this.activeMessageId = messageId;
|
|
108
|
+
const queue = [];
|
|
109
|
+
let notify = null;
|
|
110
|
+
let finished = false;
|
|
111
|
+
this.activeHandler = (ev) => {
|
|
112
|
+
queue.push(ev);
|
|
113
|
+
if (ev.type === 'turn_end' || ev.type === 'error')
|
|
114
|
+
finished = true;
|
|
115
|
+
notify?.();
|
|
116
|
+
};
|
|
117
|
+
const mode = opts.agentMode ?? this.opts.agentMode ?? 'smart';
|
|
118
|
+
const effort = clampEffort(opts.thinkingEffort ?? this.opts.thinkingEffort ?? 'high');
|
|
119
|
+
this.opts.transport.send({
|
|
120
|
+
type: 'user_message',
|
|
121
|
+
payload: {
|
|
122
|
+
thread_id: this.state.threadId,
|
|
123
|
+
text: lastUser.text,
|
|
124
|
+
message_id: messageId,
|
|
125
|
+
// The server checks these; the app's tf() supplies them on every frame.
|
|
126
|
+
surfaceType: this.opts.transport.surface,
|
|
127
|
+
outpostId: this.opts.transport.outpostId,
|
|
128
|
+
agent_mode: mode === 'advanced' ? 'smart' : mode,
|
|
129
|
+
thinking_effort: effort,
|
|
130
|
+
send_origin: 'composer',
|
|
131
|
+
had_physical_input: true,
|
|
132
|
+
traceId: randomUUID(),
|
|
133
|
+
user_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC',
|
|
134
|
+
user_locale: 'en-US',
|
|
135
|
+
auto_routing: false,
|
|
136
|
+
web_search_enabled: false,
|
|
137
|
+
direct_chat: false,
|
|
138
|
+
...(opts.attachments && opts.attachments.length > 0
|
|
139
|
+
? { attachments: opts.attachments }
|
|
140
|
+
: {}),
|
|
141
|
+
},
|
|
142
|
+
});
|
|
143
|
+
try {
|
|
144
|
+
while (!finished) {
|
|
145
|
+
if (queue.length === 0) {
|
|
146
|
+
await new Promise((resolve) => {
|
|
147
|
+
notify = () => {
|
|
148
|
+
notify = null;
|
|
149
|
+
resolve();
|
|
150
|
+
};
|
|
151
|
+
});
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
yield queue.shift();
|
|
155
|
+
}
|
|
156
|
+
while (queue.length > 0)
|
|
157
|
+
yield queue.shift();
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
this.activeHandler = null;
|
|
161
|
+
this.activeMessageId = null;
|
|
162
|
+
const reply = this.lastText;
|
|
163
|
+
if (reply)
|
|
164
|
+
this.state.sentTurns.push({ role: 'assistant', text: reply });
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
lastText = '';
|
|
168
|
+
/** Reasoning accumulated for the turn in flight. */
|
|
169
|
+
lastThinking = '';
|
|
170
|
+
/** Usage seen for the turn in flight; attached when `message_complete` lands. */
|
|
171
|
+
pendingUsage = null;
|
|
172
|
+
/** Ask the server to stop the in-flight turn. */
|
|
173
|
+
cancel() {
|
|
174
|
+
if (!this.state)
|
|
175
|
+
return;
|
|
176
|
+
try {
|
|
177
|
+
this.opts.transport.send({
|
|
178
|
+
type: 'stop_generation',
|
|
179
|
+
payload: {
|
|
180
|
+
thread_id: this.state.threadId,
|
|
181
|
+
...(this.activeMessageId ? { message_id: this.activeMessageId } : {}),
|
|
182
|
+
explicit_pause: true,
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
catch (e) {
|
|
187
|
+
this.log('cancel failed', e);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
close() {
|
|
191
|
+
this.opts.transport.terminate();
|
|
192
|
+
this.connected = false;
|
|
193
|
+
}
|
|
194
|
+
// -------------------------------------------------------------------------
|
|
195
|
+
// inbound dispatch — shapes verified against the live gateway
|
|
196
|
+
// -------------------------------------------------------------------------
|
|
197
|
+
handleBody(body) {
|
|
198
|
+
let msg;
|
|
199
|
+
try {
|
|
200
|
+
msg = JSON.parse(body);
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const type = typeof msg['type'] === 'string' ? msg['type'] : '';
|
|
206
|
+
const payload = msg['payload'] && typeof msg['payload'] === 'object'
|
|
207
|
+
? msg['payload']
|
|
208
|
+
: {};
|
|
209
|
+
// Housekeeping frames: observed constantly, never part of a turn.
|
|
210
|
+
if (HOUSEKEEPING_FRAME_TYPES.has(type)) {
|
|
211
|
+
if (type === 'session_list') {
|
|
212
|
+
this.log('session_list ignored (chat works without it)');
|
|
213
|
+
}
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
// Server-side errors that end a turn.
|
|
217
|
+
if (type === 'error') {
|
|
218
|
+
const code = typeof msg['code'] === 'string' ? msg['code'] : 'error';
|
|
219
|
+
const message = typeof msg['message'] === 'string' ? msg['message'] : body;
|
|
220
|
+
this.deliver({ type: 'error', code, message });
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
switch (type) {
|
|
224
|
+
case 'message_start': {
|
|
225
|
+
const id = typeof msg['message_id'] === 'string' ? msg['message_id'] : this.activeMessageId ?? '';
|
|
226
|
+
this.lastText = '';
|
|
227
|
+
this.deliver({ type: 'message_start', messageId: id });
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
case 'text_delta': {
|
|
231
|
+
const delta = typeof payload['delta'] === 'string' ? payload['delta'] : '';
|
|
232
|
+
if (delta)
|
|
233
|
+
this.lastText += delta;
|
|
234
|
+
this.deliver({ type: 'text', delta });
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
// Reasoning stream. VERIFIED present on the live gateway: a prompt that
|
|
238
|
+
// invites extended thinking produces `thinking_start`, many
|
|
239
|
+
// `thinking_delta {delta}` frames, then the answer. An earlier version of
|
|
240
|
+
// this file claimed "there is NO thinking_delta in the observed chat flow"
|
|
241
|
+
// and had no case for it, so every reasoning token was silently dropped —
|
|
242
|
+
// the comment was a wrong inference from single-turn PONG tests, which
|
|
243
|
+
// never engage thinking at all.
|
|
244
|
+
case 'thinking_start': {
|
|
245
|
+
this.lastThinking = '';
|
|
246
|
+
this.deliver({ type: 'thinking', delta: '' });
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
case 'thinking_delta': {
|
|
250
|
+
const delta = typeof payload['delta'] === 'string' ? payload['delta'] : '';
|
|
251
|
+
if (!delta)
|
|
252
|
+
return;
|
|
253
|
+
this.lastThinking += delta;
|
|
254
|
+
this.deliver({ type: 'thinking', delta });
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
case 'thinking_complete': {
|
|
258
|
+
const text = typeof payload['text'] === 'string' ? payload['text'] : this.lastThinking;
|
|
259
|
+
if (text)
|
|
260
|
+
this.lastThinking = text;
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
case 'title_generated': {
|
|
264
|
+
const title = typeof payload['title'] === 'string' ? payload['title'] : '';
|
|
265
|
+
if (title)
|
|
266
|
+
this.deliver({ type: 'title', title });
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
case 'tool_start': {
|
|
270
|
+
const toolName = typeof payload['tool_name'] === 'string' ? payload['tool_name'] : 'unknown';
|
|
271
|
+
const toolId = typeof payload['tool_id'] === 'string' ? payload['tool_id'] : randomUUID();
|
|
272
|
+
this.deliver({ type: 'tool_start', toolName, toolId, args: payload['arguments'] ?? null });
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
// `tool_result` is the verified name — the renderer's task-stream handler
|
|
276
|
+
// (startup-*.js, `case 'tool_result'`) reads {tool_id, result, error,
|
|
277
|
+
// status, arguments}. `tool_end` does NOT exist in this protocol; it was a
|
|
278
|
+
// guess in the first version and silently matched nothing.
|
|
279
|
+
case 'tool_result': {
|
|
280
|
+
const toolId = typeof payload['tool_id'] === 'string' ? payload['tool_id'] : '';
|
|
281
|
+
const error = typeof payload['error'] === 'string' ? payload['error'] : undefined;
|
|
282
|
+
this.deliver({ type: 'tool_end', toolId, result: payload['result'] ?? null, error });
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
// `turn_usage` (verified name) -> our usage event. It arrives BEFORE the
|
|
286
|
+
// turn is actually closed, so it reports usage but does NOT end the stream
|
|
287
|
+
// — see the `message_complete` note below for why that distinction cost a
|
|
288
|
+
// real bug.
|
|
289
|
+
case 'turn_usage': {
|
|
290
|
+
this.pendingUsage = parseUsage(payload);
|
|
291
|
+
this.deliver({ type: 'usage', usage: this.pendingUsage });
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
// Authoritative end of a turn.
|
|
295
|
+
//
|
|
296
|
+
// WHY THIS ALONE CLOSES THE TURN
|
|
297
|
+
// ------------------------------
|
|
298
|
+
// The server sends `turn_usage` a few hundred ms before `message_complete`.
|
|
299
|
+
// Ending the stream on `turn_usage` let the caller fire the NEXT turn while
|
|
300
|
+
// the server was still finishing the previous one, and the server answered
|
|
301
|
+
// that next message with an empty `message_complete {text:"", initiator:
|
|
302
|
+
// "user"}` — an echo, not a reply. Measured on a live socket:
|
|
303
|
+
//
|
|
304
|
+
// two turns back-to-back -> 2nd reply empty
|
|
305
|
+
// three turns back-to-back -> 2nd empty, 3rd got the 2nd's answer
|
|
306
|
+
// with a 2.5 s gap -> both fine
|
|
307
|
+
//
|
|
308
|
+
// So the messages were queued, never lost, and the fix is to wait for the
|
|
309
|
+
// authoritative close instead of the usage frame.
|
|
310
|
+
case 'message_complete': {
|
|
311
|
+
const text = typeof payload['text'] === 'string' ? payload['text'] : this.lastText;
|
|
312
|
+
if (text)
|
|
313
|
+
this.lastText = text;
|
|
314
|
+
this.deliver({ type: 'turn_end', usage: this.pendingUsage });
|
|
315
|
+
this.pendingUsage = null;
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
case 'text_complete': {
|
|
319
|
+
const text = typeof payload['text'] === 'string' ? payload['text'] : '';
|
|
320
|
+
if (text)
|
|
321
|
+
this.lastText = text;
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
default:
|
|
325
|
+
if (!TURN_END_FRAME_TYPES.has(type)) {
|
|
326
|
+
this.log('unhandled frame type', type);
|
|
327
|
+
}
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
deliver(ev) {
|
|
332
|
+
const h = this.activeHandler;
|
|
333
|
+
if (!h) {
|
|
334
|
+
if (ev.type === 'error')
|
|
335
|
+
this.log('error with no active turn:', ev.code, ev.message);
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
h(ev);
|
|
339
|
+
}
|
|
340
|
+
failActive(code, message) {
|
|
341
|
+
const h = this.activeHandler;
|
|
342
|
+
if (h)
|
|
343
|
+
h({ type: 'error', code, message });
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
// ---------------------------------------------------------------------------
|
|
347
|
+
function clampEffort(e) {
|
|
348
|
+
// 'max' is capped at 'high' in the shipping build.
|
|
349
|
+
return e === 'off' || e === 'low' || e === 'medium' ? e : 'high';
|
|
350
|
+
}
|
|
351
|
+
function normalizeHistory(turns) {
|
|
352
|
+
const out = [];
|
|
353
|
+
for (const t of turns) {
|
|
354
|
+
const text = typeof t.text === 'string' ? t.text : '';
|
|
355
|
+
if (!text)
|
|
356
|
+
continue;
|
|
357
|
+
out.push({ role: t.role === 'assistant' ? 'assistant' : 'user', text });
|
|
358
|
+
}
|
|
359
|
+
// Merge consecutive same-role turns: the protocol has one user turn per frame.
|
|
360
|
+
const merged = [];
|
|
361
|
+
for (const t of out) {
|
|
362
|
+
const prev = merged[merged.length - 1];
|
|
363
|
+
if (prev && prev.role === t.role)
|
|
364
|
+
prev.text += `\n\n${t.text}`;
|
|
365
|
+
else
|
|
366
|
+
merged.push({ ...t });
|
|
367
|
+
}
|
|
368
|
+
return merged;
|
|
369
|
+
}
|
|
370
|
+
function parseUsage(raw) {
|
|
371
|
+
if (!raw || typeof raw !== 'object')
|
|
372
|
+
return null;
|
|
373
|
+
const u = raw;
|
|
374
|
+
const num = (k) => (typeof u[k] === 'number' ? u[k] : 0);
|
|
375
|
+
return {
|
|
376
|
+
input: num('input_tokens'),
|
|
377
|
+
output: num('output_tokens'),
|
|
378
|
+
cacheRead: num('cache_read_tokens'),
|
|
379
|
+
cacheWrite: num('cache_write_tokens'),
|
|
380
|
+
costUsd: num('cost_usd'),
|
|
381
|
+
agentHours: num('agent_hours'),
|
|
382
|
+
resolvedModelId: typeof u['resolved_model_id'] === 'string' ? u['resolved_model_id'] : '',
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
//# sourceMappingURL=session.js.map
|