@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,240 @@
1
+ import { chmod, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
2
+ import { randomBytes } from 'node:crypto';
3
+ import path from 'node:path';
4
+ export const MAX_RULES = 200;
5
+ const MAX_PATTERN_CHARS = 300;
6
+ const TOOL_PATTERN = /^(\*|[a-z][a-z0-9_]*)$/;
7
+ export function permissionsPath(cwd) {
8
+ return process.env.KIRO_PERMISSIONS_PATH || path.join(cwd, '.kiro', 'permissions.json');
9
+ }
10
+ /** Compiles a glob where `*` is any run of characters and `?` is one. */
11
+ export function matchesPattern(pattern, text) {
12
+ let source = '^';
13
+ for (const char of pattern) {
14
+ if (char === '*')
15
+ source += '[\\s\\S]*';
16
+ else if (char === '?')
17
+ source += '[\\s\\S]';
18
+ else
19
+ source += char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
20
+ }
21
+ try {
22
+ return new RegExp(`${source}$`).test(text);
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ /**
29
+ * Splits a shell command into the parts a shell would run, so a rule must cover
30
+ * every one of them. Returns null when quoting is unterminated, because there
31
+ * is no reliable way to tell where one command ends.
32
+ */
33
+ export function splitCommand(command) {
34
+ const parts = [];
35
+ let current = '';
36
+ let quote = null;
37
+ for (let index = 0; index < command.length; index++) {
38
+ const char = command[index];
39
+ if (quote !== null) {
40
+ if (char === '\\' && quote === '"' && index + 1 < command.length) {
41
+ current += char + command[index + 1];
42
+ index++;
43
+ continue;
44
+ }
45
+ if (char === quote)
46
+ quote = null;
47
+ current += char;
48
+ continue;
49
+ }
50
+ if (char === '"' || char === "'") {
51
+ quote = char;
52
+ current += char;
53
+ continue;
54
+ }
55
+ if (char === '\\' && index + 1 < command.length) {
56
+ current += char + command[index + 1];
57
+ index++;
58
+ continue;
59
+ }
60
+ if (char === ';' || char === '\n' || char === '\r' || char === '|' || char === '&') {
61
+ const pair = command[index + 1] === char && (char === '|' || char === '&');
62
+ parts.push(current);
63
+ current = '';
64
+ if (pair)
65
+ index++;
66
+ continue;
67
+ }
68
+ current += char;
69
+ }
70
+ if (quote !== null)
71
+ return null;
72
+ parts.push(current);
73
+ return parts.map((part) => part.trim()).filter(Boolean);
74
+ }
75
+ function tokens(segment) {
76
+ return segment.trim().split(/\s+/).filter(Boolean);
77
+ }
78
+ /**
79
+ * The narrowest useful pattern for a request, shown before the rule is saved.
80
+ * For a command that is the program plus its subcommand (`git status*`); for a
81
+ * file that is the exact path.
82
+ */
83
+ export function suggestRulePattern(tool, subject) {
84
+ if (tool !== 'run_command')
85
+ return subject;
86
+ const segments = splitCommand(subject);
87
+ // Chained commands need one rule per segment, so offer none rather than a
88
+ // pattern that would cover only the first.
89
+ if (!segments || segments.length !== 1)
90
+ return '';
91
+ const parts = tokens(segments[0]);
92
+ const program = parts[0];
93
+ if (!program || /[*?]/.test(subject))
94
+ return '';
95
+ const sub = parts[1];
96
+ // A bare program plus a flag would approve too much (`rm*` covers `rm -rf /`),
97
+ // so a flag keeps its target in the pattern.
98
+ const next = parts[2];
99
+ const head = sub === undefined
100
+ ? program
101
+ : sub.startsWith('-')
102
+ ? next && !next.startsWith('-')
103
+ ? `${program} ${sub} ${next}`
104
+ : `${program} ${sub}`
105
+ : `${program} ${sub}`;
106
+ return `${head}*`;
107
+ }
108
+ function ruleApplies(rule, tool, subject) {
109
+ if (rule.tool !== '*' && rule.tool !== tool)
110
+ return false;
111
+ return matchesPattern(rule.match, subject);
112
+ }
113
+ /**
114
+ * Decides whether a request may run without asking. A deny rule always wins; a
115
+ * command is allowed only when every one of its segments is allowed.
116
+ */
117
+ export function evaluateRules(rules, request) {
118
+ if (rules.length === 0 || request.subject === undefined)
119
+ return 'ask';
120
+ const subject = request.subject;
121
+ const segments = request.tool === 'run_command' ? splitCommand(subject) : [subject];
122
+ if (segments === null)
123
+ return 'ask';
124
+ let allowed = segments.length > 0;
125
+ for (const segment of segments) {
126
+ if (rules.some((rule) => rule.action === 'deny' && ruleApplies(rule, request.tool, segment))) {
127
+ return 'deny';
128
+ }
129
+ if (!rules.some((rule) => rule.action === 'allow' && ruleApplies(rule, request.tool, segment))) {
130
+ allowed = false;
131
+ }
132
+ }
133
+ return allowed ? 'allow' : 'ask';
134
+ }
135
+ export function normalizeRules(raw) {
136
+ const list = Array.isArray(raw)
137
+ ? raw
138
+ : typeof raw === 'object' && raw !== null && Array.isArray(raw.rules)
139
+ ? (raw.rules)
140
+ : [];
141
+ const rules = [];
142
+ const seen = new Set();
143
+ for (const entry of list) {
144
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry))
145
+ continue;
146
+ const rule = entry;
147
+ const tool = typeof rule.tool === 'string' ? rule.tool.trim() : '';
148
+ const match = typeof rule.match === 'string' ? rule.match.trim() : '';
149
+ const action = rule.action === 'deny' ? 'deny' : rule.action === 'allow' ? 'allow' : undefined;
150
+ if (!action || !TOOL_PATTERN.test(tool) || !match)
151
+ continue;
152
+ if (match.length > MAX_PATTERN_CHARS || /[\r\n]/.test(match))
153
+ continue;
154
+ const key = `${tool}\u0000${match}\u0000${action}`;
155
+ if (seen.has(key))
156
+ continue;
157
+ seen.add(key);
158
+ rules.push({ tool, match, action });
159
+ if (rules.length >= MAX_RULES)
160
+ break;
161
+ }
162
+ return rules;
163
+ }
164
+ /** Reads the project's rules. A broken file never blocks startup. */
165
+ export async function loadRules(cwd) {
166
+ const file = permissionsPath(cwd);
167
+ let text;
168
+ try {
169
+ text = await readFile(file, 'utf8');
170
+ }
171
+ catch (error) {
172
+ if (error.code === 'ENOENT')
173
+ return { path: file, rules: [] };
174
+ return { path: file, rules: [], problem: `Could not read ${file}: ${error.message}` };
175
+ }
176
+ try {
177
+ return { path: file, rules: normalizeRules(JSON.parse(text)) };
178
+ }
179
+ catch {
180
+ return {
181
+ path: file,
182
+ rules: [],
183
+ problem: `${file} is not valid JSON; no approval rules are in effect.`,
184
+ };
185
+ }
186
+ }
187
+ export async function saveRules(cwd, rules) {
188
+ const file = permissionsPath(cwd);
189
+ const dir = path.dirname(file);
190
+ await mkdir(dir, { recursive: true, mode: 0o700 });
191
+ try {
192
+ await chmod(dir, 0o700);
193
+ }
194
+ catch {
195
+ // not meaningful on every platform
196
+ }
197
+ const body = `${JSON.stringify({ version: 1, rules: normalizeRules(rules) }, null, 2)}\n`;
198
+ const temp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
199
+ try {
200
+ await writeFile(temp, body, { encoding: 'utf8', mode: 0o600 });
201
+ await rename(temp, file);
202
+ }
203
+ catch (error) {
204
+ await unlink(temp).catch(() => undefined);
205
+ throw new Error(`Could not save ${file}: ${error.message}`);
206
+ }
207
+ try {
208
+ await chmod(file, 0o600);
209
+ }
210
+ catch {
211
+ // best effort
212
+ }
213
+ return file;
214
+ }
215
+ /** Adds a rule, replacing one with the same tool and pattern. */
216
+ export async function addRule(cwd, rule) {
217
+ const current = await loadRules(cwd);
218
+ const rules = [
219
+ ...current.rules.filter((entry) => !(entry.tool === rule.tool && entry.match === rule.match)),
220
+ rule,
221
+ ];
222
+ const file = await saveRules(cwd, rules);
223
+ return { path: file, rules: normalizeRules(rules) };
224
+ }
225
+ export async function removeRule(cwd, rule) {
226
+ const current = await loadRules(cwd);
227
+ const rules = current.rules.filter((entry) => !(entry.tool === rule.tool && entry.match === rule.match));
228
+ const file = await saveRules(cwd, rules);
229
+ return { path: file, rules: normalizeRules(rules) };
230
+ }
231
+ /** Deletes the rule file; the directory stays. */
232
+ export async function clearRules(cwd) {
233
+ const file = permissionsPath(cwd);
234
+ await unlink(file).catch((error) => {
235
+ if (error.code !== 'ENOENT')
236
+ throw error;
237
+ });
238
+ return file;
239
+ }
240
+ //# sourceMappingURL=permissions.js.map
@@ -1,4 +1,5 @@
1
1
  import { setTimeout as sleep } from 'node:timers/promises';
2
+ import { chatEndpoint, requestHeaders } from './request.js';
2
3
  import { ProviderError } from './types.js';
3
4
  const MAX_RETRIES = 3;
4
5
  const DEFAULT_RETRY_BASE_MS = 500;
@@ -7,10 +8,6 @@ const DEFAULT_STREAM_IDLE_MS = 120_000;
7
8
  function isRecord(value) {
8
9
  return typeof value === 'object' && value !== null && !Array.isArray(value);
9
10
  }
10
- function endpointFor(baseUrl) {
11
- const trimmed = baseUrl.replace(/\/+$/, '');
12
- return trimmed.endsWith('/chat/completions') ? trimmed : `${trimmed}/chat/completions`;
13
- }
14
11
  function extractText(content) {
15
12
  if (typeof content === 'string')
16
13
  return content;
@@ -136,6 +133,7 @@ function finalizeToolCalls(calls) {
136
133
  export class OpenAIProvider {
137
134
  type = 'openai';
138
135
  model;
136
+ profile;
139
137
  baseUrl;
140
138
  apiKey;
141
139
  temperature;
@@ -147,6 +145,7 @@ export class OpenAIProvider {
147
145
  */
148
146
  completionTokenStyle;
149
147
  constructor(profile, apiKey) {
148
+ this.profile = profile;
150
149
  this.baseUrl = profile.baseUrl;
151
150
  this.model = profile.model;
152
151
  this.apiKey = apiKey;
@@ -155,7 +154,7 @@ export class OpenAIProvider {
155
154
  this.completionTokenStyle = reasoningModel(profile.model) ? 'completion' : 'chat';
156
155
  }
157
156
  async *stream(messages, tools, options = {}) {
158
- const endpoint = endpointFor(this.baseUrl);
157
+ const endpoint = chatEndpoint(this.baseUrl);
159
158
  let url;
160
159
  try {
161
160
  url = new URL(endpoint);
@@ -164,11 +163,10 @@ export class OpenAIProvider {
164
163
  throw new ProviderError(`Invalid endpoint URL: ${endpoint}`);
165
164
  }
166
165
  const headers = {
166
+ ...requestHeaders(this.profile, this.apiKey),
167
167
  'Content-Type': 'application/json',
168
168
  Accept: 'text/event-stream, application/json',
169
169
  };
170
- if (this.apiKey)
171
- headers.Authorization = `Bearer ${this.apiKey}`;
172
170
  const body = {
173
171
  model: this.model,
174
172
  messages: messages.map((message) => {
@@ -0,0 +1,71 @@
1
+ /**
2
+ * URL and header construction shared by the provider and model discovery, so a
3
+ * profile with custom headers behaves the same in `/models`, the connection
4
+ * test, and real turns.
5
+ */
6
+ /** Strips trailing slashes and an optional query string from a base URL. */
7
+ function splitBase(baseUrl) {
8
+ const trimmed = baseUrl.trim();
9
+ const hash = trimmed.indexOf('#');
10
+ const withoutHash = hash === -1 ? trimmed : trimmed.slice(0, hash);
11
+ const mark = withoutHash.indexOf('?');
12
+ return {
13
+ path: (mark === -1 ? withoutHash : withoutHash.slice(0, mark)).replace(/\/+$/, ''),
14
+ query: mark === -1 ? '' : withoutHash.slice(mark),
15
+ };
16
+ }
17
+ /**
18
+ * Builds an endpoint under the base URL, keeping the base's own query string.
19
+ * A base that already names the endpoint is returned unchanged.
20
+ */
21
+ export function endpointUrl(baseUrl, suffix) {
22
+ const { path, query } = splitBase(baseUrl);
23
+ const already = path.toLowerCase().endsWith(suffix.toLowerCase());
24
+ return `${already ? path : `${path}/${suffix.replace(/^\/+/, '')}`}${query}`;
25
+ }
26
+ /** The chat completions endpoint for a profile's base URL. */
27
+ export function chatEndpoint(baseUrl) {
28
+ return endpointUrl(baseUrl, 'chat/completions');
29
+ }
30
+ /** Substitutes ${VAR} in a header value from the environment; leaves unknown names literal. */
31
+ export function expandHeaderValue(value) {
32
+ return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (match, name) => {
33
+ const fromEnv = process.env[name];
34
+ return fromEnv === undefined ? match : fromEnv;
35
+ });
36
+ }
37
+ const RESERVED_HEADERS = new Set([
38
+ 'content-type',
39
+ 'content-length',
40
+ 'accept',
41
+ 'authorization',
42
+ 'host',
43
+ 'connection',
44
+ 'transfer-encoding',
45
+ ]);
46
+ /**
47
+ * Headers a profile adds to every request. Reserved headers are skipped: the
48
+ * key belongs in `apiKeyEnv`, and the rest would break the request itself.
49
+ * Values may reference `${VAR}` so a token can stay in the environment.
50
+ */
51
+ export function profileHeaders(profile) {
52
+ const headers = {};
53
+ for (const [rawName, rawValue] of Object.entries(profile.headers ?? {})) {
54
+ const name = rawName.trim();
55
+ if (!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(name))
56
+ continue;
57
+ if (RESERVED_HEADERS.has(name.toLowerCase()))
58
+ continue;
59
+ headers[name] = expandHeaderValue(rawValue);
60
+ }
61
+ return headers;
62
+ }
63
+ /** Authorization plus the profile's own headers, ready for fetch. */
64
+ export function requestHeaders(profile, apiKey) {
65
+ const headers = { ...profileHeaders(profile) };
66
+ if (apiKey && !Object.keys(headers).some((name) => name.toLowerCase() === 'authorization')) {
67
+ headers.Authorization = `Bearer ${apiKey}`;
68
+ }
69
+ return headers;
70
+ }
71
+ //# sourceMappingURL=request.js.map
package/dist/tools/fs.js CHANGED
@@ -195,6 +195,8 @@ const writeFileTool = {
195
195
  warning: resolved.outside
196
196
  ? `This path is outside the working directory: ${resolved.abs}`
197
197
  : undefined,
198
+ subject: resolved.display,
199
+ insideWorkspace: !resolved.outside,
198
200
  };
199
201
  if (!(await requestApproval(ctx, request)))
200
202
  return denied();
@@ -372,6 +374,8 @@ const editFileTool = {
372
374
  warning: resolved.outside
373
375
  ? `This path is outside the working directory: ${resolved.abs}`
374
376
  : undefined,
377
+ subject: resolved.display,
378
+ insideWorkspace: !resolved.outside,
375
379
  };
376
380
  if (!(await requestApproval(ctx, request)))
377
381
  return denied();
@@ -453,6 +457,8 @@ const multiEditTool = {
453
457
  warning: resolved.outside
454
458
  ? `This path is outside the working directory: ${resolved.abs}`
455
459
  : undefined,
460
+ subject: resolved.display,
461
+ insideWorkspace: !resolved.outside,
456
462
  };
457
463
  if (!(await requestApproval(ctx, request)))
458
464
  return denied();
@@ -5,6 +5,7 @@ import { patchTools } from './patch.js';
5
5
  import { searchTools } from './search.js';
6
6
  import { runCommandTool } from './shell.js';
7
7
  import { skillTools } from './skill.js';
8
+ import { extraTools } from './registry.js';
8
9
  import { toolError } from './types.js';
9
10
  export const MAX_TOOL_RESULT_CHARS = 60_000;
10
11
  export const tools = [
@@ -16,9 +17,19 @@ export const tools = [
16
17
  ...skillTools,
17
18
  ];
18
19
  export const toolDefinitions = tools.map((tool) => tool.definition);
19
- const byName = new Map(tools.map((tool) => [tool.definition.function.name, tool]));
20
+ /** Built-in tools plus any MCP tools registered after startup. */
21
+ export function allTools() {
22
+ return [...tools, ...extraTools()];
23
+ }
24
+ export function allToolDefinitions() {
25
+ return [...toolDefinitions, ...extraTools().map((tool) => tool.definition)];
26
+ }
27
+ function findTool(name) {
28
+ return (tools.find((tool) => tool.definition.function.name === name) ??
29
+ extraTools().find((tool) => tool.definition.function.name === name));
30
+ }
20
31
  export function isReadOnlyTool(name) {
21
- return byName.get(name)?.readOnly === true;
32
+ return findTool(name)?.readOnly === true;
22
33
  }
23
34
  /** Strips registered credentials so they cannot reach the model or a saved session. */
24
35
  function redactResult(result) {
@@ -46,9 +57,11 @@ function capResult(name, result) {
46
57
  };
47
58
  }
48
59
  export async function executeTool(name, rawArguments, ctx) {
49
- const tool = byName.get(name);
60
+ const tool = findTool(name);
50
61
  if (!tool) {
51
- return toolError(`Unknown tool "${name}". Available tools: ${[...byName.keys()].join(', ')}.`);
62
+ return toolError(`Unknown tool "${name}". Available tools: ${allTools()
63
+ .map((entry) => entry.definition.function.name)
64
+ .join(', ')}.`);
52
65
  }
53
66
  let parsed;
54
67
  try {
@@ -71,4 +84,5 @@ export async function executeTool(name, rawArguments, ctx) {
71
84
  return redactResult(toolError(`${name} failed: ${message}`));
72
85
  }
73
86
  }
87
+ export { setExtraTools, extraTools } from './registry.js';
74
88
  //# sourceMappingURL=index.js.map
@@ -156,6 +156,9 @@ const applyPatchTool = {
156
156
  .map((file) => file.abs)
157
157
  .join(', ')}`
158
158
  : undefined,
159
+ // A rule covers one path, so a multi-file patch stays manual.
160
+ subject: planned.length === 1 ? planned[0].display : undefined,
161
+ insideWorkspace: !planned.some((file) => file.outside),
159
162
  };
160
163
  if (!(await requestApproval(ctx, request)))
161
164
  return denied();
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The tool list is fixed at build time, but MCP servers are discovered at
3
+ * startup, so their tools are appended here. `executeTool` and the agent loop
4
+ * both read the merged list through this module.
5
+ */
6
+ let extras = [];
7
+ export function setExtraTools(tools) {
8
+ extras = tools;
9
+ }
10
+ export function extraTools() {
11
+ return extras;
12
+ }
13
+ export function extraToolDefinitions() {
14
+ return extras.map((tool) => tool.definition);
15
+ }
16
+ //# sourceMappingURL=registry.js.map
@@ -3,6 +3,8 @@ import { childEnv } from '../secrets.js';
3
3
  import { denied, toolError } from './types.js';
4
4
  import { truncateMiddle } from './diff.js';
5
5
  const DEFAULT_TIMEOUT_SECONDS = 60;
6
+ /** Longest live tail kept for the status bar; the transcript keeps the full result. */
7
+ const MAX_LIVE_TAIL = 400;
6
8
  const MAX_TIMEOUT_SECONDS = 600;
7
9
  const MAX_OUTPUT_CHARS = 20_000;
8
10
  const CAPTURE_LIMIT = 80_000;
@@ -88,6 +90,7 @@ export const runCommandTool = {
88
90
  tool: 'run_command',
89
91
  title: 'Run command',
90
92
  detail: `$ ${command}`,
93
+ subject: command.trim(),
91
94
  };
92
95
  if (ctx.signal.aborted)
93
96
  return denied('Cancelled by user.');
@@ -177,10 +180,26 @@ export const runCommandTool = {
177
180
  ctx.signal.addEventListener('abort', onAbort, { once: true });
178
181
  if (ctx.signal.aborted)
179
182
  onAbort();
183
+ // The tail of the newest line is enough to see progress; the full output
184
+ // still arrives in the tool result when the command finishes.
185
+ let live = '';
186
+ const emitLive = (chunk) => {
187
+ if (!ctx.onOutput)
188
+ return;
189
+ live = (live + chunk).slice(-MAX_LIVE_TAIL);
190
+ const tail = live.slice(live.lastIndexOf('\n') + 1).trimEnd() || live.trimEnd();
191
+ ctx.onOutput({ tool: 'run_command', chunk, tail: tail.slice(-MAX_LIVE_TAIL) });
192
+ };
180
193
  child.stdout?.setEncoding('utf8');
181
194
  child.stderr?.setEncoding('utf8');
182
- child.stdout?.on('data', (chunk) => stdout.add(chunk));
183
- child.stderr?.on('data', (chunk) => stderr.add(chunk));
195
+ child.stdout?.on('data', (chunk) => {
196
+ stdout.add(chunk);
197
+ emitLive(chunk);
198
+ });
199
+ child.stderr?.on('data', (chunk) => {
200
+ stderr.add(chunk);
201
+ emitLive(chunk);
202
+ });
184
203
  child.on('error', (error) => finish(null, null, error));
185
204
  child.on('close', (code, signal) => finish(code, signal));
186
205
  });