passport-bridge 0.7.0 → 0.8.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/dist/passport.js CHANGED
@@ -1,123 +1,32 @@
1
1
  #!/usr/bin/env node
2
- import { spawn } from "node:child_process";
3
- import { randomUUID } from "node:crypto";
4
- import { readFileSync, realpathSync, writeFileSync } from "node:fs";
2
+ import { realpathSync, writeFileSync } from "node:fs";
5
3
  import { fileURLToPath } from "node:url";
6
- import { ArgError, bool, parseArgs, repeated, value } from "./cliArgs.js";
7
- import { SERVER_TOO_OLD } from "./cliProtocol.js";
8
- import { completionScript } from "./completion.js";
9
- import { assertProfileName, credsPath, getProfile, readCreds, removeProfile, withProfileLock, writeProfile } from "./credentials.js";
4
+ import { bool, parseArgs, repeated, value } from "./cliArgs.js";
5
+ import { removeProfile, withProfileLock } from "./credentials.js";
10
6
  import { VERSION } from "./version.js";
11
- const DEFAULT_TIMEOUT_MS = 30_000;
7
+ import { login } from "./cliLogin.js";
8
+ import { asFailure, emitFailure, emitResult, helpResult } from "./cliOutput.js";
9
+ import { completionResult, profilesResult, useProfileResult, versionResult } from "./cliOffline.js";
10
+ import { connect, managePayload } from "./cliConnect.js";
11
+ import { firstText, hasNonText, payloadOf, refusalOf, requireSuccess } from "./cliResult.js";
12
+ import { callerFrom, endpoint, failure, firstSentence, readBoundedJson, resolveCliAuth, safeApiError, sanitize, sleep, timedFetch, timeoutMs } from "./cliSupport.js";
13
+ import { readBoundedUtf8Descriptor } from "./boundedFile.js";
14
+ import { runCliSession, writeCliSessionFailure } from "./cliSession.js";
15
+ export { refusalOf } from "./cliResult.js";
16
+ export { callerFrom, sanitize } from "./cliSupport.js";
12
17
  const APPROVAL_RETRY_MS = 3_000;
13
- class CliFailure extends Error {
14
- exitCode;
15
- cause;
16
- details;
17
- constructor(message, exitCode, cause, details = {}) {
18
- super(message);
19
- this.exitCode = exitCode;
20
- this.cause = cause;
21
- this.details = details;
22
- }
23
- }
24
- function failure(message, exitCode, cause, details = {}) {
25
- throw new CliFailure(message, exitCode, cause, details);
26
- }
27
- function timeoutMs(args) {
28
- return Math.ceil(Number(value(args, "timeout") ?? DEFAULT_TIMEOUT_MS / 1000) * 1000);
29
- }
30
- function profileName(raw) {
31
- try {
32
- assertProfileName(raw);
33
- return raw;
34
- }
35
- catch (error) {
36
- return failure(error instanceof Error ? error.message : "Invalid profile name.", 6, "usage");
37
- }
38
- }
39
- function endpoint(raw) {
40
- try {
41
- const parsed = new URL(raw);
42
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
43
- throw new Error();
44
- if (parsed.username || parsed.password)
45
- return failure("Passport endpoint URLs cannot contain a username or password.", 6, "usage");
46
- const host = parsed.hostname.toLowerCase();
47
- const loopback = host === "localhost" ||
48
- host === "[::1]" ||
49
- host === "::1" ||
50
- /^127(?:\.\d{1,3}){3}$/.test(host);
51
- if (parsed.protocol === "http:" && !loopback) {
52
- return failure("Passport CLI requires HTTPS for remote servers. Configure HTTPS for your self-hosted Passport deployment; plain HTTP is allowed only on localhost, 127.0.0.0/8, or ::1.", 6, "usage");
53
- }
54
- return parsed.toString().replace(/\/$/, "");
55
- }
56
- catch (error) {
57
- if (error instanceof CliFailure)
58
- throw error;
59
- return failure("Passport endpoint must be an http or https URL.", 6, "usage");
60
- }
61
- }
62
- function cloudOrigin(raw) {
63
- const normalized = endpoint(raw);
64
- const parsed = new URL(normalized);
65
- if (parsed.pathname !== "/" || parsed.search || parsed.hash)
66
- return failure("--cloud must be a Passport origin without a path, query, or fragment.", 6, "usage");
67
- return parsed.origin;
68
- }
69
- function resolveAuth(args, env) {
70
- const explicitProfile = value(args, "profile");
71
- const agentKey = env.PASSPORT_AGENT_KEY ?? "";
72
- const agentEndpoint = env.PASSPORT_ENDPOINT ?? "";
73
- if (agentKey || agentEndpoint) {
74
- if (!agentKey || !agentEndpoint) {
75
- return failure("PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT must be set together.", 2, "auth", { hint: "Set both variables, or run: passport login" });
76
- }
77
- if (explicitProfile !== undefined)
78
- return failure("--profile cannot be used with PASSPORT_AGENT_KEY.", 6, "usage");
79
- return { kind: "agent-key", endpoint: endpoint(agentEndpoint), agentKey };
80
- }
81
- const creds = readCreds();
82
- const names = Object.keys(creds).sort();
83
- const fallbackProfile = env.PASSPORT_PROFILE || (names.length === 1 ? names[0] : "");
84
- const profile = explicitProfile !== undefined ? profileName(explicitProfile) : fallbackProfile ? profileName(fallbackProfile) : "";
85
- if (!profile) {
86
- const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
87
- return failure(`No Passport profile selected.${suffix}`, 2, "auth", { hint: "Run: passport login" });
88
- }
89
- const saved = creds[profile];
90
- if (!saved) {
91
- const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
92
- return failure(`Passport profile "${profile}" does not exist.${suffix}`, 2, "auth", { hint: "Run: passport login" });
93
- }
94
- return { kind: "profile", endpoint: endpoint(saved.endpoint), profile, refreshToken: saved.refreshToken };
95
- }
96
- export function callerFrom(args, env) {
97
- const explicit = value(args, "caller");
98
- if (explicit !== undefined) {
99
- const normalized = explicit.trim().toLowerCase();
100
- if (!/^[a-z0-9-]{1,24}$/.test(normalized))
101
- return failure("--caller must contain 1-24 lowercase letters, numbers, or hyphens.", 6, "usage");
102
- return normalized;
103
- }
104
- const keys = Object.keys(env);
105
- if (Object.hasOwn(env, "CLAUDECODE") || keys.some((key) => key.startsWith("CLAUDE_CODE")))
106
- return "claude-code";
107
- if (Object.hasOwn(env, "CODEX_SANDBOX") || keys.some((key) => key.startsWith("CODEX_")))
108
- return "codex";
109
- if (Object.hasOwn(env, "OPENCODE") || keys.some((key) => key.startsWith("OPENCODE_")))
110
- return "opencode";
111
- if (Object.hasOwn(env, "CURSOR_TRACE_ID") || keys.some((key) => key.startsWith("CURSOR_")))
112
- return "cursor";
113
- if (Object.hasOwn(env, "GEMINI_CLI"))
114
- return "gemini";
115
- return undefined;
116
- }
18
+ const CLI_ARGUMENT_STDIN_MAX_BYTES = 1024 * 1024;
117
19
  async function withGateway(args, runtime, fn) {
118
- const auth = resolveAuth(args, runtime.env);
20
+ if (runtime.sharedGateway)
21
+ return fn(runtime.sharedGateway.gateway, runtime.sharedGateway.auth);
22
+ const auth = resolveCliAuth(args, runtime.env);
119
23
  const { CliGateway } = await import("./cliClient.js");
120
- const gateway = await CliGateway.connect({ auth, caller: callerFrom(args, runtime.env), timeoutMs: timeoutMs(args), signal: runtime.signal });
24
+ const gateway = await CliGateway.connect({
25
+ auth,
26
+ caller: callerFrom(args, runtime.env),
27
+ timeoutMs: timeoutMs(args),
28
+ signal: runtime.signal
29
+ });
121
30
  try {
122
31
  await gateway.assertCliProtocol();
123
32
  return await fn(gateway, auth);
@@ -126,160 +35,11 @@ async function withGateway(args, runtime, fn) {
126
35
  await gateway.close();
127
36
  }
128
37
  }
129
- function firstText(result) {
130
- return result.content.filter((part) => part.type === "text").map((part) => part.text).join("");
131
- }
132
- function hasNonText(result) {
133
- return result.content.some((part) => part.type !== "text");
134
- }
135
- function payloadOf(result, label) {
136
- const text = firstText(result);
137
- if (text) {
138
- try {
139
- const parsed = JSON.parse(text);
140
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
141
- return parsed;
142
- }
143
- catch {
144
- /* structured content may carry a future server payload */
145
- }
146
- }
147
- if (result.structuredContent && !result.structuredContent.cause)
148
- return result.structuredContent;
149
- return failure(`Passport returned an invalid ${label} payload.`, 1, "invalid_server_response");
150
- }
151
- export function refusalOf(result) {
152
- const structured = result.structuredContent;
153
- // Upstream tools own arbitrary structuredContent and may legitimately use a
154
- // business field named `cause`. Only Passport-stamped refusals control CLI
155
- // exit/retry behavior; ordinary upstream errors remain tool errors.
156
- if (result._meta?.["passport/refusal"] !== true) {
157
- return result.isError ? new CliFailure(firstText(result) || "The tool returned an error.", 1, "tool_error") : undefined;
158
- }
159
- const cause = typeof structured?.cause === "string" ? structured.cause : "";
160
- // approval_pending deliberately remains isError:false for compatibility with
161
- // interactive MCP agents. A CLI refusal is identified by its trusted
162
- // structured cause, never by isError or human prose.
163
- if (!cause)
164
- return new CliFailure("Passport returned an invalid refusal payload.", 1, "invalid_server_response");
165
- const recognized = new Set(["needs_connect", "approval_pending", "approval_denied", "blocked", "unknown_tool"]);
166
- if (!recognized.has(cause)) {
167
- // Successful upstream tools may legitimately return a business field named
168
- // `cause`; only Passport's reserved refusal values change CLI control flow.
169
- return result.isError ? new CliFailure(firstText(result) || "The tool returned an error.", 1, "tool_error") : undefined;
170
- }
171
- const app = typeof structured?.app === "string" ? structured.app : undefined;
172
- const approvalId = typeof structured?.approvalId === "string" ? structured.approvalId : undefined;
173
- let message = firstText(result) || "Passport refused the call.";
174
- if (cause === "needs_connect") {
175
- return new CliFailure(message, 3, cause, { app, hint: `Run: passport connect ${app ?? "<app>"}` });
176
- }
177
- if (cause === "approval_pending") {
178
- if (approvalId && !message.includes(approvalId))
179
- message = `${message}\nApproval ID: ${approvalId}`;
180
- return new CliFailure(message, 4, cause, { app, approvalId });
181
- }
182
- if (cause === "approval_denied" || cause === "blocked")
183
- return new CliFailure(message, 5, cause, { app, approvalId });
184
- if (cause === "unknown_tool")
185
- return new CliFailure(message, 6, cause, { app });
186
- return new CliFailure(`Passport returned an unsupported refusal cause: ${cause}.`, 1, "invalid_server_response", { app, approvalId });
187
- }
188
- function requireSuccess(result) {
189
- const refusal = refusalOf(result);
190
- if (refusal)
191
- throw refusal;
192
- return result;
193
- }
194
- async function login(args, runtime) {
195
- if (runtime.env.PASSPORT_AGENT_KEY || runtime.env.PASSPORT_ENDPOINT) {
196
- return failure("Unset PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT before interactive login.", 6, "usage");
197
- }
198
- const explicitProfile = value(args, "profile");
199
- const requestedProfile = explicitProfile !== undefined ? profileName(explicitProfile) : runtime.env.PASSPORT_PROFILE ? profileName(runtime.env.PASSPORT_PROFILE) : "";
200
- const requestedExisting = requestedProfile ? getProfile(requestedProfile) : undefined;
201
- const cloudRaw = value(args, "cloud") || runtime.env.PASSPORT_CLOUD || (requestedExisting ? new URL(endpoint(requestedExisting.endpoint)).origin : "");
202
- if (!cloudRaw)
203
- return failure("--cloud <origin> is required for the first login.", 6, "usage");
204
- const cloud = cloudOrigin(cloudRaw);
205
- const workspaceOption = value(args, "workspace");
206
- const workspace = workspaceOption?.trim() ?? "";
207
- if (workspaceOption !== undefined && !/^[A-Za-z0-9_-]{1,80}$/.test(workspace))
208
- return failure("--workspace must be a valid workspace id.", 6, "usage");
209
- const clientOption = value(args, "client");
210
- const client = clientOption === undefined ? "cli" : clientOption.trim();
211
- if (!/^[A-Za-z0-9._-]{1,40}$/.test(client))
212
- return failure("--client must be a valid client id (1-40 characters).", 6, "usage");
213
- const ws = workspace ? `?ws=${encodeURIComponent(workspace)}` : "";
214
- const start = await timedFetch(`${cloud}/api/auth/device/start${ws}`, { method: "POST" }, timeoutMs(args), runtime.signal);
215
- if (start.status === 404) {
216
- return failure("Passport could not find that workspace. Ask your admin for its workspace id.", 2, "auth");
217
- }
218
- if (!start.ok)
219
- return failure(`Could not start sign-in (${start.status}).`, 1, "server");
220
- const started = (await start.json());
221
- if (typeof started.code !== "string" || typeof started.userCode !== "string" || typeof started.verifyUrl !== "string") {
222
- return failure("Passport returned an invalid device sign-in response.", 1, "invalid_server_response");
223
- }
224
- runtime.stderr.write(`Sign in to Passport\nOpen: ${started.verifyUrl}\nConfirm code: ${started.userCode}\nWaiting for approval...\n`);
225
- if (!runtime.env.PASSPORT_NO_OPEN)
226
- openUrl(started.verifyUrl);
227
- const deadlineAt = Date.now() + 10 * 60 * 1000;
228
- let sessionToken = "";
229
- while (Date.now() < deadlineAt) {
230
- await sleep(1_500, runtime.signal);
231
- const poll = await timedFetch(`${cloud}/api/auth/device/poll`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code: started.code }) }, timeoutMs(args), runtime.signal);
232
- if (!poll.ok)
233
- return failure(`Could not check sign-in (${poll.status}).`, 1, "server");
234
- const result = (await poll.json());
235
- if (result.status === "approved" && typeof result.token === "string") {
236
- sessionToken = result.token;
237
- break;
238
- }
239
- if (result.status === "denied" || result.status === "expired")
240
- return failure(`Sign-in ${result.status}.`, 2, "auth");
241
- }
242
- if (!sessionToken)
243
- return failure("Timed out waiting for sign-in approval.", 2, "auth");
244
- const tokenWorkspace = workspace || (await import("./bridge.js")).workspaceOfToken(sessionToken) || "workspace";
245
- const profile = profileName(requestedProfile || `cli@${tokenWorkspace}`);
246
- const storedInstanceId = getProfile(profile)?.instanceId;
247
- const instanceId = storedInstanceId && /^[A-Za-z0-9._:-]{1,128}$/.test(storedInstanceId) ? storedInstanceId : randomUUID();
248
- const credential = await timedFetch(`${cloud}/api/my/bridge-credential`, {
249
- method: "POST",
250
- headers: { "content-type": "application/json", authorization: `Bearer ${sessionToken}` },
251
- body: JSON.stringify({
252
- client,
253
- target: "workspace",
254
- surface: "cli",
255
- instanceId,
256
- instanceLabel: profile
257
- })
258
- }, timeoutMs(args), runtime.signal);
259
- if (!credential.ok) {
260
- const message = await safeApiError(credential, "Could not create a CLI credential.");
261
- return failure(message, credential.status === 401 || credential.status === 403 ? 2 : 1, "auth");
262
- }
263
- const body = (await credential.json());
264
- if (typeof body.refreshToken !== "string" || typeof body.endpoint !== "string") {
265
- return failure("Passport returned an invalid credential response.", 1, "invalid_server_response");
266
- }
267
- const credentialEndpoint = endpoint(body.endpoint);
268
- await withProfileLock(profile, async () => writeProfile(profile, {
269
- refreshToken: body.refreshToken,
270
- endpoint: credentialEndpoint,
271
- instanceId
272
- }));
273
- return {
274
- json: { profile, endpoint: credentialEndpoint, client, surface: "cli" },
275
- human: `Signed in as profile "${profile}".\nCredential saved to ${credsPath()}.`
276
- };
277
- }
278
38
  async function logout(args, runtime) {
279
39
  if (runtime.env.PASSPORT_AGENT_KEY || runtime.env.PASSPORT_ENDPOINT) {
280
40
  return failure("Agent-key authentication is not stored locally and cannot be logged out. Unset the environment variables instead.", 6, "usage");
281
41
  }
282
- const auth = resolveAuth(args, runtime.env);
42
+ const auth = resolveCliAuth(args, runtime.env);
283
43
  if (auth.kind !== "profile")
284
44
  return failure("No local profile is active.", 2, "auth");
285
45
  const existing = await withProfileLock(auth.profile, async () => removeProfile(auth.profile));
@@ -287,7 +47,11 @@ async function logout(args, runtime) {
287
47
  let warning = "";
288
48
  if (existing) {
289
49
  try {
290
- const response = await timedFetch(`${new URL(existing.endpoint).origin}/api/token/revoke`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ refreshToken: existing.refreshToken }) }, timeoutMs(args), runtime.signal);
50
+ const response = await timedFetch(`${new URL(existing.endpoint).origin}/api/token/revoke`, {
51
+ method: "POST",
52
+ headers: { "content-type": "application/json" },
53
+ body: JSON.stringify({ refreshToken: existing.refreshToken })
54
+ }, timeoutMs(args), runtime.signal);
291
55
  revoked = response.ok;
292
56
  if (!response.ok)
293
57
  warning = `Warning: the server could not revoke the credential (${response.status}); the local profile was removed.`;
@@ -300,21 +64,6 @@ async function logout(args, runtime) {
300
64
  runtime.stderr.write(`${warning}\n`);
301
65
  return { json: { profile: auth.profile, removed: true, revoked }, human: `Signed out profile "${auth.profile}".` };
302
66
  }
303
- function managePayload(result) {
304
- requireSuccess(result);
305
- const payload = payloadOf(result, "connection");
306
- if (!payload.workspace ||
307
- typeof payload.workspace !== "object" ||
308
- !payload.member ||
309
- typeof payload.member !== "object" ||
310
- typeof payload.client !== "string" ||
311
- payload.surface !== "cli" ||
312
- typeof payload.auth !== "string" ||
313
- !Array.isArray(payload.connections)) {
314
- return failure(SERVER_TOO_OLD, 1, "server_too_old");
315
- }
316
- return payload;
317
- }
318
67
  async function status(args, runtime) {
319
68
  return withGateway(args, runtime, async (gateway, auth) => {
320
69
  const managed = managePayload(await gateway.callTool("passport_manage_connections", { includeLinks: false }));
@@ -322,8 +71,35 @@ async function status(args, runtime) {
322
71
  app: String(row.app ?? ""),
323
72
  name: String(row.name ?? row.app ?? ""),
324
73
  status: String(row.status ?? "unknown"),
325
- toolCount: Number(row.toolCount ?? 0)
74
+ toolCount: Number(row.toolCount ?? 0),
75
+ ...(row.status === "needs_your_signin"
76
+ ? auth.kind === "profile"
77
+ ? {
78
+ remediation: {
79
+ cause: "needs_connect",
80
+ next: {
81
+ argv: ["passport", "connect", String(row.app ?? ""), "--wait", "120"],
82
+ description: "Complete member sign-in, then retry the tool call."
83
+ }
84
+ }
85
+ }
86
+ : {
87
+ remediation: {
88
+ cause: "member_profile_required",
89
+ action: "use_member_profile_or_managed_connection",
90
+ description: "Use an interactive member profile, delegate the agent to a member, or configure a company-managed connection."
91
+ }
92
+ }
93
+ : {})
326
94
  }));
95
+ const connectionActions = auth.kind === "profile"
96
+ ? mcps
97
+ .filter((mcp) => mcp.status === "needs_your_signin" && /^[A-Za-z0-9._-]+$/.test(mcp.app))
98
+ .map((mcp) => ({
99
+ argv: ["passport", "connect", mcp.app, "--wait", "120"],
100
+ description: `Connect ${mcp.name}.`
101
+ }))
102
+ : [];
327
103
  const data = {
328
104
  workspace: { id: String(managed.workspace.id), name: String(managed.workspace.name) },
329
105
  member: { id: String(managed.member.id), email: String(managed.member.email) },
@@ -331,7 +107,8 @@ async function status(args, runtime) {
331
107
  auth: managed.auth,
332
108
  ...(auth.kind === "profile" ? { profile: auth.profile } : {}),
333
109
  client: managed.client,
334
- mcps
110
+ mcps,
111
+ ...(connectionActions.length ? { next: connectionActions } : {})
335
112
  };
336
113
  const lines = [
337
114
  `${data.workspace.name} (${data.workspace.id})`,
@@ -339,7 +116,15 @@ async function status(args, runtime) {
339
116
  `Endpoint: ${data.endpoint}`,
340
117
  ...(auth.kind === "profile" ? [`Profile: ${auth.profile}`] : []),
341
118
  `Client: ${managed.client} · Surface: ${managed.surface} · Auth: ${managed.auth}`,
342
- ...(mcps.length ? mcps.map((mcp) => `${mcp.name} (${mcp.app}): ${mcp.status} · ${mcp.toolCount} permitted tool${mcp.toolCount === 1 ? "" : "s"}`) : ["No visible MCPs."])
119
+ ...(mcps.length
120
+ ? mcps.map((mcp) => `${mcp.name} (${mcp.app}): ${mcp.status} · ${mcp.toolCount} permitted tool${mcp.toolCount === 1 ? "" : "s"}${mcp.status === "needs_your_signin"
121
+ ? auth.kind === "agent-key"
122
+ ? " · Requires an interactive member profile, delegation, or a company-managed connection"
123
+ : /^[A-Za-z0-9._-]+$/.test(mcp.app)
124
+ ? ` · Run: passport connect ${mcp.app} --wait 120`
125
+ : " · Run passport status --json for the safe connect argv"
126
+ : ""}`)
127
+ : ["No visible MCPs."])
343
128
  ];
344
129
  return { json: data, human: lines.join("\n") };
345
130
  });
@@ -377,7 +162,7 @@ async function discover(args, runtime) {
377
162
  const message = await safeApiError(response, "Could not submit the fleet discovery scan.");
378
163
  return failure(message, response.status === 401 || response.status === 403 ? 2 : 1, "server");
379
164
  }
380
- const report = (await response.json());
165
+ const report = await readBoundedJson(response);
381
166
  const direct = Number(report.stats?.directConnections ?? 0);
382
167
  const review = Number(report.stats?.needsReview ?? 0);
383
168
  const enforcement = String(report.policy?.enforcement ?? "observe");
@@ -402,7 +187,10 @@ async function search(args, runtime) {
402
187
  if (value(args, "app") !== undefined && !value(args, "app").trim())
403
188
  return failure("--app cannot be empty.", 6, "usage");
404
189
  return withGateway(args, runtime, async (gateway) => {
405
- const result = requireSuccess(await gateway.callTool("passport_search_tools", { ...(query ? { query } : {}), ...(value(args, "app") ? { app: value(args, "app") } : {}) }));
190
+ const result = requireSuccess(await gateway.callTool("passport_search_tools", {
191
+ ...(query ? { query } : {}),
192
+ ...(value(args, "app") ? { app: value(args, "app") } : {})
193
+ }));
406
194
  const payload = payloadOf(result, "search");
407
195
  const lines = [];
408
196
  if (query) {
@@ -436,9 +224,20 @@ async function describe(args, runtime) {
436
224
  const results = Array.isArray(payload.results) ? payload.results : [];
437
225
  const exact = results.find((hit) => hit.tool === name);
438
226
  if (!exact) {
439
- const suggestions = results.slice(0, 5).map((hit) => String(hit.tool ?? "")).filter(Boolean);
227
+ const suggestions = results
228
+ .slice(0, 5)
229
+ .map((hit) => String(hit.tool ?? ""))
230
+ .filter(Boolean);
440
231
  const suffix = suggestions.length ? ` Near matches: ${suggestions.join(", ")}.` : "";
441
- return failure(`Unknown tool "${name}".${suffix}`, 6, "unknown_tool");
232
+ return failure(`Unknown tool "${name}".${suffix}`, 6, "unknown_tool", {
233
+ hint: `Run: passport search "${name}"`,
234
+ next: [
235
+ {
236
+ argv: ["passport", "search", name],
237
+ description: "Search permitted tool names."
238
+ }
239
+ ]
240
+ });
442
241
  }
443
242
  const schema = exact.parameters ?? {};
444
243
  const human = [
@@ -455,18 +254,53 @@ async function run(args, runtime) {
455
254
  const tool = args.positionals[0];
456
255
  const toolArgs = runArguments(args);
457
256
  const waitSeconds = value(args, "wait") ? Number(value(args, "wait")) : 0;
458
- return withGateway(args, runtime, async (gateway) => {
257
+ return withGateway(args, runtime, async (gateway, auth) => {
459
258
  const deadlineAt = waitSeconds ? Date.now() + waitSeconds * 1000 : 0;
259
+ let waitingForApproval = false;
460
260
  let result = await gateway.callTool("passport_call", { tool, args: toolArgs });
461
261
  for (;;) {
462
262
  const refusal = refusalOf(result);
463
- if (!refusal)
263
+ if (!refusal) {
264
+ if (waitingForApproval && !bool(args, "quiet"))
265
+ runtime.stderr.write("Approval received. Continuing...\n");
464
266
  break;
267
+ }
268
+ if (refusal.cause === "needs_connect" && auth.kind === "agent-key") {
269
+ return failure("This agent key cannot create a person's sign-in link.", 3, "member_profile_required", {
270
+ app: refusal.details.app,
271
+ hint: "Use an interactive member profile, delegate the agent to a member, or configure a company-managed connection.",
272
+ remediation: {
273
+ action: "use_member_profile_or_managed_connection",
274
+ description: "Use an interactive member profile, delegate the agent to a member, or configure a company-managed connection."
275
+ }
276
+ });
277
+ }
278
+ if (refusal.cause === "approval_pending") {
279
+ refusal.details.retry = {
280
+ command: "run",
281
+ tool,
282
+ waitSeconds: waitSeconds || 120,
283
+ arguments: Object.keys(toolArgs).length ? "reuse_original" : "none"
284
+ };
285
+ if (!Object.keys(toolArgs).length) {
286
+ refusal.details.next = [
287
+ {
288
+ argv: ["passport", "run", tool, "--wait", String(waitSeconds || 120)],
289
+ description: "Retry this tool and wait for approval."
290
+ }
291
+ ];
292
+ }
293
+ }
465
294
  if (refusal.cause !== "approval_pending" || !waitSeconds)
466
295
  throw refusal;
467
296
  const remaining = deadlineAt - Date.now();
468
297
  if (remaining <= 0)
469
298
  throw refusal;
299
+ if (!waitingForApproval && !bool(args, "quiet")) {
300
+ const approval = refusal.details.approvalId ? ` (${refusal.details.approvalId})` : "";
301
+ runtime.stderr.write(`Approval pending${approval}. Waiting up to ${waitSeconds} seconds...\n`);
302
+ waitingForApproval = true;
303
+ }
470
304
  await sleep(Math.min(APPROVAL_RETRY_MS, remaining), runtime.signal);
471
305
  if (Date.now() >= deadlineAt)
472
306
  throw refusal;
@@ -493,7 +327,7 @@ function runArguments(args) {
493
327
  if (positional !== undefined)
494
328
  return jsonObject(positional, "tool arguments");
495
329
  if (fromStdin !== undefined)
496
- return jsonObject(readFileSync(0, "utf8"), "stdin");
330
+ return jsonObject(readBoundedUtf8Descriptor(0, CLI_ARGUMENT_STDIN_MAX_BYTES), "stdin");
497
331
  const out = Object.create(null);
498
332
  const seen = new Set();
499
333
  for (const raw of sets)
@@ -535,101 +369,6 @@ function jsonObject(raw, label) {
535
369
  return failure(`${label} must be a valid JSON object.`, 6, "usage");
536
370
  }
537
371
  }
538
- async function connect(args, runtime) {
539
- const alias = value(args, "alias");
540
- if (alias !== undefined && !/^[A-Za-z0-9 -]{1,32}$/.test(alias.trim()))
541
- return failure("--alias must contain 1-32 letters, numbers, spaces, or hyphens.", 6, "usage");
542
- const requested = args.positionals;
543
- return withGateway(args, runtime, async (gateway) => {
544
- let managed = managePayload(await gateway.callTool("passport_manage_connections", {
545
- ...(alias !== undefined ? { alias: alias.trim() } : {}),
546
- ...(requested.length ? { apps: requested } : {})
547
- }));
548
- const rows = requested.length ? requested.map((app) => findConnection(managed.connections, app)) : managed.connections;
549
- const human = connectionLines(managed, rows, requested.length > 0);
550
- const urls = connectionUrls(managed, rows, requested.length > 0);
551
- if (bool(args, "open")) {
552
- if (urls.length > 1)
553
- return failure("--open requires a single connect URL. Name one MCP, or use the aggregate connect flow.", 6, "usage");
554
- if (urls[0])
555
- openUrl(urls[0]);
556
- }
557
- const waitSeconds = value(args, "wait") ? Number(value(args, "wait")) : 0;
558
- if (!waitSeconds)
559
- return { json: managed, human: human.join("\n") };
560
- const targets = requested.length
561
- ? rows.filter((row) => row.status === "needs_your_signin").map((row) => String(row.app))
562
- : rows.filter((row) => row.status === "needs_your_signin").map((row) => String(row.app));
563
- if (!targets.length)
564
- return { json: managed, human: human.join("\n") };
565
- if (!bool(args, "json") && (!bool(args, "quiet") || !bool(args, "open")))
566
- runtime.stdout.write(`${human.join("\n")}\n`);
567
- const waitResult = await waitForConnections(gateway, targets, waitSeconds, runtime.signal);
568
- if (!waitResult.connected) {
569
- const note = typeof waitResult.note === "string" ? waitResult.note : "Timed out waiting for the MCP connection.";
570
- return failure(note, 1, "connection_timeout", { app: targets.length === 1 ? targets[0] : undefined });
571
- }
572
- managed = managePayload(await gateway.callTool("passport_manage_connections", { includeLinks: false }));
573
- return { json: managed, human: typeof waitResult.note === "string" ? waitResult.note : "Connection ready." };
574
- });
575
- }
576
- function findConnection(rows, requested) {
577
- const needle = requested.trim().toLowerCase();
578
- const row = rows.find((entry) => String(entry.app ?? "").toLowerCase() === needle || String(entry.name ?? "").toLowerCase() === needle);
579
- if (!row)
580
- return failure(`Unknown MCP "${requested}". Run passport status to see visible MCPs.`, 6, "unknown_app", { app: requested });
581
- return row;
582
- }
583
- function connectionUrls(managed, rows, explicitlyNamed) {
584
- const needSignin = rows.filter((row) => row.status === "needs_your_signin");
585
- if (!explicitlyNamed && needSignin.length >= 2 && managed.connectAllUrl)
586
- return [managed.connectAllUrl];
587
- return needSignin.map((row) => row.connectUrl).filter((url) => typeof url === "string");
588
- }
589
- function connectionLines(managed, rows, explicitlyNamed) {
590
- const urls = connectionUrls(managed, rows, explicitlyNamed);
591
- if (!explicitlyNamed && urls.length === 1 && rows.filter((row) => row.status === "needs_your_signin").length >= 2) {
592
- return [`Connect your MCPs: ${urls[0]}`];
593
- }
594
- const lines = [];
595
- for (const row of rows) {
596
- const name = String(row.name ?? row.app ?? "MCP");
597
- if (row.status === "needs_your_signin" && typeof row.connectUrl === "string")
598
- lines.push(`${name}: ${row.connectUrl}`);
599
- else if (row.status === "connected" || row.status === "org_managed")
600
- lines.push(`${name}: already connected`);
601
- else if (typeof row.action === "string")
602
- lines.push(`${name}: ${row.action}`);
603
- else
604
- lines.push(`${name}: ${String(row.status ?? "unknown")}`);
605
- }
606
- if (!lines.length || (!explicitlyNamed && !rows.some((row) => row.status === "needs_your_signin")))
607
- lines.push(managed.note || "Nothing needs connecting.");
608
- return lines;
609
- }
610
- async function waitForConnections(gateway, apps, seconds, signal) {
611
- const deadlineAt = Date.now() + seconds * 1000;
612
- let latest = { connected: false };
613
- do {
614
- const remaining = Math.max(1, Math.ceil((deadlineAt - Date.now()) / 1000));
615
- const chunk = Math.min(120, remaining);
616
- const result = requireSuccess(await gateway.callTool("passport_wait_for_connection", apps.length === 1 ? { app: apps[0], timeoutSeconds: chunk } : { apps, timeoutSeconds: chunk }, (chunk + 5) * 1000));
617
- const text = firstText(result);
618
- try {
619
- latest = JSON.parse(text);
620
- }
621
- catch {
622
- return failure("Passport returned an invalid connection wait payload.", 1, "invalid_server_response");
623
- }
624
- if (latest.connected === true || latest.status === "connected")
625
- return { ...latest, connected: true };
626
- if (latest.status === "needs_setup")
627
- return { ...latest, connected: false };
628
- if (Date.now() < deadlineAt)
629
- await sleep(Math.min(250, deadlineAt - Date.now()), signal);
630
- } while (Date.now() < deadlineAt);
631
- return { ...latest, connected: false };
632
- }
633
372
  async function resources(args, runtime) {
634
373
  if (value(args, "out") !== undefined && !value(args, "out"))
635
374
  return failure("--out cannot be empty.", 6, "usage");
@@ -638,7 +377,9 @@ async function resources(args, runtime) {
638
377
  if (!uri) {
639
378
  const listed = await gateway.listResources();
640
379
  const human = listed.resources.length
641
- ? listed.resources.map((resource) => `${resource.uri} · ${resource.name}${resource.mimeType ? ` · ${resource.mimeType}` : ""}`).join("\n")
380
+ ? listed.resources
381
+ .map((resource) => `${resource.uri} · ${resource.name}${resource.mimeType ? ` · ${resource.mimeType}` : ""}`)
382
+ .join("\n")
642
383
  : "No resources are available.";
643
384
  return { json: listed, human };
644
385
  }
@@ -654,7 +395,12 @@ async function resources(args, runtime) {
654
395
  if (read.contents.some((content) => "blob" in content)) {
655
396
  return failure("The resource is binary. Use --out <file> or --json.", 1, "non_text_content");
656
397
  }
657
- return { json: read, human: read.contents.map((content) => ("text" in content ? content.text : "")).join(""), essential: true, raw: true };
398
+ return {
399
+ json: read,
400
+ human: read.contents.map((content) => ("text" in content ? content.text : "")).join(""),
401
+ essential: true,
402
+ raw: true
403
+ };
658
404
  });
659
405
  }
660
406
  function resourceBytes(contents) {
@@ -676,7 +422,9 @@ async function prompts(args, runtime) {
676
422
  const human = listed.prompts.length
677
423
  ? listed.prompts
678
424
  .map((prompt) => {
679
- const names = prompt.arguments?.map((argument) => `${argument.name}${argument.required ? "*" : ""}`).join(", ");
425
+ const names = prompt.arguments
426
+ ?.map((argument) => `${argument.name}${argument.required ? "*" : ""}`)
427
+ .join(", ");
680
428
  return `${prompt.name}${names ? ` (${names})` : ""}${prompt.description ? ` · ${prompt.description}` : ""}`;
681
429
  })
682
430
  .join("\n")
@@ -713,7 +461,11 @@ function assignPrompt(raw, out, seen) {
713
461
  return failure("--set expects key=value.", 6, "usage");
714
462
  const key = raw.slice(0, equals).trim();
715
463
  if (!key || key === "__proto__" || key === "prototype" || key === "constructor" || seen.has(key)) {
716
- return failure(!key ? "Prompt argument key cannot be empty." : seen.has(key) ? `Prompt argument "${key}" was provided more than once.` : `Invalid prompt argument key: ${key}.`, 6, "usage");
464
+ return failure(!key
465
+ ? "Prompt argument key cannot be empty."
466
+ : seen.has(key)
467
+ ? `Prompt argument "${key}" was provided more than once.`
468
+ : `Invalid prompt argument key: ${key}.`, 6, "usage");
717
469
  }
718
470
  seen.add(key);
719
471
  out[key] = raw.slice(equals + 1);
@@ -727,51 +479,16 @@ function promptBytes(messages) {
727
479
  }
728
480
  return failure("A multi-part binary prompt cannot be written to one file. Use --json.", 6, "usage");
729
481
  }
730
- function help(args) {
731
- const verb = args.positionals[0];
732
- const text = helpText(verb);
733
- return { json: { command: verb ?? null, help: text }, human: text, essential: true };
734
- }
735
- function completion(args) {
736
- const shell = args.positionals[0];
737
- if (shell !== "bash" && shell !== "zsh" && shell !== "fish") {
738
- return failure("completion requires bash, zsh, or fish.", 6, "usage");
739
- }
740
- const script = completionScript(shell);
741
- return { json: { shell, script }, human: script, essential: true, raw: true };
742
- }
743
- function version(args, env) {
744
- let profile;
745
- let resolvedEndpoint;
746
- if (env.PASSPORT_AGENT_KEY && env.PASSPORT_ENDPOINT && value(args, "profile") !== undefined) {
747
- return failure("--profile cannot be used with PASSPORT_AGENT_KEY.", 6, "usage");
748
- }
749
- if (env.PASSPORT_AGENT_KEY && env.PASSPORT_ENDPOINT) {
750
- resolvedEndpoint = endpoint(env.PASSPORT_ENDPOINT);
751
- }
752
- else {
753
- const creds = readCreds();
754
- const names = Object.keys(creds);
755
- const explicitProfile = value(args, "profile");
756
- const candidate = explicitProfile !== undefined ? profileName(explicitProfile) : env.PASSPORT_PROFILE ? profileName(env.PASSPORT_PROFILE) : names.length === 1 ? profileName(names[0]) : "";
757
- if (candidate && creds[candidate]) {
758
- profile = candidate;
759
- resolvedEndpoint = endpoint(creds[candidate].endpoint);
760
- }
761
- }
762
- const data = { version: VERSION, ...(resolvedEndpoint ? { endpoint: resolvedEndpoint } : {}), ...(profile ? { profile } : {}) };
763
- return {
764
- json: data,
765
- human: [`passport ${VERSION}`, ...(resolvedEndpoint ? [`Endpoint: ${resolvedEndpoint}`] : []), ...(profile ? [`Profile: ${profile}`] : [])].join("\n"),
766
- essential: true
767
- };
768
- }
769
482
  async function dispatch(args, runtime) {
770
483
  switch (args.command) {
771
484
  case "login":
772
485
  return login(args, runtime);
773
486
  case "logout":
774
487
  return logout(args, runtime);
488
+ case "profiles":
489
+ return profilesResult(args);
490
+ case "use":
491
+ return useProfileResult(args, runtime.env);
775
492
  case "status":
776
493
  return status(args, runtime);
777
494
  case "doctor":
@@ -783,187 +500,55 @@ async function dispatch(args, runtime) {
783
500
  case "run":
784
501
  return run(args, runtime);
785
502
  case "connect":
786
- return connect(args, runtime);
503
+ return connect(args, runtime, withGateway);
787
504
  case "resources":
788
505
  return resources(args, runtime);
789
506
  case "prompts":
790
507
  return prompts(args, runtime);
791
508
  case "discover":
792
509
  return discover(args, runtime);
510
+ case "session":
511
+ return runCliSession(args, runtime, dispatch);
793
512
  case "completion":
794
- return completion(args);
513
+ return completionResult(args);
795
514
  case "help":
796
- return help(args);
515
+ return helpResult(args);
797
516
  case "version":
798
- return version(args, runtime.env);
799
- }
800
- }
801
- function helpText(verb) {
802
- const details = {
803
- login: "passport login --cloud <origin> [--workspace <id>] [--client <id>] [--profile <name>]\nStarts device sign-in and stores a cli-surface rotating credential.",
804
- logout: "passport logout [--profile <name>]\nRevokes the rotating credential and always removes the local profile.",
805
- status: "passport status\nJSON: {workspace,member,endpoint,auth,profile?,client,mcps:[{app,name,status,toolCount}]}",
806
- doctor: "passport doctor [--profile <name>]\nChecks Node, credential-store safety, endpoint security, server health, authentication, serverInfo, and the exact CLI protocol. JSON includes {ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}.",
807
- search: "passport search [query...] [--app <key>]\nEmpty query lists the complete permitted catalog. JSON is the server search payload.",
808
- describe: "passport describe <tool>\nShows the exact tool definition and complete parameter schema.",
809
- run: "passport run <tool> [json-object]\n --args - read the JSON object from stdin\n --set key=value set a string argument (repeatable)\n --set-json key=<json> set a typed argument (repeatable)\n --wait <sec> retry only a definite approval_pending call\nJSON is the complete MCP tool result; human stdout is verbatim tool text.",
810
- connect: "passport connect [app...] [--alias <name>] [--open] [--wait <sec>]\nShows member-bound connection links and can wait for sign-in to finish. JSON is the manage_connections payload.",
811
- resources: "passport resources [uri] [--out <file>]\nLists or reads workspace MCP resources. Binary content requires --out or --json.",
812
- prompts: "passport prompts [name] [--set key=value] [--out <file>]\nLists or gets workspace MCP prompts. Binary content requires --out or --json.",
813
- discover: "passport discover\nScans supported local MCP configuration, submits privacy-minimized inventory, and exits 5 when a managed policy reports a violation.",
814
- completion: "passport completion <bash|zsh|fish>\nPrints an offline shell-completion script to stdout.",
815
- help: "passport help [verb]",
816
- version: "passport version\nWorks without a profile or network."
817
- };
818
- if (verb && details[verb])
819
- return `${details[verb]}\n\nGlobal: --profile <name> --json --timeout <sec> --quiet --caller <id>`;
820
- return `Passport CLI ${VERSION}
821
-
822
- Usage: passport <command> [options]
823
-
824
- login Sign in with the device flow
825
- logout Revoke and remove a profile
826
- status Show identity and visible MCP connection state
827
- doctor Diagnose local setup and server compatibility
828
- search Find permitted tools or list the catalog
829
- describe Show one exact tool definition
830
- run Run a governed tool
831
- connect Connect member MCP accounts
832
- resources List or read MCP resources
833
- prompts List or get MCP prompts
834
- discover Scan this computer for direct MCP configuration
835
- completion Generate bash, zsh, or fish completion
836
- help Show command help
837
- version Show CLI version and local context
838
-
839
- Global: --profile <name> --json --timeout <sec> --quiet --caller <id>
840
-
841
- Exit codes: 0 success · 1 network/server · 2 auth · 3 needs-connect · 4 approval-pending · 5 policy/guardrail/selection/approval-denial · 6 usage/unknown
842
- With --json, stdout is exactly one JSON value. Hints and warnings use stderr.`;
843
- }
844
- function emit(result, args, runtime) {
845
- if (bool(args, "json")) {
846
- runtime.stdout.write(`${JSON.stringify(result.json)}\n`);
847
- return;
848
- }
849
- if (result.human === undefined || (bool(args, "quiet") && !result.essential))
850
- return;
851
- if (Buffer.isBuffer(result.human))
852
- runtime.stdout.write(result.human);
853
- else
854
- runtime.stdout.write(result.raw ? result.human : `${result.human}${result.human.endsWith("\n") ? "" : "\n"}`);
855
- }
856
- function asFailure(error) {
857
- if (error instanceof CliFailure)
858
- return error;
859
- if (error instanceof ArgError)
860
- return new CliFailure(error.message, 6, "usage");
861
- const raw = error instanceof Error ? error.message : String(error);
862
- const message = sanitize(raw);
863
- if (message === SERVER_TOO_OLD || message.includes("CLI-compatible server"))
864
- return new CliFailure(SERVER_TOO_OLD, 1, "server_too_old");
865
- if (/token exchange failed|invalid_or_revoked|unauthori[sz]ed|\b401\b/i.test(message)) {
866
- return new CliFailure("Passport authentication expired or was revoked.", 2, "auth", { hint: "Run: passport login" });
867
- }
868
- if (/timeout|timed out|aborted|aborterror|requesttimeout/i.test(message))
869
- return new CliFailure("The Passport request timed out; it was not retried.", 1, "timeout");
870
- return new CliFailure(message || "Passport request failed.", 1, "network_or_server");
871
- }
872
- export function sanitize(message) {
873
- // Bound work before applying redactors: SDK/network errors can contain a
874
- // surprisingly large serialized cause. The final user-facing error is 500
875
- // chars, so scanning a small prefix is sufficient and avoids regex work over
876
- // an attacker-sized payload.
877
- return message
878
- .slice(0, 2_000)
879
- .replace(/Bearer\s+\S+/gi, "Bearer [redacted]")
880
- .replace(/("(?:refreshToken|refresh-token|accessToken|access-token|token|agentKey|agent_key|agent-key|apiKey|api_key|api-key|clientSecret|client_secret|client-secret)"\s*:\s*")[^"]*"/gi, "$1[redacted]\"")
881
- .replace(/((?:refreshToken|refresh-token|accessToken|access-token|token|agentKey|agent_key|agent-key|apiKey|api_key|api-key|agent-key|clientSecret|client_secret|client-secret)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&}]+)/gi, "$1[redacted]")
882
- .replace(/\b(?:[A-Za-z0-9_-]+~)?(?:pak|ppr|ppa|pp)_[A-Za-z0-9_-]{12,}\b/g, "[redacted]")
883
- .slice(0, 500);
884
- }
885
- function emitFailure(error, json, quiet, runtime) {
886
- if (json) {
887
- runtime.stdout.write(`${JSON.stringify({
888
- error: error.message,
889
- cause: error.cause,
890
- exitCode: error.exitCode,
891
- ...(error.details.approvalId ? { approvalId: error.details.approvalId } : {}),
892
- ...(error.details.app ? { app: error.details.app } : {})
893
- })}\n`);
894
- }
895
- else {
896
- runtime.stderr.write(`${error.message}\n`);
517
+ return versionResult(args, runtime.env);
897
518
  }
898
- if (error.details.hint && !quiet)
899
- runtime.stderr.write(`${error.details.hint}\n`);
900
519
  }
901
- async function timedFetch(input, init, ms, parent) {
902
- return fetch(input, { ...init, signal: AbortSignal.any([parent, AbortSignal.timeout(ms)]) });
903
- }
904
- async function safeApiError(response, fallback) {
905
- try {
906
- const body = (await response.json());
907
- return typeof body.error === "string" ? sanitize(body.error) : fallback;
908
- }
909
- catch {
910
- return fallback;
911
- }
912
- }
913
- function sleep(ms, signal) {
914
- return new Promise((resolve, reject) => {
915
- if (signal.aborted) {
916
- reject(signal.reason);
917
- return;
918
- }
919
- const timer = setTimeout(done, ms);
920
- function done() {
921
- signal.removeEventListener("abort", cancelled);
922
- resolve();
923
- }
924
- function cancelled() {
925
- clearTimeout(timer);
926
- signal.removeEventListener("abort", cancelled);
927
- reject(signal.reason);
928
- }
929
- signal.addEventListener("abort", cancelled, { once: true });
930
- });
931
- }
932
- function openUrl(url) {
933
- const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
934
- const argv = process.platform === "win32" ? ["/c", "start", "", url] : [url];
935
- try {
936
- const child = spawn(command, argv, { stdio: "ignore", detached: true, shell: false });
937
- child.on("error", () => { });
938
- child.unref();
939
- }
940
- catch {
941
- /* the printed URL remains usable */
942
- }
943
- }
944
- function firstSentence(value) {
945
- const trimmed = value.trim().replace(/\s+/g, " ");
946
- const match = trimmed.match(/^.*?[.!?](?:\s|$)/);
947
- return (match?.[0] ?? trimmed).trim();
948
- }
949
- export async function main(argv = process.argv.slice(2), env = process.env) {
520
+ export async function main(argv = process.argv.slice(2), env = process.env, io = {
521
+ stdin: process.stdin,
522
+ stdout: process.stdout,
523
+ stderr: process.stderr
524
+ }) {
950
525
  const controller = new AbortController();
951
526
  const cancel = () => controller.abort(new Error("Cancelled."));
952
527
  process.once("SIGINT", cancel);
953
528
  process.once("SIGTERM", cancel);
954
- const runtime = { env, stdout: process.stdout, stderr: process.stderr, signal: controller.signal };
529
+ const runtime = {
530
+ env,
531
+ stdin: io.stdin ?? process.stdin,
532
+ stdout: io.stdout,
533
+ stderr: io.stderr,
534
+ signal: controller.signal
535
+ };
955
536
  let args;
956
537
  const wantsJson = argv.some((item) => item === "--json" || item.startsWith("--json="));
957
538
  const wantsQuiet = argv.includes("--quiet");
958
539
  try {
959
540
  args = parseArgs(argv);
960
541
  const result = await dispatch(args, runtime);
961
- emit(result, args, runtime);
542
+ if (args.command !== "session")
543
+ emitResult(result, args, runtime);
962
544
  return result.exitCode ?? 0;
963
545
  }
964
546
  catch (error) {
965
547
  const cliError = asFailure(error);
966
- emitFailure(cliError, args ? bool(args, "json") : wantsJson, args ? bool(args, "quiet") : wantsQuiet, runtime);
548
+ if (args?.command === "session")
549
+ await writeCliSessionFailure(runtime, cliError);
550
+ else
551
+ emitFailure(cliError, args ? bool(args, "json") : wantsJson, args ? bool(args, "quiet") : wantsQuiet, runtime);
967
552
  return cliError.exitCode;
968
553
  }
969
554
  finally {