@ywldan/kiro 0.4.0 → 0.5.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.
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Minimal JSON-RPC 2.0 over a child process's stdio, the transport MCP calls
3
+ * "stdio". One JSON object per line in each direction (NDJSON): the protocol
4
+ * frames on newlines, so a pretty-printed message would break every server.
5
+ *
6
+ * Nothing here knows about MCP itself; `client.ts` builds the MCP handshake on
7
+ * top, which keeps the framing testable on its own.
8
+ */
9
+ export class RpcError extends Error {
10
+ code;
11
+ constructor(error) {
12
+ super(`JSON-RPC ${error.code}: ${error.message}`);
13
+ this.name = 'RpcError';
14
+ this.code = error.code;
15
+ }
16
+ }
17
+ export class RpcTimeoutError extends Error {
18
+ constructor(method, timeoutMs) {
19
+ super(`${method} did not answer within ${timeoutMs / 1000}s.`);
20
+ this.name = 'RpcTimeoutError';
21
+ }
22
+ }
23
+ export const DEFAULT_RPC_TIMEOUT_MS = 30_000;
24
+ /** Correlates requests with responses and dispatches inbound requests to handlers. */
25
+ export class RpcChannel {
26
+ nextId = 1;
27
+ pending = new Map();
28
+ handlers = new Map();
29
+ write;
30
+ timeoutMs;
31
+ onNotice;
32
+ closed = false;
33
+ constructor(options) {
34
+ this.write = options.write;
35
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_RPC_TIMEOUT_MS;
36
+ this.onNotice = options.onNotice ?? (() => { });
37
+ }
38
+ /** Methods the server may call on the client, such as `roots/list`. */
39
+ handle(method, handler) {
40
+ this.handlers.set(method, handler);
41
+ }
42
+ /**
43
+ * `timeoutMs` overrides the channel default for one call, e.g. a blocking
44
+ * tool. `signal` drops the call without waiting for the timeout; the server
45
+ * still finishes on its side, so only use it when the answer is no longer
46
+ * wanted.
47
+ */
48
+ request(method, params, timeoutMs, signal) {
49
+ if (this.closed)
50
+ return Promise.reject(new Error('The MCP connection is closed.'));
51
+ if (signal?.aborted)
52
+ return Promise.reject(new Error(`${method} was cancelled.`));
53
+ const id = this.nextId++;
54
+ const limit = timeoutMs ?? this.timeoutMs;
55
+ return new Promise((resolve, reject) => {
56
+ const finish = (error, value) => {
57
+ const entry = this.pending.get(id);
58
+ if (!entry)
59
+ return;
60
+ this.pending.delete(id);
61
+ clearTimeout(entry.timer);
62
+ if (entry.signal)
63
+ entry.signal.removeEventListener('abort', entry.onAbort);
64
+ if (error)
65
+ reject(error);
66
+ else
67
+ resolve(value);
68
+ };
69
+ const timer = setTimeout(() => {
70
+ this.pending.delete(id);
71
+ if (signal)
72
+ signal.removeEventListener('abort', onAbort);
73
+ reject(new RpcTimeoutError(method, limit));
74
+ }, limit);
75
+ timer.unref?.();
76
+ const onAbort = () => {
77
+ this.pending.delete(id);
78
+ clearTimeout(timer);
79
+ reject(new Error(`${method} was cancelled.`));
80
+ };
81
+ signal?.addEventListener('abort', onAbort, { once: true });
82
+ this.pending.set(id, {
83
+ method,
84
+ resolve: resolve,
85
+ reject,
86
+ timer,
87
+ onAbort,
88
+ signal,
89
+ });
90
+ this.send({ jsonrpc: '2.0', id, method, ...(params === undefined ? {} : { params }) });
91
+ });
92
+ }
93
+ notify(method, params) {
94
+ if (this.closed)
95
+ return;
96
+ this.send({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) });
97
+ }
98
+ /** Reads one line of output; anything that is not JSON-RPC is reported, not thrown. */
99
+ receive(line) {
100
+ const text = line.trim();
101
+ if (!text)
102
+ return;
103
+ let message;
104
+ try {
105
+ message = JSON.parse(text);
106
+ }
107
+ catch {
108
+ // Servers sometimes print banners; keep them out of the transcript but visible.
109
+ this.onNotice(`MCP server printed non-JSON output: ${text.slice(0, 200)}`);
110
+ return;
111
+ }
112
+ if (Array.isArray(message)) {
113
+ for (const entry of message)
114
+ this.receiveMessage(entry);
115
+ return;
116
+ }
117
+ this.receiveMessage(message);
118
+ }
119
+ close() {
120
+ this.closed = true;
121
+ for (const [id, pending] of this.pending) {
122
+ clearTimeout(pending.timer);
123
+ if (pending.signal)
124
+ pending.signal.removeEventListener('abort', pending.onAbort);
125
+ pending.reject(new Error(`The connection closed before ${pending.method} answered.`));
126
+ this.pending.delete(id);
127
+ }
128
+ }
129
+ send(payload) {
130
+ this.write(`${JSON.stringify(payload)}\n`);
131
+ }
132
+ receiveMessage(raw) {
133
+ if (typeof raw !== 'object' || raw === null)
134
+ return;
135
+ const message = raw;
136
+ const id = typeof message.id === 'number' ? message.id : undefined;
137
+ if (typeof message.method === 'string') {
138
+ // A request from the server expects a response; a notification does not.
139
+ const params = message.params;
140
+ if (id === undefined) {
141
+ this.onNotice(`MCP notification ignored: ${message.method}`);
142
+ return;
143
+ }
144
+ const handler = this.handlers.get(message.method);
145
+ if (!handler) {
146
+ this.send({
147
+ jsonrpc: '2.0',
148
+ id,
149
+ error: { code: -32601, message: `Method not found: ${message.method}` },
150
+ });
151
+ return;
152
+ }
153
+ void Promise.resolve()
154
+ .then(() => handler(params))
155
+ .then((result) => this.send({ jsonrpc: '2.0', id, result }))
156
+ .catch((error) => this.send({
157
+ jsonrpc: '2.0',
158
+ id,
159
+ error: { code: -32000, message: error instanceof Error ? error.message : String(error) },
160
+ }));
161
+ return;
162
+ }
163
+ if (id === undefined)
164
+ return;
165
+ const pending = this.pending.get(id);
166
+ if (!pending)
167
+ return;
168
+ this.pending.delete(id);
169
+ clearTimeout(pending.timer);
170
+ if (typeof message.error === 'object' && message.error !== null) {
171
+ const error = message.error;
172
+ pending.reject(new RpcError({
173
+ code: typeof error.code === 'number' ? error.code : -32000,
174
+ message: typeof error.message === 'string' ? error.message : 'Unknown JSON-RPC error',
175
+ data: error.data,
176
+ }));
177
+ return;
178
+ }
179
+ pending.resolve(message.result);
180
+ }
181
+ }
182
+ /** Splits a byte stream into lines without assuming every chunk ends on one. */
183
+ export function createLineReader(onLine) {
184
+ let buffer = '';
185
+ return {
186
+ push(chunk) {
187
+ buffer += chunk;
188
+ let index = buffer.indexOf('\n');
189
+ while (index !== -1) {
190
+ const line = buffer.slice(0, index);
191
+ buffer = buffer.slice(index + 1);
192
+ onLine(line);
193
+ index = buffer.indexOf('\n');
194
+ }
195
+ // A server that never sends a newline must not grow the buffer forever.
196
+ if (buffer.length > 8 * 1024 * 1024) {
197
+ buffer = '';
198
+ onLine('');
199
+ }
200
+ },
201
+ flush() {
202
+ if (buffer)
203
+ onLine(buffer);
204
+ buffer = '';
205
+ },
206
+ };
207
+ }
208
+ //# sourceMappingURL=rpc.js.map
@@ -0,0 +1,106 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { endpointFrom, MCP_CLIENT_NAME, MCP_CLIENT_VERSION, MCP_PROTOCOL_VERSION } from './client.js';
3
+ import { RpcChannel, createLineReader, RpcError } from './rpc.js';
4
+ import { childEnvFor } from './env.js';
5
+ /** How long `tools/list` and `tools/call` may take before the call fails. */
6
+ export const MCP_CALL_TIMEOUT_MS = Number(process.env.KIRO_MCP_TIMEOUT_MS ?? 30_000);
7
+ const MAX_STDERR_KEPT = 2_000;
8
+ /**
9
+ * Starts a server process and speaks MCP over its stdio. This is the fallback
10
+ * used when `@modelcontextprotocol/sdk` is not installed, and it is what the
11
+ * tests exercise, so the framing is covered without an optional dependency.
12
+ */
13
+ export async function connectStdio(name, config, options = {}) {
14
+ const notices = [];
15
+ let child;
16
+ try {
17
+ child = spawn(config.command, config.args ?? [], {
18
+ cwd: config.cwd ?? options.cwd ?? process.cwd(),
19
+ env: childEnvFor(config.env),
20
+ stdio: ['pipe', 'pipe', 'pipe'],
21
+ windowsHide: true,
22
+ shell: process.platform === 'win32',
23
+ });
24
+ }
25
+ catch (error) {
26
+ throw new Error(`Could not start MCP server "${name}": ${error.message}`);
27
+ }
28
+ let stderrTail = '';
29
+ child.stderr?.setEncoding('utf8');
30
+ child.stderr?.on('data', (chunk) => {
31
+ stderrTail = (stderrTail + chunk).slice(-MAX_STDERR_KEPT);
32
+ });
33
+ const exited = new Promise((resolve) => {
34
+ child.on('close', (code, signal) => resolve({ code, signal }));
35
+ child.on('error', () => resolve({ code: null, signal: null }));
36
+ });
37
+ const rpc = new RpcChannel({
38
+ write: (line) => {
39
+ if (child.stdin?.writable)
40
+ child.stdin.write(line);
41
+ },
42
+ timeoutMs: config.timeoutMs ?? MCP_CALL_TIMEOUT_MS,
43
+ onNotice: (message) => {
44
+ notices.push(message);
45
+ options.onNotice?.(`${name}: ${message}`);
46
+ },
47
+ });
48
+ // A server may ask for roots or sampling; Kiro answers "not supported" so the
49
+ // server falls back instead of waiting forever.
50
+ rpc.handle('roots/list', () => ({ roots: [] }));
51
+ rpc.handle('ping', () => ({}));
52
+ const reader = createLineReader((line) => rpc.receive(line));
53
+ child.stdout?.setEncoding('utf8');
54
+ child.stdout?.on('data', (chunk) => reader.push(chunk));
55
+ const closed = new Promise((resolve) => {
56
+ void exited.then(() => {
57
+ reader.flush();
58
+ rpc.close();
59
+ resolve();
60
+ });
61
+ });
62
+ if (!child.pid) {
63
+ const detail = stderrTail.trim().split('\n').slice(-3).join('\n');
64
+ throw new Error(`Could not start MCP server "${name}"${detail ? `: ${detail}` : '.'}`);
65
+ }
66
+ // The handshake is the only place where a wrong protocol version is fatal:
67
+ // the spec allows the client to continue with the version it asked for.
68
+ let init;
69
+ try {
70
+ init = await rpc.request('initialize', {
71
+ protocolVersion: MCP_PROTOCOL_VERSION,
72
+ capabilities: { roots: { listChanged: false } },
73
+ clientInfo: { name: MCP_CLIENT_NAME, version: MCP_CLIENT_VERSION },
74
+ });
75
+ rpc.notify('notifications/initialized', {});
76
+ }
77
+ catch (error) {
78
+ if (error instanceof RpcError) {
79
+ throw new Error(`MCP server "${name}" rejected the handshake: ${error.message}`);
80
+ }
81
+ throw error;
82
+ }
83
+ const info = typeof init === 'object' && init !== null
84
+ ? (init.serverInfo ?? {})
85
+ : {};
86
+ const endpoint = endpointFrom(name, 'builtin', {
87
+ name: typeof info.name === 'string' ? info.name : name,
88
+ version: typeof info.version === 'string' ? info.version : 'unknown',
89
+ }, (method, params, signal) => rpc.request(method, params, method === 'tools/call' ? config.timeoutMs : undefined, signal), async () => {
90
+ rpc.close();
91
+ child.stdin?.end();
92
+ // Give the server a moment to exit, then stop it: a hung server must not
93
+ // keep the CLI alive when the user quits.
94
+ const timer = setTimeout(() => child.kill('SIGTERM'), 500);
95
+ timer.unref?.();
96
+ await Promise.race([closed, new Promise((resolve) => setTimeout(resolve, 1_500))]);
97
+ clearTimeout(timer);
98
+ if (child.exitCode === null)
99
+ child.kill('SIGKILL');
100
+ });
101
+ // A server that dies later fails its pending calls instead of leaving them to
102
+ // time out: rpc.close() rejects everything still waiting.
103
+ void closed.then(() => rpc.close());
104
+ return endpoint;
105
+ }
106
+ //# sourceMappingURL=stdio.js.map
package/dist/model/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import { configPath, loadConfig, normalizeBaseUrl, recoverConfig, saveConfig, validateProfileName, ConfigError, } from '../config.js';
1
+ import { configPath, loadConfig, normalizeBaseUrl, parseHeaderEntry, recoverConfig, saveConfig, validateProfileName, ConfigError, } from '../config.js';
2
2
  import { defaultKeyEnv, envPath, keyStatus, loadEnvFile, validateEnvName, writeEnvValue, EnvError, } from '../env.js';
3
3
  import { testConnection } from './discovery.js';
4
4
  import { CliModelUi, closeModelUi, ModelCliError } from './cli-ui.js';
@@ -21,6 +21,7 @@ Add options:
21
21
  --api-key <key> store a new key in ~/.kiro/.env (never in config.json)
22
22
  --temperature <n> sampling temperature (default 0.2)
23
23
  --max-tokens <n> response limit (default 4096)
24
+ --header <name:value> extra request header (repeatable; value may use \${VAR})
24
25
  --set-active make the new profile active
25
26
  --no-test skip the connection test
26
27
  -h, --help show this help
@@ -31,6 +32,7 @@ Keys live in ${envPath()} (mode 0600); config.json only stores the variable name
31
32
  function parseFlags(argv, spec) {
32
33
  const parsed = {
33
34
  values: new Map(),
35
+ repeated: new Map(),
34
36
  booleans: new Set(),
35
37
  positionals: [],
36
38
  help: false,
@@ -57,8 +59,9 @@ function parseFlags(argv, spec) {
57
59
  parsed.booleans.add(flag);
58
60
  continue;
59
61
  }
60
- if (!spec.value.has(flag))
62
+ if (!spec.value.has(flag) && !spec.repeated?.has(flag)) {
61
63
  throw new ModelCliError(`Unknown option: ${flag}`, 2);
64
+ }
62
65
  let value;
63
66
  if (equals !== -1) {
64
67
  value = arg.slice(equals + 1);
@@ -72,6 +75,12 @@ function parseFlags(argv, spec) {
72
75
  }
73
76
  if (!value)
74
77
  throw new ModelCliError(`Option ${flag} requires a value.`, 2);
78
+ if (spec.repeated?.has(flag)) {
79
+ const list = parsed.repeated.get(flag) ?? [];
80
+ list.push(value);
81
+ parsed.repeated.set(flag, list);
82
+ continue;
83
+ }
75
84
  parsed.values.set(flag, value);
76
85
  }
77
86
  return parsed;
@@ -123,7 +132,9 @@ async function loadConfigForCommand(interactive) {
123
132
  }
124
133
  function printProfile(key, profile, active) {
125
134
  const marker = active ? '*' : ' ';
126
- console.log(`${marker} ${key} ${profile.model} ${profile.baseUrl} (${keyStatus(profile)})`);
135
+ const headers = Object.keys(profile.headers ?? {});
136
+ const headerNote = headers.length > 0 ? ` headers: ${headers.join(',')}` : '';
137
+ console.log(`${marker} ${key} ${profile.model} ${profile.baseUrl} (${keyStatus(profile)})${headerNote}`);
127
138
  }
128
139
  async function runWizard() {
129
140
  const ui = new CliModelUi();
@@ -150,6 +161,7 @@ async function runAdd(argv) {
150
161
  '--max-tokens',
151
162
  ]),
152
163
  boolean: new Set(['--set-active', '--no-test']),
164
+ repeated: new Set(['--header']),
153
165
  };
154
166
  const parsed = parseFlags(argv, spec);
155
167
  if (parsed.help) {
@@ -159,7 +171,7 @@ async function runAdd(argv) {
159
171
  if (parsed.positionals.length > 0) {
160
172
  usageError(`Unexpected argument: ${parsed.positionals[0]}`);
161
173
  }
162
- if (parsed.values.size === 0 && parsed.booleans.size === 0) {
174
+ if (parsed.values.size === 0 && parsed.booleans.size === 0 && parsed.repeated.size === 0) {
163
175
  const loaded = await loadConfigForCommand(true);
164
176
  const ui = new CliModelUi();
165
177
  const ctx = {
@@ -195,6 +207,16 @@ async function runAdd(argv) {
195
207
  if (loaded.config.profiles[name]) {
196
208
  throw new ModelCliError(`Profile "${name}" already exists. Run "kiro model" and choose "Edit a model", or pick another name.`, 1);
197
209
  }
210
+ let headers;
211
+ for (const entry of parsed.repeated.get('--header') ?? []) {
212
+ try {
213
+ const { name: headerName, value } = parseHeaderEntry(entry);
214
+ headers = { ...headers, [headerName]: value };
215
+ }
216
+ catch (error) {
217
+ usageError(error.message);
218
+ }
219
+ }
198
220
  const profile = {
199
221
  type: 'openai',
200
222
  baseUrl,
@@ -202,6 +224,7 @@ async function runAdd(argv) {
202
224
  model,
203
225
  temperature,
204
226
  maxTokens,
227
+ headers,
205
228
  };
206
229
  if (envName && !keyValue && !process.env[envName]) {
207
230
  console.error(`Kiro: warning: $${envName} is not set. The connection test will fail; ` +
@@ -1,4 +1,5 @@
1
1
  import { createProvider } from '../providers/index.js';
2
+ import { endpointUrl, requestHeaders } from '../providers/request.js';
2
3
  import { ProviderError } from '../providers/types.js';
3
4
  import { formatDuration } from '../ui/text.js';
4
5
  export const DEFAULT_TIMEOUT_MS = 10_000;
@@ -6,11 +7,9 @@ function isRecord(value) {
6
7
  return typeof value === 'object' && value !== null && !Array.isArray(value);
7
8
  }
8
9
  export function modelsEndpoint(baseUrl) {
9
- const trimmed = baseUrl.trim().replace(/\/+$/, '');
10
- const withoutChat = trimmed.endsWith('/chat/completions')
11
- ? trimmed.slice(0, -'/chat/completions'.length).replace(/\/+$/, '')
12
- : trimmed;
13
- return `${withoutChat}/models`;
10
+ // A base that already names the chat endpoint maps back to its root.
11
+ const root = baseUrl.trim().replace(/\/chat\/completions\/?(?=$|[?#])/i, '');
12
+ return endpointUrl(root, 'models');
14
13
  }
15
14
  function snippet(text) {
16
15
  try {
@@ -84,9 +83,10 @@ export async function discoverModels(options) {
84
83
  }, timeoutMs);
85
84
  const onOuterAbort = () => controller.abort();
86
85
  options.signal?.addEventListener('abort', onOuterAbort, { once: true });
87
- const headers = { Accept: 'application/json' };
88
- if (options.apiKey)
89
- headers.Authorization = `Bearer ${options.apiKey}`;
86
+ const headers = {
87
+ ...requestHeaders({ type: 'openai', baseUrl: options.baseUrl, model: '', headers: options.headers }, options.apiKey),
88
+ Accept: 'application/json',
89
+ };
90
90
  try {
91
91
  const response = await fetch(url, { method: 'GET', headers, signal: controller.signal });
92
92
  if (!response.ok) {
@@ -1,4 +1,4 @@
1
- import { DEFAULT_CONTEXT_WINDOW, normalizeBaseUrl, suggestProfileName, validateProfileName, } from '../config.js';
1
+ import { DEFAULT_CONTEXT_WINDOW, normalizeBaseUrl, parseHeaderEntry, suggestProfileName, validateProfileName, } from '../config.js';
2
2
  import { defaultKeyEnv, isValidEnvName, keyPreview, writeEnvValue, } from '../env.js';
3
3
  import { discoverModels, modelsEndpoint, testConnection, } from './discovery.js';
4
4
  import { allPresets } from './presets.js';
@@ -194,6 +194,7 @@ async function editFields(ctx, draft, originalName) {
194
194
  key: 'contextWindow',
195
195
  label: `Context window (${current.contextWindow ?? DEFAULT_CONTEXT_WINDOW})`,
196
196
  },
197
+ { key: 'headers', label: `Extra request headers (${headerSummary(current)})` },
197
198
  { key: 'done', label: 'Done editing; test and save' },
198
199
  ]);
199
200
  if (field === null)
@@ -315,9 +316,46 @@ async function editFields(ctx, draft, originalName) {
315
316
  if (answer === null)
316
317
  return null;
317
318
  draft.profile = { ...draft.profile, contextWindow: Number(answer) };
319
+ continue;
320
+ }
321
+ if (field === 'headers') {
322
+ const answer = await ui.text({
323
+ label: 'Header as "Name: value" (Enter keeps; comma separates entries; "-" removes all)',
324
+ allowEmpty: true,
325
+ mask: false,
326
+ });
327
+ if (answer === null)
328
+ return null;
329
+ const value = answer.trim();
330
+ if (!value) {
331
+ ui.note('muted', `Headers unchanged: ${headerSummary(current)}.`);
332
+ continue;
333
+ }
334
+ if (value === '-') {
335
+ draft.profile = { ...draft.profile, headers: undefined };
336
+ ui.note('muted', 'Custom headers removed.');
337
+ continue;
338
+ }
339
+ try {
340
+ const merged = { ...current.headers };
341
+ for (const entry of value.split(',')) {
342
+ const { name, value: headerValue } = parseHeaderEntry(entry);
343
+ merged[name] = headerValue;
344
+ }
345
+ draft.profile = { ...draft.profile, headers: merged };
346
+ ui.note('muted', `Headers: ${headerSummary(draft.profile)}.`);
347
+ }
348
+ catch (error) {
349
+ ui.note('error', error.message);
350
+ }
318
351
  }
319
352
  }
320
353
  }
354
+ /** Header names only: values may hold a token, so the UI never prints them. */
355
+ function headerSummary(profile) {
356
+ const names = Object.keys(profile.headers ?? {});
357
+ return names.length > 0 ? names.join(', ') : 'none';
358
+ }
321
359
  async function storePendingKey(draft) {
322
360
  if (!draft.pendingKey)
323
361
  return { profile: draft.profile };
@@ -496,6 +534,26 @@ export async function runAddFlow(ctx) {
496
534
  maxTokens = Number(tokensAnswer);
497
535
  contextWindow = Number(windowAnswer);
498
536
  }
537
+ const headerAnswer = await ui.text({
538
+ label: 'Extra request headers as "Name: value", comma separated (Enter to skip)',
539
+ allowEmpty: true,
540
+ });
541
+ if (headerAnswer === null)
542
+ return cancel(ctx);
543
+ let headers;
544
+ if (headerAnswer.trim()) {
545
+ try {
546
+ headers = {};
547
+ for (const entry of headerAnswer.split(',')) {
548
+ const { name: headerName, value } = parseHeaderEntry(entry);
549
+ headers[headerName] = value;
550
+ }
551
+ }
552
+ catch (error) {
553
+ ui.note('error', error.message);
554
+ ui.note('muted', 'The profile will be saved without custom headers.');
555
+ }
556
+ }
499
557
  const draft = {
500
558
  name,
501
559
  profile: {
@@ -507,6 +565,7 @@ export async function runAddFlow(ctx) {
507
565
  temperature,
508
566
  maxTokens,
509
567
  contextWindow,
568
+ headers,
510
569
  },
511
570
  pendingKey,
512
571
  };