skydive-cli 0.1.0-beta.109 → 0.1.0-beta.163
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/dist/js/bin.mjs +947 -19
- package/dist/js/{boot-DRWra2vY.mjs → boot-B-eA8M6t.mjs} +12 -39
- package/package.json +1 -1
- package/dist/js/print-CQ8b7JUC.mjs +0 -745
package/dist/js/bin.mjs
CHANGED
|
@@ -11,9 +11,27 @@ import { spawnSync } from "node:child_process";
|
|
|
11
11
|
import { createHash } from "node:crypto";
|
|
12
12
|
import fs from "node:fs";
|
|
13
13
|
import zlib from "node:zlib";
|
|
14
|
+
import { createParser } from "eventsource-parser";
|
|
14
15
|
|
|
16
|
+
//#region \0rolldown/runtime.js
|
|
17
|
+
var __defProp = Object.defineProperty;
|
|
18
|
+
var __exportAll = (all, no_symbols) => {
|
|
19
|
+
let target = {};
|
|
20
|
+
for (var name in all) {
|
|
21
|
+
__defProp(target, name, {
|
|
22
|
+
get: all[name],
|
|
23
|
+
enumerable: true
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
if (!no_symbols) {
|
|
27
|
+
__defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
28
|
+
}
|
|
29
|
+
return target;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
//#endregion
|
|
15
33
|
//#region package.json
|
|
16
|
-
var version$1 = "0.1.0-beta.
|
|
34
|
+
var version$1 = "0.1.0-beta.163";
|
|
17
35
|
|
|
18
36
|
//#endregion
|
|
19
37
|
//#region src/types.ts
|
|
@@ -553,7 +571,7 @@ async function loginWithDevice({ appUrl, openBrowser = true }) {
|
|
|
553
571
|
let intervalMs = (code.interval ?? 5) * 1e3 || DEFAULT_INTERVAL_MS;
|
|
554
572
|
const expiresAt = Date.now() + code.expires_in * 1e3;
|
|
555
573
|
while (Date.now() < expiresAt) {
|
|
556
|
-
await sleep(intervalMs);
|
|
574
|
+
await sleep$1(intervalMs);
|
|
557
575
|
const result = await pollDeviceToken({
|
|
558
576
|
appUrl,
|
|
559
577
|
deviceCode: code.device_code,
|
|
@@ -601,7 +619,7 @@ function formatUserCode(code) {
|
|
|
601
619
|
if (code.length !== 8) return code;
|
|
602
620
|
return `${code.slice(0, 4)}-${code.slice(4)}`;
|
|
603
621
|
}
|
|
604
|
-
function sleep(ms) {
|
|
622
|
+
function sleep$1(ms) {
|
|
605
623
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
606
624
|
}
|
|
607
625
|
|
|
@@ -794,7 +812,7 @@ function requireClient$2(argv) {
|
|
|
794
812
|
}
|
|
795
813
|
return new SkydiveApiClient(result.value);
|
|
796
814
|
}
|
|
797
|
-
const listCommand$
|
|
815
|
+
const listCommand$4 = {
|
|
798
816
|
command: "list",
|
|
799
817
|
describe: "List agents",
|
|
800
818
|
builder: (y) => y.option("limit", {
|
|
@@ -938,7 +956,7 @@ const createCommand$1 = {
|
|
|
938
956
|
const agentsCommand = {
|
|
939
957
|
command: "agents",
|
|
940
958
|
describe: "Manage agents",
|
|
941
|
-
builder: (y) => y.command(listCommand$
|
|
959
|
+
builder: (y) => y.command(listCommand$4).command(getCommand).command(createCommand$1).demandCommand(1, "Specify a subcommand: list, get, create"),
|
|
942
960
|
handler: () => {}
|
|
943
961
|
};
|
|
944
962
|
|
|
@@ -952,7 +970,7 @@ function requireClient$1(argv) {
|
|
|
952
970
|
}
|
|
953
971
|
return new SkydiveApiClient(result.value);
|
|
954
972
|
}
|
|
955
|
-
const listCommand$
|
|
973
|
+
const listCommand$3 = {
|
|
956
974
|
command: "list",
|
|
957
975
|
describe: "List API keys for an agent",
|
|
958
976
|
handler: async (argv) => {
|
|
@@ -1041,7 +1059,7 @@ const keysCommand = {
|
|
|
1041
1059
|
type: "string",
|
|
1042
1060
|
demandOption: true,
|
|
1043
1061
|
describe: "Agent ID"
|
|
1044
|
-
}).command(listCommand$
|
|
1062
|
+
}).command(listCommand$3).command(createCommand).command(revokeCommand).demandCommand(1, "Specify a subcommand: list, create, revoke"),
|
|
1045
1063
|
handler: () => {}
|
|
1046
1064
|
};
|
|
1047
1065
|
|
|
@@ -1056,12 +1074,12 @@ function requireClient(argv) {
|
|
|
1056
1074
|
return new SkydiveApiClient(result.value);
|
|
1057
1075
|
}
|
|
1058
1076
|
/** Read all of stdin as UTF-8, trimming a single trailing newline. */
|
|
1059
|
-
async function readStdin() {
|
|
1077
|
+
async function readStdin$1() {
|
|
1060
1078
|
const chunks = [];
|
|
1061
1079
|
for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
1062
1080
|
return Buffer.concat(chunks).toString("utf8").replace(/\n$/, "");
|
|
1063
1081
|
}
|
|
1064
|
-
const listCommand$
|
|
1082
|
+
const listCommand$2 = {
|
|
1065
1083
|
command: "list",
|
|
1066
1084
|
describe: "List secret names for an agent (values are never shown)",
|
|
1067
1085
|
handler: async (argv) => {
|
|
@@ -1100,7 +1118,7 @@ const setCommand = {
|
|
|
1100
1118
|
printError("No value given. Pass it as an argument or pipe it on stdin, e.g. `echo -n \"$TOKEN\" | skydive secrets set MY_KEY --agent-id <id>`.");
|
|
1101
1119
|
process.exit(1);
|
|
1102
1120
|
}
|
|
1103
|
-
value = await readStdin();
|
|
1121
|
+
value = await readStdin$1();
|
|
1104
1122
|
}
|
|
1105
1123
|
if (!value) {
|
|
1106
1124
|
printError("Empty secret value.");
|
|
@@ -1147,7 +1165,7 @@ const secretsCommand = {
|
|
|
1147
1165
|
type: "string",
|
|
1148
1166
|
demandOption: true,
|
|
1149
1167
|
describe: "Agent ID"
|
|
1150
|
-
}).command(listCommand$
|
|
1168
|
+
}).command(listCommand$2).command(setCommand).command(rmCommand).demandCommand(1, "Specify a subcommand: list, set, rm"),
|
|
1151
1169
|
handler: () => {}
|
|
1152
1170
|
};
|
|
1153
1171
|
|
|
@@ -2134,7 +2152,7 @@ const chatCommand = {
|
|
|
2134
2152
|
printError(`Unknown theme "${themeId}". Valid themes: ${themes.map((t) => t.id).join(", ")}`);
|
|
2135
2153
|
process.exit(1);
|
|
2136
2154
|
}
|
|
2137
|
-
const { runChat } = await import("./boot-
|
|
2155
|
+
const { runChat } = await import("./boot-B-eA8M6t.mjs");
|
|
2138
2156
|
await runChat({
|
|
2139
2157
|
appUrl,
|
|
2140
2158
|
sessionToken: session.value.sessionToken,
|
|
@@ -2152,7 +2170,7 @@ async function runPrintMode({ argv, appUrl }) {
|
|
|
2152
2170
|
printError(`${session.error.message} For non-interactive use, run \`skydive auth login --web\` first, or set SKYDIVE_SESSION_TOKEN.`);
|
|
2153
2171
|
process.exit(1);
|
|
2154
2172
|
}
|
|
2155
|
-
const { runPrint, readStdin } = await
|
|
2173
|
+
const { runPrint, readStdin } = await Promise.resolve().then(() => print_exports);
|
|
2156
2174
|
let prompt = (argv.print ?? "").trim();
|
|
2157
2175
|
if (!prompt) {
|
|
2158
2176
|
if (process.stdin.isTTY) {
|
|
@@ -2182,15 +2200,925 @@ async function runPrintMode({ argv, appUrl }) {
|
|
|
2182
2200
|
}
|
|
2183
2201
|
|
|
2184
2202
|
//#endregion
|
|
2185
|
-
//#region src/
|
|
2203
|
+
//#region src/chat/api/rest.ts
|
|
2204
|
+
var HttpError = class extends Error {
|
|
2205
|
+
constructor(status, body) {
|
|
2206
|
+
super(`HTTP ${status}: ${body.slice(0, 200)}`);
|
|
2207
|
+
this.status = status;
|
|
2208
|
+
this.body = body;
|
|
2209
|
+
this.name = "HttpError";
|
|
2210
|
+
}
|
|
2211
|
+
};
|
|
2212
|
+
const MAX_STREAM_RECONNECTS = 5;
|
|
2213
|
+
function createRestClient({ appUrl, sessionToken }) {
|
|
2214
|
+
const baseHeaders = {
|
|
2215
|
+
authorization: `Bearer ${sessionToken}`,
|
|
2216
|
+
accept: "application/json"
|
|
2217
|
+
};
|
|
2218
|
+
async function get(path, schema) {
|
|
2219
|
+
const res = await fetch(`${appUrl}${path}`, { headers: baseHeaders });
|
|
2220
|
+
if (!res.ok) throw new HttpError(res.status, await res.text().catch(() => ""));
|
|
2221
|
+
return schema.parse(await res.json());
|
|
2222
|
+
}
|
|
2223
|
+
async function post(path, body, schema, method = "POST") {
|
|
2224
|
+
const res = await fetch(`${appUrl}${path}`, {
|
|
2225
|
+
method,
|
|
2226
|
+
headers: {
|
|
2227
|
+
...baseHeaders,
|
|
2228
|
+
"content-type": "application/json"
|
|
2229
|
+
},
|
|
2230
|
+
body: JSON.stringify(body)
|
|
2231
|
+
});
|
|
2232
|
+
if (!res.ok) throw new HttpError(res.status, await res.text().catch(() => ""));
|
|
2233
|
+
return schema.parse(await res.json());
|
|
2234
|
+
}
|
|
2235
|
+
async function del(path) {
|
|
2236
|
+
const res = await fetch(`${appUrl}${path}`, {
|
|
2237
|
+
method: "DELETE",
|
|
2238
|
+
headers: baseHeaders
|
|
2239
|
+
});
|
|
2240
|
+
if (!res.ok) throw new HttpError(res.status, await res.text().catch(() => ""));
|
|
2241
|
+
}
|
|
2242
|
+
return {
|
|
2243
|
+
listAgents: async ({ scope, onPage }) => {
|
|
2244
|
+
const all = [];
|
|
2245
|
+
let cursor;
|
|
2246
|
+
const maxAgents = 2e3;
|
|
2247
|
+
do {
|
|
2248
|
+
const params = new URLSearchParams({
|
|
2249
|
+
limit: "100",
|
|
2250
|
+
scope,
|
|
2251
|
+
sort: "mine_first_usage",
|
|
2252
|
+
includeStats: "false"
|
|
2253
|
+
});
|
|
2254
|
+
if (cursor) params.set("cursor", cursor);
|
|
2255
|
+
const page = await get(`/api/v1/agents?${params.toString()}`, listAgentsResponseSchema);
|
|
2256
|
+
all.push(...page.agents);
|
|
2257
|
+
cursor = page.nextCursor ?? void 0;
|
|
2258
|
+
onPage?.([...all]);
|
|
2259
|
+
} while (cursor && all.length < maxAgents);
|
|
2260
|
+
return all;
|
|
2261
|
+
},
|
|
2262
|
+
createAgent: async ({ name }) => {
|
|
2263
|
+
const { agent } = await post("/api/v1/agents", { name }, createAgentResponseSchema);
|
|
2264
|
+
return agent;
|
|
2265
|
+
},
|
|
2266
|
+
getConversation: async ({ conversationId }) => {
|
|
2267
|
+
const { conversation } = await get(`/api/v1/conversations/${encodeURIComponent(conversationId)}`, getConversationResponseSchema);
|
|
2268
|
+
return conversation;
|
|
2269
|
+
},
|
|
2270
|
+
listModels: async () => {
|
|
2271
|
+
const { models } = await get("/api/v1/models", listModelsResponseSchema);
|
|
2272
|
+
return models;
|
|
2273
|
+
},
|
|
2274
|
+
updateAgentModel: async ({ agentId, model }) => {
|
|
2275
|
+
const { agent } = await post(`/api/v1/agents/${encodeURIComponent(agentId)}`, { model }, updateAgentResponseSchema, "PATCH");
|
|
2276
|
+
return { model: agent.model ?? null };
|
|
2277
|
+
},
|
|
2278
|
+
listConversations: async ({ agentId, limit }) => {
|
|
2279
|
+
const all = [];
|
|
2280
|
+
const maxConversations = limit ?? 5e3;
|
|
2281
|
+
let cursor;
|
|
2282
|
+
do {
|
|
2283
|
+
const remaining = maxConversations - all.length;
|
|
2284
|
+
const params = new URLSearchParams({
|
|
2285
|
+
agentId,
|
|
2286
|
+
includeTotal: "false"
|
|
2287
|
+
});
|
|
2288
|
+
params.set("limit", String(Math.min(remaining, 100)));
|
|
2289
|
+
if (cursor) params.set("cursor", cursor);
|
|
2290
|
+
const page = await get(`/api/v1/conversations?${params.toString()}`, listConversationsResponseSchema);
|
|
2291
|
+
all.push(...page.conversations);
|
|
2292
|
+
cursor = page.nextCursor ?? void 0;
|
|
2293
|
+
} while (cursor && all.length < maxConversations);
|
|
2294
|
+
return limit ? all.slice(0, limit) : all;
|
|
2295
|
+
},
|
|
2296
|
+
listMessages: async ({ conversationId }) => {
|
|
2297
|
+
const { messages } = await get(`/api/v1/conversations/${encodeURIComponent(conversationId)}/messages`, listMessagesResponseSchema);
|
|
2298
|
+
return messages;
|
|
2299
|
+
},
|
|
2300
|
+
getRecap: async ({ conversationId }) => {
|
|
2301
|
+
const { recap } = await get(`/api/v1/conversations/${encodeURIComponent(conversationId)}/recap`, recapResponseSchema);
|
|
2302
|
+
return recap?.text ?? null;
|
|
2303
|
+
},
|
|
2304
|
+
uploadAttachment: async ({ agentId, fileName, mediaType, data }) => {
|
|
2305
|
+
const size = data.byteLength;
|
|
2306
|
+
const presign = await post("/api/v1/attachments/presign", {
|
|
2307
|
+
agentId,
|
|
2308
|
+
fileName,
|
|
2309
|
+
mediaType,
|
|
2310
|
+
size
|
|
2311
|
+
}, presignResponseSchema);
|
|
2312
|
+
const putRes = await fetch(presign.uploadUrl, {
|
|
2313
|
+
method: "PUT",
|
|
2314
|
+
headers: { "content-type": mediaType },
|
|
2315
|
+
body: new Uint8Array(data)
|
|
2316
|
+
});
|
|
2317
|
+
if (!putRes.ok) throw new HttpError(putRes.status, await putRes.text().catch(() => ""));
|
|
2318
|
+
const finalized = await post(`/api/v1/attachments/${encodeURIComponent(presign.id)}/finalize`, {
|
|
2319
|
+
agentId,
|
|
2320
|
+
fileName: presign.fileName,
|
|
2321
|
+
mediaType: presign.mediaType,
|
|
2322
|
+
size
|
|
2323
|
+
}, finalizeResponseSchema);
|
|
2324
|
+
return {
|
|
2325
|
+
id: presign.id,
|
|
2326
|
+
fileName: finalized.fileName,
|
|
2327
|
+
mediaType: finalized.mediaType,
|
|
2328
|
+
sizeBytes: finalized.sizeBytes ?? size
|
|
2329
|
+
};
|
|
2330
|
+
},
|
|
2331
|
+
deleteConversation: async ({ conversationId }) => {
|
|
2332
|
+
await del(`/api/v1/conversations/${encodeURIComponent(conversationId)}`);
|
|
2333
|
+
},
|
|
2334
|
+
sendMessage: async ({ clientSurface, ...input }) => post("/api/v1/chat/send", {
|
|
2335
|
+
...input,
|
|
2336
|
+
clientSurface
|
|
2337
|
+
}, sendResultSchema),
|
|
2338
|
+
activeRun: async ({ conversationId }) => {
|
|
2339
|
+
const { run } = await get(`/api/v1/chat/active-run?${new URLSearchParams({ conversationId }).toString()}`, activeRunResponseSchema);
|
|
2340
|
+
return run;
|
|
2341
|
+
},
|
|
2342
|
+
cancelRun: async ({ runId }) => {
|
|
2343
|
+
await post(`/api/v1/chat/runs/${encodeURIComponent(runId)}/cancel`, {}, z.object({ ok: z.boolean() }));
|
|
2344
|
+
},
|
|
2345
|
+
cancelSteer: async ({ directiveId }) => {
|
|
2346
|
+
await post(`/api/v1/chat/steer/${encodeURIComponent(directiveId)}/cancel`, {}, z.object({ ok: z.boolean() }));
|
|
2347
|
+
},
|
|
2348
|
+
oauthConnect: async (input) => {
|
|
2349
|
+
const { connectLink } = await post("/api/v1/oauth/connect", input, oauthConnectResponseSchema);
|
|
2350
|
+
return { connectLink };
|
|
2351
|
+
},
|
|
2352
|
+
externalOauthConnect: async (input) => {
|
|
2353
|
+
const { authorizationUrl } = await post("/api/v1/external-oauth/connect", input, externalOauthConnectResponseSchema);
|
|
2354
|
+
return { authorizationUrl: authorizationUrl ?? null };
|
|
2355
|
+
},
|
|
2356
|
+
fulfillCredential: async ({ url, body }) => {
|
|
2357
|
+
const target = new URL(url, appUrl).toString();
|
|
2358
|
+
const res = await fetch(target, {
|
|
2359
|
+
method: "POST",
|
|
2360
|
+
headers: {
|
|
2361
|
+
...baseHeaders,
|
|
2362
|
+
"content-type": "application/json"
|
|
2363
|
+
},
|
|
2364
|
+
body: JSON.stringify(body)
|
|
2365
|
+
});
|
|
2366
|
+
if (!res.ok) throw new HttpError(res.status, await res.text().catch(() => ""));
|
|
2367
|
+
},
|
|
2368
|
+
streamRun: async ({ runId, signal, onEvent }) => {
|
|
2369
|
+
let lastEventId = null;
|
|
2370
|
+
let finished = false;
|
|
2371
|
+
let reconnects = 0;
|
|
2372
|
+
for (;;) {
|
|
2373
|
+
if (signal.aborted) return;
|
|
2374
|
+
try {
|
|
2375
|
+
const headers = {
|
|
2376
|
+
authorization: `Bearer ${sessionToken}`,
|
|
2377
|
+
accept: "text/event-stream"
|
|
2378
|
+
};
|
|
2379
|
+
if (lastEventId) headers["last-event-id"] = lastEventId;
|
|
2380
|
+
const res = await fetch(`${appUrl}/api/v1/chat/runs/${encodeURIComponent(runId)}/stream`, {
|
|
2381
|
+
headers,
|
|
2382
|
+
signal
|
|
2383
|
+
});
|
|
2384
|
+
if (!res.ok || !res.body) throw new HttpError(res.status, await res.text().catch(() => ""));
|
|
2385
|
+
reconnects = 0;
|
|
2386
|
+
const parser = createParser({ onEvent: (message) => {
|
|
2387
|
+
if (message.id) lastEventId = message.id;
|
|
2388
|
+
if (message.event === "error") {
|
|
2389
|
+
const { error } = streamErrorSchema.parse(JSON.parse(message.data));
|
|
2390
|
+
throw new Error(error);
|
|
2391
|
+
}
|
|
2392
|
+
const event = runStreamEventSchema.parse(JSON.parse(message.data));
|
|
2393
|
+
if (event.kind === "finished") finished = true;
|
|
2394
|
+
onEvent(event.kind === "finished" ? {
|
|
2395
|
+
...event,
|
|
2396
|
+
error: event.error ?? null
|
|
2397
|
+
} : event);
|
|
2398
|
+
} });
|
|
2399
|
+
const decoder = new TextDecoder();
|
|
2400
|
+
const reader = res.body.getReader();
|
|
2401
|
+
try {
|
|
2402
|
+
for (;;) {
|
|
2403
|
+
const { done, value } = await reader.read();
|
|
2404
|
+
if (done) break;
|
|
2405
|
+
parser.feed(decoder.decode(value, { stream: true }));
|
|
2406
|
+
if (finished) return;
|
|
2407
|
+
}
|
|
2408
|
+
} finally {
|
|
2409
|
+
try {
|
|
2410
|
+
await reader.cancel();
|
|
2411
|
+
} catch (_error) {}
|
|
2412
|
+
}
|
|
2413
|
+
} catch (err) {
|
|
2414
|
+
if (signal.aborted) return;
|
|
2415
|
+
if (err instanceof HttpError && err.status >= 400 && err.status < 500) throw err;
|
|
2416
|
+
reconnects += 1;
|
|
2417
|
+
if (reconnects > MAX_STREAM_RECONNECTS) throw err;
|
|
2418
|
+
await sleep(Math.min(500 * 2 ** reconnects, 5e3));
|
|
2419
|
+
continue;
|
|
2420
|
+
}
|
|
2421
|
+
if (finished) return;
|
|
2422
|
+
reconnects += 1;
|
|
2423
|
+
if (reconnects > MAX_STREAM_RECONNECTS) throw new Error("run stream ended unexpectedly");
|
|
2424
|
+
await sleep(Math.min(500 * 2 ** reconnects, 5e3));
|
|
2425
|
+
}
|
|
2426
|
+
},
|
|
2427
|
+
streamConversation: async ({ conversationId, signal, onEvent }) => {
|
|
2428
|
+
let reconnects = 0;
|
|
2429
|
+
for (;;) {
|
|
2430
|
+
if (signal.aborted) return;
|
|
2431
|
+
try {
|
|
2432
|
+
const res = await fetch(`${appUrl}/api/v1/chat/conversations/${encodeURIComponent(conversationId)}/stream`, {
|
|
2433
|
+
headers: {
|
|
2434
|
+
authorization: `Bearer ${sessionToken}`,
|
|
2435
|
+
accept: "text/event-stream"
|
|
2436
|
+
},
|
|
2437
|
+
signal
|
|
2438
|
+
});
|
|
2439
|
+
if (!res.ok || !res.body) throw new HttpError(res.status, await res.text().catch(() => ""));
|
|
2440
|
+
reconnects = 0;
|
|
2441
|
+
const parser = createParser({ onEvent: (message) => {
|
|
2442
|
+
const parsed = conversationStreamEventSchema.safeParse(JSON.parse(message.data));
|
|
2443
|
+
if (parsed.success) onEvent(parsed.data);
|
|
2444
|
+
} });
|
|
2445
|
+
const decoder = new TextDecoder();
|
|
2446
|
+
const reader = res.body.getReader();
|
|
2447
|
+
try {
|
|
2448
|
+
for (;;) {
|
|
2449
|
+
const { done, value } = await reader.read();
|
|
2450
|
+
if (done) break;
|
|
2451
|
+
parser.feed(decoder.decode(value, { stream: true }));
|
|
2452
|
+
}
|
|
2453
|
+
} finally {
|
|
2454
|
+
try {
|
|
2455
|
+
await reader.cancel();
|
|
2456
|
+
} catch (_error) {}
|
|
2457
|
+
}
|
|
2458
|
+
} catch (err) {
|
|
2459
|
+
if (signal.aborted) return;
|
|
2460
|
+
if (err instanceof HttpError && err.status >= 400 && err.status < 500) throw err;
|
|
2461
|
+
reconnects += 1;
|
|
2462
|
+
if (reconnects > MAX_STREAM_RECONNECTS) throw err;
|
|
2463
|
+
await sleep(Math.min(500 * 2 ** reconnects, 5e3));
|
|
2464
|
+
continue;
|
|
2465
|
+
}
|
|
2466
|
+
if (signal.aborted) return;
|
|
2467
|
+
reconnects += 1;
|
|
2468
|
+
if (reconnects > MAX_STREAM_RECONNECTS) throw new Error("conversation stream ended unexpectedly");
|
|
2469
|
+
await sleep(Math.min(500 * 2 ** reconnects, 5e3));
|
|
2470
|
+
}
|
|
2471
|
+
}
|
|
2472
|
+
};
|
|
2473
|
+
}
|
|
2474
|
+
function sleep(ms) {
|
|
2475
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2476
|
+
}
|
|
2477
|
+
const agentSummarySchema = z.object({
|
|
2478
|
+
id: z.string().uuid(),
|
|
2479
|
+
name: z.string(),
|
|
2480
|
+
slug: z.string().nullable().optional(),
|
|
2481
|
+
title: z.string().nullable().optional(),
|
|
2482
|
+
description: z.string().nullable().optional(),
|
|
2483
|
+
createdAt: z.string(),
|
|
2484
|
+
creatorName: z.string().nullable().optional(),
|
|
2485
|
+
model: z.string().nullable().optional(),
|
|
2486
|
+
modelLocked: z.boolean().optional()
|
|
2487
|
+
});
|
|
2488
|
+
const platformModelSchema = z.object({
|
|
2489
|
+
id: z.string(),
|
|
2490
|
+
displayName: z.string(),
|
|
2491
|
+
providerDisplay: z.string().optional(),
|
|
2492
|
+
reasoning: z.boolean().optional(),
|
|
2493
|
+
compliant: z.boolean().optional()
|
|
2494
|
+
}).passthrough();
|
|
2495
|
+
const listModelsResponseSchema = z.object({ models: z.array(platformModelSchema) });
|
|
2496
|
+
const updateAgentResponseSchema = z.object({ agent: z.object({ model: z.string().nullable().optional() }).passthrough() });
|
|
2497
|
+
const listAgentsResponseSchema = z.object({
|
|
2498
|
+
agents: z.array(agentSummarySchema),
|
|
2499
|
+
nextCursor: z.string().nullable().optional(),
|
|
2500
|
+
totalCount: z.number().nullable().optional()
|
|
2501
|
+
});
|
|
2502
|
+
const createAgentResponseSchema = z.object({ agent: agentSummarySchema });
|
|
2503
|
+
const conversationSummarySchema = z.object({
|
|
2504
|
+
id: z.string().uuid(),
|
|
2505
|
+
title: z.string().nullable(),
|
|
2506
|
+
createdAt: z.string(),
|
|
2507
|
+
updatedAt: z.string(),
|
|
2508
|
+
preview: z.string().nullable(),
|
|
2509
|
+
channel: z.string().nullable(),
|
|
2510
|
+
channelLabel: z.string().nullable(),
|
|
2511
|
+
agent: z.object({
|
|
2512
|
+
id: z.string().uuid(),
|
|
2513
|
+
name: z.string(),
|
|
2514
|
+
slug: z.string().nullable().optional(),
|
|
2515
|
+
title: z.string().nullable().optional()
|
|
2516
|
+
})
|
|
2517
|
+
});
|
|
2518
|
+
const conversationTitleSchema = z.object({
|
|
2519
|
+
id: z.string().uuid(),
|
|
2520
|
+
title: z.string().nullable()
|
|
2521
|
+
});
|
|
2522
|
+
const getConversationResponseSchema = z.object({ conversation: conversationTitleSchema });
|
|
2523
|
+
const listConversationsResponseSchema = z.object({
|
|
2524
|
+
conversations: z.array(conversationSummarySchema),
|
|
2525
|
+
nextCursor: z.string().nullable().optional(),
|
|
2526
|
+
totalCount: z.number().optional()
|
|
2527
|
+
});
|
|
2528
|
+
const uiMessagePartSchema = z.union([
|
|
2529
|
+
z.object({
|
|
2530
|
+
type: z.literal("text"),
|
|
2531
|
+
text: z.string()
|
|
2532
|
+
}),
|
|
2533
|
+
z.object({
|
|
2534
|
+
type: z.literal("reasoning"),
|
|
2535
|
+
text: z.string().optional()
|
|
2536
|
+
}),
|
|
2537
|
+
z.object({
|
|
2538
|
+
type: z.literal("dynamic-tool"),
|
|
2539
|
+
toolCallId: z.string(),
|
|
2540
|
+
toolName: z.string(),
|
|
2541
|
+
input: z.unknown().optional(),
|
|
2542
|
+
output: z.unknown().optional(),
|
|
2543
|
+
state: z.string().optional(),
|
|
2544
|
+
errorText: z.string().optional()
|
|
2545
|
+
}),
|
|
2546
|
+
z.object({ type: z.string() }).passthrough()
|
|
2547
|
+
]);
|
|
2548
|
+
const uiMessageSchema = z.object({
|
|
2549
|
+
id: z.string(),
|
|
2550
|
+
role: z.string(),
|
|
2551
|
+
parts: z.array(uiMessagePartSchema)
|
|
2552
|
+
});
|
|
2553
|
+
const recapResponseSchema = z.object({ recap: z.object({ text: z.string() }).nullable() });
|
|
2554
|
+
const listMessagesResponseSchema = z.object({ messages: z.array(uiMessageSchema) });
|
|
2555
|
+
const sendResultSchema = z.object({
|
|
2556
|
+
runId: z.string(),
|
|
2557
|
+
conversationId: z.string().uuid(),
|
|
2558
|
+
isNewConversation: z.boolean(),
|
|
2559
|
+
steered: z.boolean().optional(),
|
|
2560
|
+
directive: z.object({ id: z.string() }).passthrough().optional()
|
|
2561
|
+
});
|
|
2562
|
+
const presignResponseSchema = z.object({
|
|
2563
|
+
id: z.string(),
|
|
2564
|
+
uploadUrl: z.string(),
|
|
2565
|
+
fileName: z.string(),
|
|
2566
|
+
mediaType: z.string()
|
|
2567
|
+
});
|
|
2568
|
+
const finalizeResponseSchema = z.object({
|
|
2569
|
+
fileName: z.string(),
|
|
2570
|
+
mediaType: z.string(),
|
|
2571
|
+
sizeBytes: z.number().nullable().optional()
|
|
2572
|
+
});
|
|
2573
|
+
const activeRunResponseSchema = z.object({ run: z.object({ runId: z.string() }).nullable() });
|
|
2574
|
+
const oauthConnectResponseSchema = z.object({ connectLink: z.string() }).passthrough();
|
|
2575
|
+
const externalOauthConnectResponseSchema = z.object({ authorizationUrl: z.string().optional() }).passthrough();
|
|
2576
|
+
const runStreamEventSchema = z.union([z.object({
|
|
2577
|
+
kind: z.literal("chunk"),
|
|
2578
|
+
chunk: z.record(z.unknown())
|
|
2579
|
+
}), z.object({
|
|
2580
|
+
kind: z.literal("finished"),
|
|
2581
|
+
status: z.string(),
|
|
2582
|
+
error: z.string().nullish()
|
|
2583
|
+
})]);
|
|
2584
|
+
const streamErrorSchema = z.object({ error: z.string() });
|
|
2585
|
+
const conversationStreamEventSchema = z.object({
|
|
2586
|
+
kind: z.literal("conversation"),
|
|
2587
|
+
id: z.string(),
|
|
2588
|
+
title: z.string().nullable()
|
|
2589
|
+
});
|
|
2590
|
+
|
|
2591
|
+
//#endregion
|
|
2592
|
+
//#region src/chat/util.ts
|
|
2593
|
+
/** Narrowing helper for the many `unknown` payloads the chat stream and
|
|
2594
|
+
* tool inputs/outputs carry. A type predicate (not an `as` cast), so call
|
|
2595
|
+
* sites can read properties without asserting. */
|
|
2596
|
+
function isRecord(value) {
|
|
2597
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2598
|
+
}
|
|
2599
|
+
/** Best-effort message from an unknown thrown value. */
|
|
2600
|
+
function errorMessage(err) {
|
|
2601
|
+
return err instanceof Error ? err.message : String(err);
|
|
2602
|
+
}
|
|
2603
|
+
|
|
2604
|
+
//#endregion
|
|
2605
|
+
//#region src/chat/tui/chat/card.ts
|
|
2606
|
+
const urlActionKinds = [
|
|
2607
|
+
"open_oauth",
|
|
2608
|
+
"open_external_oauth",
|
|
2609
|
+
"open_github_app",
|
|
2610
|
+
"submit_credential"
|
|
2611
|
+
];
|
|
2612
|
+
function isUrlActionKind(value) {
|
|
2613
|
+
return typeof value === "string" && urlActionKinds.includes(value);
|
|
2614
|
+
}
|
|
2615
|
+
function optionalString(value) {
|
|
2616
|
+
return typeof value === "string" && value ? value : null;
|
|
2617
|
+
}
|
|
2618
|
+
function bindStateKey(props) {
|
|
2619
|
+
const value = props.value;
|
|
2620
|
+
if (!isRecord(value)) return null;
|
|
2621
|
+
const pointer = value.$bindState;
|
|
2622
|
+
if (typeof pointer !== "string") return null;
|
|
2623
|
+
return pointer.startsWith("/") ? pointer.slice(1) : pointer;
|
|
2624
|
+
}
|
|
2625
|
+
function parseButton(element) {
|
|
2626
|
+
const props = isRecord(element.props) ? element.props : {};
|
|
2627
|
+
const label = optionalString(props.label) ?? "Connect";
|
|
2628
|
+
const on = isRecord(element.on) ? element.on : null;
|
|
2629
|
+
const press = on && isRecord(on.press) ? on.press : null;
|
|
2630
|
+
if (!press) return null;
|
|
2631
|
+
const params = isRecord(press.params) ? press.params : {};
|
|
2632
|
+
const primary = props.variant === "primary";
|
|
2633
|
+
if (press.action === "approve_portal_access") {
|
|
2634
|
+
const agentId = params.agentId;
|
|
2635
|
+
if (typeof agentId !== "string" || !agentId) return null;
|
|
2636
|
+
return {
|
|
2637
|
+
label,
|
|
2638
|
+
action: {
|
|
2639
|
+
kind: "grant_portal",
|
|
2640
|
+
agentId,
|
|
2641
|
+
deviceId: typeof params.deviceId === "string" && params.deviceId ? params.deviceId : null
|
|
2642
|
+
},
|
|
2643
|
+
primary
|
|
2644
|
+
};
|
|
2645
|
+
}
|
|
2646
|
+
if (!isUrlActionKind(press.action)) return null;
|
|
2647
|
+
const url = params.url;
|
|
2648
|
+
if (typeof url !== "string" || !url) return null;
|
|
2649
|
+
return {
|
|
2650
|
+
label,
|
|
2651
|
+
action: {
|
|
2652
|
+
kind: press.action,
|
|
2653
|
+
url
|
|
2654
|
+
},
|
|
2655
|
+
primary
|
|
2656
|
+
};
|
|
2657
|
+
}
|
|
2658
|
+
function parseConnectCard(spec) {
|
|
2659
|
+
if (!isRecord(spec)) return null;
|
|
2660
|
+
const { root, elements } = spec;
|
|
2661
|
+
if (typeof root !== "string" || !isRecord(elements)) return null;
|
|
2662
|
+
const rootEl = elements[root];
|
|
2663
|
+
if (!isRecord(rootEl) || rootEl.type !== "Card") return null;
|
|
2664
|
+
const rootProps = isRecord(rootEl.props) ? rootEl.props : {};
|
|
2665
|
+
const title = optionalString(rootProps.title);
|
|
2666
|
+
if (!title) return null;
|
|
2667
|
+
const fields = [];
|
|
2668
|
+
const buttons = [];
|
|
2669
|
+
const children = Array.isArray(rootEl.children) ? rootEl.children : [];
|
|
2670
|
+
for (const childId of children) {
|
|
2671
|
+
if (typeof childId !== "string") continue;
|
|
2672
|
+
const el = elements[childId];
|
|
2673
|
+
if (!isRecord(el)) continue;
|
|
2674
|
+
if (el.type === "TextInput" || el.type === "SecretInput") {
|
|
2675
|
+
const props = isRecord(el.props) ? el.props : {};
|
|
2676
|
+
const key = bindStateKey(props);
|
|
2677
|
+
if (!key) continue;
|
|
2678
|
+
fields.push({
|
|
2679
|
+
key,
|
|
2680
|
+
label: optionalString(props.label) ?? key,
|
|
2681
|
+
placeholder: optionalString(props.placeholder),
|
|
2682
|
+
secret: el.type === "SecretInput"
|
|
2683
|
+
});
|
|
2684
|
+
continue;
|
|
2685
|
+
}
|
|
2686
|
+
if (el.type === "Button") {
|
|
2687
|
+
const button = parseButton(el);
|
|
2688
|
+
if (button) buttons.push(button);
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
const preferred = buttons.find((b) => b.primary) ?? buttons[0] ?? null;
|
|
2692
|
+
return {
|
|
2693
|
+
title,
|
|
2694
|
+
subtitle: optionalString(rootProps.subtitle),
|
|
2695
|
+
description: optionalString(rootProps.description),
|
|
2696
|
+
fields,
|
|
2697
|
+
button: preferred ? {
|
|
2698
|
+
label: preferred.label,
|
|
2699
|
+
action: preferred.action
|
|
2700
|
+
} : null,
|
|
2701
|
+
state: isRecord(spec.state) ? spec.state : {}
|
|
2702
|
+
};
|
|
2703
|
+
}
|
|
2704
|
+
|
|
2705
|
+
//#endregion
|
|
2706
|
+
//#region src/chat/tui/chat/card-actions.ts
|
|
2707
|
+
function safeUrl(url) {
|
|
2708
|
+
try {
|
|
2709
|
+
return new URL(url, "http://localhost");
|
|
2710
|
+
} catch (_error) {
|
|
2711
|
+
return null;
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
/**
|
|
2715
|
+
* Resolve a connect URL to an absolute one the OS can open in a browser.
|
|
2716
|
+
*
|
|
2717
|
+
* The server builds lazy connect links as server-relative paths (e.g.
|
|
2718
|
+
* `/api/v1/oauth/start/slack?connect_session_token=...`). The web client
|
|
2719
|
+
* resolves these against its own origin implicitly; the TUI runs outside a
|
|
2720
|
+
* browser, so `open()` on a scheme-less path is a silent no-op — the browser
|
|
2721
|
+
* never launches and the connect card sits in `launched` forever (the Slack
|
|
2722
|
+
* channel-connect deadlock). Resolve against `appUrl` first, mirroring the
|
|
2723
|
+
* `open_github_app` / `fulfillCredential` branches, so both the browser we
|
|
2724
|
+
* launch and the URL shown on the card are absolute. An already-absolute URL
|
|
2725
|
+
* passes through unchanged; if `appUrl` is missing we return the input as-is.
|
|
2726
|
+
*/
|
|
2727
|
+
function resolveConnectUrl(url, appUrl) {
|
|
2728
|
+
if (!appUrl) return url;
|
|
2729
|
+
try {
|
|
2730
|
+
return new URL(url, appUrl).toString();
|
|
2731
|
+
} catch (_error) {
|
|
2732
|
+
return url;
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
function parseOauthConnectParams(url) {
|
|
2736
|
+
const parsed = safeUrl(url);
|
|
2737
|
+
if (!parsed) return null;
|
|
2738
|
+
const integrationKey = parsed.searchParams.get("integration");
|
|
2739
|
+
const agentId = parsed.searchParams.get("agent_id");
|
|
2740
|
+
const authConfigId = parsed.searchParams.get("auth_config_id");
|
|
2741
|
+
const conversationId = parsed.searchParams.get("conversation_id");
|
|
2742
|
+
if (!integrationKey || !agentId || !authConfigId || !conversationId) return null;
|
|
2743
|
+
return {
|
|
2744
|
+
integrationKey,
|
|
2745
|
+
agentId,
|
|
2746
|
+
authConfigId,
|
|
2747
|
+
conversationId,
|
|
2748
|
+
scopes: parsed.searchParams.get("scopes")
|
|
2749
|
+
};
|
|
2750
|
+
}
|
|
2751
|
+
function parseExternalOauthConnectParams(url) {
|
|
2752
|
+
const parsed = safeUrl(url);
|
|
2753
|
+
if (!parsed) return null;
|
|
2754
|
+
const agentId = parsed.searchParams.get("agent_id");
|
|
2755
|
+
const conversationId = parsed.searchParams.get("conversation_id");
|
|
2756
|
+
const serverUrl = parsed.searchParams.get("server_url");
|
|
2757
|
+
if (!agentId || !conversationId || !serverUrl) return null;
|
|
2758
|
+
return {
|
|
2759
|
+
agentId,
|
|
2760
|
+
conversationId,
|
|
2761
|
+
serverUrl
|
|
2762
|
+
};
|
|
2763
|
+
}
|
|
2764
|
+
/**
|
|
2765
|
+
* A short human line for a failed card action. Fulfill/connect endpoints
|
|
2766
|
+
* return `{ error: string }` bodies (e.g. "already fulfilled") — prefer that
|
|
2767
|
+
* over the generic HttpError message.
|
|
2768
|
+
*/
|
|
2769
|
+
function cardActionErrorMessage(err) {
|
|
2770
|
+
if (err instanceof HttpError) {
|
|
2771
|
+
try {
|
|
2772
|
+
const parsed = JSON.parse(err.body);
|
|
2773
|
+
if (isRecord(parsed) && typeof parsed.error === "string") return parsed.error;
|
|
2774
|
+
} catch (_error) {}
|
|
2775
|
+
return `request failed (HTTP ${err.status})`;
|
|
2776
|
+
}
|
|
2777
|
+
return errorMessage(err);
|
|
2778
|
+
}
|
|
2779
|
+
const MASK_CHAR = "•";
|
|
2780
|
+
/**
|
|
2781
|
+
* Recover the real secret from the masked input's displayed text. The input
|
|
2782
|
+
* is controlled: after every edit we render bullets, which forces the cursor
|
|
2783
|
+
* to the end, so the next edit is always a tail edit — the displayed text is
|
|
2784
|
+
* some prefix of the old mask (kept characters) followed by newly typed or
|
|
2785
|
+
* pasted plaintext. Characters beyond the retained bullets are the new tail.
|
|
2786
|
+
*/
|
|
2787
|
+
function reconcileMaskedInput(previousValue, displayed) {
|
|
2788
|
+
let kept = 0;
|
|
2789
|
+
while (kept < displayed.length && kept < previousValue.length && displayed[kept] === MASK_CHAR) kept++;
|
|
2790
|
+
return previousValue.slice(0, kept) + displayed.slice(kept);
|
|
2791
|
+
}
|
|
2792
|
+
|
|
2793
|
+
//#endregion
|
|
2794
|
+
//#region src/chat/connect-cards.ts
|
|
2795
|
+
/**
|
|
2796
|
+
* Turn a parsed ConnectCard into the headless summary, resolving any relative
|
|
2797
|
+
* connect URL against the app origin so the emitted URL is directly openable.
|
|
2798
|
+
*/
|
|
2799
|
+
function summarizeConnectCard(card, appUrl) {
|
|
2800
|
+
const base = {
|
|
2801
|
+
title: card.title,
|
|
2802
|
+
subtitle: card.subtitle,
|
|
2803
|
+
description: card.description
|
|
2804
|
+
};
|
|
2805
|
+
const button = card.button;
|
|
2806
|
+
if (!button) return {
|
|
2807
|
+
...base,
|
|
2808
|
+
action: { kind: "unsupported" }
|
|
2809
|
+
};
|
|
2810
|
+
const act = button.action;
|
|
2811
|
+
switch (act.kind) {
|
|
2812
|
+
case "open_oauth":
|
|
2813
|
+
case "open_external_oauth":
|
|
2814
|
+
case "open_github_app": return {
|
|
2815
|
+
...base,
|
|
2816
|
+
action: {
|
|
2817
|
+
kind: "open_url",
|
|
2818
|
+
url: resolveConnectUrl(act.url, appUrl)
|
|
2819
|
+
}
|
|
2820
|
+
};
|
|
2821
|
+
case "submit_credential": return {
|
|
2822
|
+
...base,
|
|
2823
|
+
action: {
|
|
2824
|
+
kind: "submit_credential",
|
|
2825
|
+
url: resolveConnectUrl(act.url, appUrl),
|
|
2826
|
+
fields: card.fields.map((f) => f.label)
|
|
2827
|
+
}
|
|
2828
|
+
};
|
|
2829
|
+
case "grant_portal": return {
|
|
2830
|
+
...base,
|
|
2831
|
+
action: {
|
|
2832
|
+
kind: "approve_portal",
|
|
2833
|
+
agentId: act.agentId
|
|
2834
|
+
}
|
|
2835
|
+
};
|
|
2836
|
+
default: return {
|
|
2837
|
+
...base,
|
|
2838
|
+
action: { kind: "unsupported" }
|
|
2839
|
+
};
|
|
2840
|
+
}
|
|
2841
|
+
}
|
|
2842
|
+
/**
|
|
2843
|
+
* Parse a `data-anyone-render-spec` stream chunk into a connect-card summary,
|
|
2844
|
+
* or null if the chunk isn't a connect card (other render specs — training,
|
|
2845
|
+
* deep-learn, compute-request — parse to null, same as the TUI).
|
|
2846
|
+
*/
|
|
2847
|
+
function connectCardFromChunk(chunk, appUrl) {
|
|
2848
|
+
if (chunk["type"] !== "data-anyone-render-spec") return null;
|
|
2849
|
+
const data = chunk["data"];
|
|
2850
|
+
if (!isRecord(data)) return null;
|
|
2851
|
+
const card = parseConnectCard(data["spec"]);
|
|
2852
|
+
if (!card) return null;
|
|
2853
|
+
return summarizeConnectCard(card, appUrl);
|
|
2854
|
+
}
|
|
2855
|
+
/** Render a connect-card summary as a human-readable action block. */
|
|
2856
|
+
function formatConnectCard(card) {
|
|
2857
|
+
const lines = [];
|
|
2858
|
+
lines.push(`\n[action needed] ${card.title}`);
|
|
2859
|
+
if (card.subtitle) lines.push(card.subtitle);
|
|
2860
|
+
if (card.description) lines.push(card.description);
|
|
2861
|
+
switch (card.action.kind) {
|
|
2862
|
+
case "open_url":
|
|
2863
|
+
lines.push(`Open to continue: ${card.action.url}`);
|
|
2864
|
+
break;
|
|
2865
|
+
case "submit_credential":
|
|
2866
|
+
lines.push(`Provide credential (${card.action.fields.join(", ") || "value"}) at: ${card.action.url}`);
|
|
2867
|
+
break;
|
|
2868
|
+
case "approve_portal":
|
|
2869
|
+
lines.push(`Approve local-machine access for agent ${card.action.agentId} in the TUI or web app.`);
|
|
2870
|
+
break;
|
|
2871
|
+
case "unsupported":
|
|
2872
|
+
lines.push("Open this conversation in the web app to continue.");
|
|
2873
|
+
break;
|
|
2874
|
+
}
|
|
2875
|
+
return lines.join("\n");
|
|
2876
|
+
}
|
|
2877
|
+
|
|
2878
|
+
//#endregion
|
|
2879
|
+
//#region src/chat/print.ts
|
|
2880
|
+
var print_exports = /* @__PURE__ */ __exportAll({
|
|
2881
|
+
readStdin: () => readStdin,
|
|
2882
|
+
resolveAgent: () => resolveAgent,
|
|
2883
|
+
runPrint: () => runPrint
|
|
2884
|
+
});
|
|
2885
|
+
/**
|
|
2886
|
+
* Non-interactive chat, à la `claude -p`. Sends a single prompt to an
|
|
2887
|
+
* agent, streams the run, and prints the assistant's reply to stdout
|
|
2888
|
+
* before exiting. No OpenTUI, no Bun requirement — this rides the same
|
|
2889
|
+
* Node-friendly REST client the TUI uses, so it runs anywhere the
|
|
2890
|
+
* management commands do (CI, pipes, scripts).
|
|
2891
|
+
*
|
|
2892
|
+
* Resolution rules kept deliberately strict because there's no human to
|
|
2893
|
+
* disambiguate: an `--agent` selector must match exactly one agent, and
|
|
2894
|
+
* when it's omitted we only auto-pick if the account has exactly one.
|
|
2895
|
+
*/
|
|
2896
|
+
async function runPrint({ appUrl, sessionToken, prompt, agentSelector, conversationId, json }) {
|
|
2897
|
+
const client = createRestClient({
|
|
2898
|
+
appUrl,
|
|
2899
|
+
sessionToken
|
|
2900
|
+
});
|
|
2901
|
+
const agent = resolveAgent(await client.listAgents({
|
|
2902
|
+
scope: "org",
|
|
2903
|
+
onPage: null
|
|
2904
|
+
}), agentSelector);
|
|
2905
|
+
const send = await client.sendMessage({
|
|
2906
|
+
agentId: agent.id,
|
|
2907
|
+
conversationId,
|
|
2908
|
+
content: prompt,
|
|
2909
|
+
attachmentIds: [],
|
|
2910
|
+
clientSurface: "cli"
|
|
2911
|
+
});
|
|
2912
|
+
let text = "";
|
|
2913
|
+
const controller = new AbortController();
|
|
2914
|
+
let streamError = null;
|
|
2915
|
+
const connectCards = [];
|
|
2916
|
+
await client.streamRun({
|
|
2917
|
+
runId: send.runId,
|
|
2918
|
+
signal: controller.signal,
|
|
2919
|
+
onEvent: (event) => {
|
|
2920
|
+
if (event.kind === "finished") {
|
|
2921
|
+
if (event.error) streamError = event.error;
|
|
2922
|
+
return;
|
|
2923
|
+
}
|
|
2924
|
+
const chunk = event.chunk;
|
|
2925
|
+
if (chunk["type"] === "text-delta") {
|
|
2926
|
+
const delta = typeof chunk["delta"] === "string" ? chunk["delta"] : typeof chunk["text"] === "string" ? chunk["text"] : "";
|
|
2927
|
+
if (delta) {
|
|
2928
|
+
text += delta;
|
|
2929
|
+
if (!json) process.stdout.write(delta);
|
|
2930
|
+
}
|
|
2931
|
+
} else if (chunk["type"] === "error") streamError = typeof chunk["errorText"] === "string" ? chunk["errorText"] : "unknown error";
|
|
2932
|
+
else {
|
|
2933
|
+
const card = connectCardFromChunk(chunk, appUrl);
|
|
2934
|
+
if (card) connectCards.push(card);
|
|
2935
|
+
}
|
|
2936
|
+
}
|
|
2937
|
+
});
|
|
2938
|
+
if (streamError) throw new Error(streamError);
|
|
2939
|
+
if (!json && text && !text.endsWith("\n")) process.stdout.write("\n");
|
|
2940
|
+
if (!json) for (const card of connectCards) process.stdout.write(`${formatConnectCard(card)}\n`);
|
|
2941
|
+
return {
|
|
2942
|
+
agentId: agent.id,
|
|
2943
|
+
agentName: agent.name,
|
|
2944
|
+
conversationId: send.conversationId,
|
|
2945
|
+
isNewConversation: send.isNewConversation,
|
|
2946
|
+
runId: send.runId,
|
|
2947
|
+
text,
|
|
2948
|
+
connectCards
|
|
2949
|
+
};
|
|
2950
|
+
}
|
|
2951
|
+
/**
|
|
2952
|
+
* Pick the target agent. With no selector, auto-pick only when the
|
|
2953
|
+
* account has exactly one agent; otherwise the user must name one (there's
|
|
2954
|
+
* no picker in non-interactive mode). A selector matches by id first, then
|
|
2955
|
+
* a unique case-insensitive slug/name; ambiguous or missing matches throw
|
|
2956
|
+
* with the candidate list so the caller knows what to pass.
|
|
2957
|
+
*/
|
|
2958
|
+
function resolveAgent(agents, selector) {
|
|
2959
|
+
if (!selector) {
|
|
2960
|
+
const [only, ...rest] = agents;
|
|
2961
|
+
if (!only) throw new Error("No agents on this account.");
|
|
2962
|
+
if (rest.length === 0) return only;
|
|
2963
|
+
throw new Error(`Multiple agents on this account — pass --agent <id|slug|name>. Candidates:\n${formatCandidates(agents)}`);
|
|
2964
|
+
}
|
|
2965
|
+
const byId = agents.find((a) => a.id === selector);
|
|
2966
|
+
if (byId) return byId;
|
|
2967
|
+
const needle = selector.toLowerCase();
|
|
2968
|
+
const matches = agents.filter((a) => a.slug && a.slug.toLowerCase() === needle || a.name.toLowerCase() === needle);
|
|
2969
|
+
const [firstMatch, ...restMatches] = matches;
|
|
2970
|
+
if (firstMatch && restMatches.length === 0) return firstMatch;
|
|
2971
|
+
if (restMatches.length > 0) throw new Error(`Multiple agents match "${selector}" — pass the id instead. Candidates:\n${formatCandidates(matches)}`);
|
|
2972
|
+
throw new Error(`No agent matches "${selector}". Candidates:\n${formatCandidates(agents)}`);
|
|
2973
|
+
}
|
|
2974
|
+
function formatCandidates(agents) {
|
|
2975
|
+
return agents.slice(0, 25).map((a) => ` ${a.id} ${a.slug ?? a.name}`).join("\n");
|
|
2976
|
+
}
|
|
2977
|
+
/** Read all of stdin as UTF-8. Used when `-p` is passed with no value. */
|
|
2978
|
+
async function readStdin() {
|
|
2979
|
+
const chunks = [];
|
|
2980
|
+
for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
2981
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
2982
|
+
}
|
|
2983
|
+
|
|
2984
|
+
//#endregion
|
|
2985
|
+
//#region src/commands/session.ts
|
|
2986
|
+
/**
|
|
2987
|
+
* Resolve the signed-in chat session or exit with a friendly hint. Shared by
|
|
2988
|
+
* every command that talks to the authenticated REST API so the
|
|
2989
|
+
* resolve-or-exit block isn't copy-pasted per command.
|
|
2990
|
+
*/
|
|
2186
2991
|
function requireSession(argv) {
|
|
2187
|
-
const session = resolveSession({ appUrl: argv["api-url"] });
|
|
2992
|
+
const session = resolveSession({ appUrl: resolveAppUrl({ appUrl: argv["api-url"] }) });
|
|
2188
2993
|
if (session.isErr()) {
|
|
2189
|
-
printError(
|
|
2994
|
+
printError(`${session.error.message} Run \`skydive auth login --web\` first, or set SKYDIVE_SESSION_TOKEN.`);
|
|
2190
2995
|
process.exit(1);
|
|
2191
2996
|
}
|
|
2192
2997
|
return session.value;
|
|
2193
2998
|
}
|
|
2999
|
+
/** Resolve the session (see {@link requireSession}) and build a REST client. */
|
|
3000
|
+
function requireRestClient(argv) {
|
|
3001
|
+
const session = requireSession(argv);
|
|
3002
|
+
return createRestClient({
|
|
3003
|
+
appUrl: session.appUrl,
|
|
3004
|
+
sessionToken: session.sessionToken
|
|
3005
|
+
});
|
|
3006
|
+
}
|
|
3007
|
+
|
|
3008
|
+
//#endregion
|
|
3009
|
+
//#region src/commands/conversations.ts
|
|
3010
|
+
/**
|
|
3011
|
+
* Flatten a UiMessage's parts into plain text for the non-JSON view. Text and
|
|
3012
|
+
* reasoning parts are concatenated; tool calls are summarized to one line so a
|
|
3013
|
+
* transcript stays readable without the rich TUI rendering. This is a
|
|
3014
|
+
* lossy-but-legible view; `--json` carries the full structured parts for a
|
|
3015
|
+
* driving agent that wants everything.
|
|
3016
|
+
*/
|
|
3017
|
+
function messageToText(message) {
|
|
3018
|
+
const chunks = [];
|
|
3019
|
+
for (const part of message.parts) if (part.type === "text" && typeof part.text === "string") chunks.push(part.text);
|
|
3020
|
+
else if (part.type === "reasoning" && typeof part.text === "string") chunks.push(part.text);
|
|
3021
|
+
else if (part.type === "dynamic-tool" && "toolName" in part) {
|
|
3022
|
+
const toolName = typeof part.toolName === "string" ? part.toolName : "tool";
|
|
3023
|
+
chunks.push(`[tool: ${toolName}]`);
|
|
3024
|
+
}
|
|
3025
|
+
return chunks.join("\n").trim();
|
|
3026
|
+
}
|
|
3027
|
+
const listCommand$1 = {
|
|
3028
|
+
command: "list",
|
|
3029
|
+
describe: "List an agent's conversations",
|
|
3030
|
+
builder: (y) => y.option("agent", {
|
|
3031
|
+
type: "string",
|
|
3032
|
+
describe: "Agent whose conversations to list, by id, slug, or name. Optional when the account has exactly one agent."
|
|
3033
|
+
}).option("limit", {
|
|
3034
|
+
type: "number",
|
|
3035
|
+
describe: "Max conversations to return"
|
|
3036
|
+
}),
|
|
3037
|
+
handler: async (argv) => {
|
|
3038
|
+
const client = requireRestClient(argv);
|
|
3039
|
+
const agent = resolveAgent(await client.listAgents({
|
|
3040
|
+
scope: "org",
|
|
3041
|
+
onPage: null
|
|
3042
|
+
}), argv.agent ?? null);
|
|
3043
|
+
const conversations = await client.listConversations({
|
|
3044
|
+
agentId: agent.id,
|
|
3045
|
+
limit: argv.limit
|
|
3046
|
+
});
|
|
3047
|
+
if (argv.json) {
|
|
3048
|
+
output(argv, conversations);
|
|
3049
|
+
return;
|
|
3050
|
+
}
|
|
3051
|
+
if (conversations.length === 0) {
|
|
3052
|
+
console.log("No conversations found.");
|
|
3053
|
+
return;
|
|
3054
|
+
}
|
|
3055
|
+
printTable([
|
|
3056
|
+
"ID",
|
|
3057
|
+
"Title",
|
|
3058
|
+
"Updated",
|
|
3059
|
+
"Preview"
|
|
3060
|
+
], conversations.map((c) => [
|
|
3061
|
+
c.id,
|
|
3062
|
+
c.title ?? "-",
|
|
3063
|
+
c.updatedAt,
|
|
3064
|
+
(c.preview ?? "").replace(/\s+/g, " ").slice(0, 48) || "-"
|
|
3065
|
+
]));
|
|
3066
|
+
}
|
|
3067
|
+
};
|
|
3068
|
+
const showCommand = {
|
|
3069
|
+
command: "show <conversation-id>",
|
|
3070
|
+
describe: "Print a conversation transcript",
|
|
3071
|
+
builder: (y) => y.positional("conversation-id", {
|
|
3072
|
+
type: "string",
|
|
3073
|
+
demandOption: true,
|
|
3074
|
+
describe: "Conversation id"
|
|
3075
|
+
}).option("recap", {
|
|
3076
|
+
type: "boolean",
|
|
3077
|
+
default: false,
|
|
3078
|
+
describe: "Print the conversation recap instead of the full transcript"
|
|
3079
|
+
}),
|
|
3080
|
+
handler: async (argv) => {
|
|
3081
|
+
const client = requireRestClient(argv);
|
|
3082
|
+
const conversationId = argv["conversation-id"];
|
|
3083
|
+
if (argv.recap) {
|
|
3084
|
+
const recap = await client.getRecap({ conversationId });
|
|
3085
|
+
if (argv.json) {
|
|
3086
|
+
output(argv, {
|
|
3087
|
+
conversationId,
|
|
3088
|
+
recap
|
|
3089
|
+
});
|
|
3090
|
+
return;
|
|
3091
|
+
}
|
|
3092
|
+
console.log(recap ?? "(no recap available)");
|
|
3093
|
+
return;
|
|
3094
|
+
}
|
|
3095
|
+
const messages = await client.listMessages({ conversationId });
|
|
3096
|
+
if (argv.json) {
|
|
3097
|
+
output(argv, messages);
|
|
3098
|
+
return;
|
|
3099
|
+
}
|
|
3100
|
+
if (messages.length === 0) {
|
|
3101
|
+
console.log("No messages in this conversation.");
|
|
3102
|
+
return;
|
|
3103
|
+
}
|
|
3104
|
+
for (const message of messages) {
|
|
3105
|
+
const text = messageToText(message);
|
|
3106
|
+
if (!text) continue;
|
|
3107
|
+
console.log(`\n[${message.role}]`);
|
|
3108
|
+
console.log(text);
|
|
3109
|
+
}
|
|
3110
|
+
}
|
|
3111
|
+
};
|
|
3112
|
+
const conversationsCommand = {
|
|
3113
|
+
command: "conversations",
|
|
3114
|
+
aliases: ["conv"],
|
|
3115
|
+
describe: "List and read agent conversations",
|
|
3116
|
+
builder: (y) => y.command(listCommand$1).command(showCommand).demandCommand(1, "Specify a subcommand: list, show"),
|
|
3117
|
+
handler: () => {}
|
|
3118
|
+
};
|
|
3119
|
+
|
|
3120
|
+
//#endregion
|
|
3121
|
+
//#region src/commands/workspace.ts
|
|
2194
3122
|
/**
|
|
2195
3123
|
* List the account's workspaces, marking the active one. Shared by the `list`
|
|
2196
3124
|
* subcommand and the bare `workspace` invocation. When `hint` is true (the bare
|
|
@@ -2251,7 +3179,7 @@ const switchCommand = {
|
|
|
2251
3179
|
printError("The workspace picker needs the Bun runtime and it could not be set up automatically. Pass a workspace slug instead, or install Bun and retry.");
|
|
2252
3180
|
process.exit(1);
|
|
2253
3181
|
}
|
|
2254
|
-
const { runWorkspacePicker } = await import("./boot-
|
|
3182
|
+
const { runWorkspacePicker } = await import("./boot-B-eA8M6t.mjs");
|
|
2255
3183
|
await runWorkspacePicker(session);
|
|
2256
3184
|
return;
|
|
2257
3185
|
}
|
|
@@ -2305,7 +3233,7 @@ function createCli(argv) {
|
|
|
2305
3233
|
type: "string",
|
|
2306
3234
|
global: true,
|
|
2307
3235
|
describe: "Override API base URL"
|
|
2308
|
-
}).command(authCommand).command(chatCommand).command(agentsCommand).command(keysCommand).command(secretsCommand).command(workspaceCommand).demandCommand(1, "Specify a command. Run --help for usage.").strict().wrap(null).version(version$1).alias("v", "version").alias("h", "help").help().fail((msg, err) => {
|
|
3236
|
+
}).command(authCommand).command(chatCommand).command(conversationsCommand).command(agentsCommand).command(keysCommand).command(secretsCommand).command(workspaceCommand).demandCommand(1, "Specify a command. Run --help for usage.").strict().wrap(null).version(version$1).alias("v", "version").alias("h", "help").help().fail((msg, err) => {
|
|
2309
3237
|
printError(err ? err instanceof Error ? err.message : String(err) : msg ?? "Unknown error");
|
|
2310
3238
|
process.exit(1);
|
|
2311
3239
|
});
|
|
@@ -2378,4 +3306,4 @@ function resolveArgv(args, tty = {
|
|
|
2378
3306
|
createCli(resolveArgv(hideBin(process.argv))).parse();
|
|
2379
3307
|
|
|
2380
3308
|
//#endregion
|
|
2381
|
-
export {
|
|
3309
|
+
export { resolveWebUrl as A, themesForMode as C, DEFAULT_API_URL as D, setActiveWorkspace as E, DEFAULT_APP_URL as O, themeVersion as S, listWorkspaces as T, noColorRequested as _, parseOauthConnectParams as a, themeMode as b, parseConnectCard as c, HttpError as d, createRestClient as f, monoTheme as g, findTheme as h, parseExternalOauthConnectParams as i, saveTheme as j, getSavedTheme as k, errorMessage as l, applyTheme as m, MASK_CHAR as n, reconcileMaskedInput as o, DEFAULT_THEME_ID as p, cardActionErrorMessage as r, resolveConnectUrl as s, resolveAgent as t, isRecord as u, theme as v, getActiveWorkspaceId as w, themeModeFromColorFgBg as x, themeForMode as y };
|