@codetelemetry/mcp 0.3.9 → 0.3.12

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.
Files changed (79) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +81 -9
  3. package/dist/src/client/agent.d.ts +201 -3
  4. package/dist/src/client/agent.js +154 -0
  5. package/dist/src/client/assistants.d.ts +4 -0
  6. package/dist/src/client/assistants.js +5 -0
  7. package/dist/src/client/bin.d.ts +2 -0
  8. package/dist/src/client/bin.js +3 -0
  9. package/dist/src/client/cli.d.ts +1 -0
  10. package/dist/src/client/cli.js +567 -0
  11. package/dist/src/client/clients.d.ts +34 -0
  12. package/dist/src/client/clients.js +74 -0
  13. package/dist/src/client/codexConfig.d.ts +1 -0
  14. package/dist/src/client/codexConfig.js +5 -0
  15. package/dist/src/client/config.d.ts +5 -0
  16. package/dist/src/client/config.js +5 -0
  17. package/dist/src/client/graderSeed.d.ts +50 -0
  18. package/dist/src/client/graderSeed.js +289 -0
  19. package/dist/src/client/hostMetrics.d.ts +54 -0
  20. package/dist/src/client/hostMetrics.js +425 -0
  21. package/dist/src/client/import/browser.d.ts +30 -0
  22. package/dist/src/client/import/browser.js +157 -0
  23. package/dist/src/client/import/convert.d.ts +20 -0
  24. package/dist/src/client/import/convert.js +165 -0
  25. package/dist/src/client/import/core.d.ts +143 -0
  26. package/dist/src/client/import/core.js +441 -0
  27. package/dist/src/client/import/ledger.d.ts +52 -0
  28. package/dist/src/client/import/ledger.js +161 -0
  29. package/dist/src/client/import/model.d.ts +70 -0
  30. package/dist/src/client/import/model.js +42 -0
  31. package/dist/src/client/import/options.d.ts +24 -0
  32. package/dist/src/client/import/options.js +71 -0
  33. package/dist/src/client/import/otlpImport.d.ts +7 -0
  34. package/dist/src/client/import/otlpImport.js +81 -0
  35. package/dist/src/client/import/protocol.d.ts +35 -0
  36. package/dist/src/client/import/protocol.js +51 -0
  37. package/dist/src/client/import/run.d.ts +30 -0
  38. package/dist/src/client/import/run.js +127 -0
  39. package/dist/src/client/import/sources/claudeCodeText.d.ts +19 -0
  40. package/dist/src/client/import/sources/claudeCodeText.js +214 -0
  41. package/dist/src/client/import/sources/codexText.d.ts +20 -0
  42. package/dist/src/client/import/sources/codexText.js +319 -0
  43. package/dist/src/client/import/sources/files.d.ts +24 -0
  44. package/dist/src/client/import/sources/files.js +129 -0
  45. package/dist/src/client/import/transport.d.ts +76 -0
  46. package/dist/src/client/import/transport.js +141 -0
  47. package/dist/src/client/index.d.ts +19 -0
  48. package/dist/src/client/index.js +19 -0
  49. package/dist/src/client/kiro/collector.d.ts +88 -0
  50. package/dist/src/client/kiro/collector.js +577 -0
  51. package/dist/src/client/kiro/command.d.ts +3 -0
  52. package/dist/src/client/kiro/command.js +109 -0
  53. package/dist/src/client/kiro/config.d.ts +39 -0
  54. package/dist/src/client/kiro/config.js +107 -0
  55. package/dist/src/client/kiro/records.d.ts +52 -0
  56. package/dist/src/client/kiro/records.js +206 -0
  57. package/dist/src/client/kiro/service.d.ts +21 -0
  58. package/dist/src/client/kiro/service.js +183 -0
  59. package/dist/src/client/kiro/state.d.ts +45 -0
  60. package/dist/src/client/kiro/state.js +205 -0
  61. package/dist/src/client/kiro/transport.d.ts +9 -0
  62. package/dist/src/client/kiro/transport.js +90 -0
  63. package/dist/src/client/onboard.d.ts +5 -1
  64. package/dist/src/client/onboard.js +28 -23
  65. package/dist/src/client/piConfig.d.ts +29 -0
  66. package/dist/src/client/piConfig.js +112 -0
  67. package/dist/src/client/plan.d.ts +1 -1
  68. package/dist/src/client/plan.js +2 -1
  69. package/dist/src/client/settings.d.ts +4 -0
  70. package/dist/src/client/settings.js +17 -0
  71. package/dist/src/client/yaml.d.ts +5 -0
  72. package/dist/src/client/yaml.js +72 -0
  73. package/dist/src/mcpServer.js +1 -1
  74. package/dist/src/tools.d.ts +9 -6
  75. package/dist/src/tools.js +370 -60
  76. package/dist/src/version.d.ts +1 -1
  77. package/dist/src/version.js +1 -1
  78. package/package.json +178 -9
  79. package/tool-manifest.json +430 -21
@@ -0,0 +1,577 @@
1
+ import fs from "node:fs/promises";
2
+ import { constants } from "node:fs";
3
+ import path from "node:path";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { NO_CONTENT } from "../import/model.js";
6
+ import { toOtlpLogs } from "../import/otlpImport.js";
7
+ import { applyKiroRecord, emptyRecordState, emptyRecordCounters, KIRO_LIMITS, KiroSourceConflictError } from "./records.js";
8
+ import { cleanKiroState, claimKiroState, KIRO_SESSION_ID, KIRO_WORKSPACE, readBoundedJson, validateSession, writeAtomicJson, normalizeKiroCheckpoint } from "./state.js";
9
+ const digest = (value) => createHash("sha256").update(value).digest("hex");
10
+ const RESOURCE = { "service.name": "kiro-cli" };
11
+ const SCOPE = { name: "codetelemetry-connect.kiro-source", version: "1" };
12
+ export class KiroDiscovery {
13
+ overflow = 0;
14
+ root = null;
15
+ workspaces = new Map();
16
+ nextPassAt = 0;
17
+ cursor = 0;
18
+ async scan(root, now, deadline, clock) {
19
+ const found = [];
20
+ if (!this.root && now >= this.nextPassAt) {
21
+ try {
22
+ this.root = await fs.opendir(root, { bufferSize: 16 });
23
+ }
24
+ catch (error) {
25
+ if (error.code === "ENOENT") {
26
+ this.nextPassAt = now + 5000;
27
+ return found;
28
+ }
29
+ throw new Error("Kiro source discovery failed");
30
+ }
31
+ }
32
+ let entries = 0;
33
+ for (let i = 0; this.root && i < 16 && entries < KIRO_LIMITS.directoryEntriesPerTick && clock() < deadline; i++) {
34
+ const entry = await this.root.read();
35
+ entries++;
36
+ if (!entry) {
37
+ await this.root.close();
38
+ this.root = null;
39
+ this.nextPassAt = now + 2000;
40
+ break;
41
+ }
42
+ if (entry.isDirectory() && KIRO_WORKSPACE.test(entry.name) && !this.workspaces.has(entry.name) && this.workspaces.size < KIRO_LIMITS.sessions) {
43
+ this.workspaces.set(entry.name, await fs.opendir(path.join(root, entry.name), { bufferSize: 16 }));
44
+ }
45
+ else if (entry.isDirectory() && KIRO_WORKSPACE.test(entry.name) && !this.workspaces.has(entry.name))
46
+ this.overflow++;
47
+ }
48
+ while (this.workspaces.size && entries < KIRO_LIMITS.directoryEntriesPerTick && clock() < deadline) {
49
+ const names = [...this.workspaces.keys()];
50
+ const name = names[this.cursor++ % names.length];
51
+ const dir = this.workspaces.get(name);
52
+ const entry = await dir.read();
53
+ entries++;
54
+ if (!entry) {
55
+ await dir.close();
56
+ this.workspaces.delete(name);
57
+ continue;
58
+ }
59
+ if (entry.isDirectory() && KIRO_SESSION_ID.test(entry.name))
60
+ found.push({ relative: `${name}/${entry.name}`, id: entry.name });
61
+ }
62
+ return found;
63
+ }
64
+ async close() { if (this.root)
65
+ await this.root.close(); for (const dir of this.workspaces.values())
66
+ await dir.close(); this.workspaces.clear(); this.root = null; }
67
+ }
68
+ export class KiroCollector {
69
+ options;
70
+ checkpoint;
71
+ pending = null;
72
+ release = null;
73
+ discovery = new KiroDiscovery();
74
+ carries = new Map();
75
+ candidates = [];
76
+ candidateCursor = 0;
77
+ capacityBlocked = false;
78
+ stateBytesBlocked = false;
79
+ running = false;
80
+ lastPostAt = -Infinity;
81
+ startedAt;
82
+ health = { version: 2, status: "idle", trackedSessions: 0, parkedSessions: 0, skippingOversizeSessions: 0, cachedTailBytes: 0, cachedTailSessions: 0, carryEvictions: 0, discoveryBacklog: 0, backloggedSessions: 0, unsupportedSessions: 0,
83
+ sourceConflicts: 0, sourceErrors: 0, ignoredRecords: 0, malformedRecords: 0, duplicateRecords: 0, evictedCalls: 0, unsupportedToolDetails: 0, discoveryOverflow: 0, oversizeRecords: 0, readBytes: 0, logsAcknowledged: 0,
84
+ requests: 0, pending: false, lastTickAt: 0 };
85
+ recordCounters = emptyRecordCounters();
86
+ constructor(options) {
87
+ if (!/^[a-f0-9]{64}$/.test(options.destinationHash))
88
+ throw new Error("Kiro destination fingerprint is required");
89
+ const policy = options.policy ?? NO_CONTENT;
90
+ if (typeof policy.prompts !== "boolean" || typeof policy.toolDetails !== "boolean")
91
+ throw new Error("invalid Kiro content policy");
92
+ this.options = { ...options, policy: Object.freeze({ ...policy }) };
93
+ this.startedAt = (options.now ?? Date.now)();
94
+ }
95
+ policyHash() { const policy = this.policy(); return digest(JSON.stringify([policy.prompts, policy.toolDetails])); }
96
+ now() { return (this.options.now ?? Date.now)(); }
97
+ file(name) { return path.join(this.options.stateDir, name); }
98
+ policy() { return this.options.policy ?? NO_CONTENT; }
99
+ fits(checkpoint) { return Buffer.byteLength(JSON.stringify(checkpoint)) + 1 <= KIRO_LIMITS.checkpointBytes; }
100
+ async save() { await writeAtomicJson(this.file("checkpoint.json"), this.checkpoint, KIRO_LIMITS.checkpointBytes); }
101
+ async open() {
102
+ this.release = await claimKiroState(this.options.stateDir);
103
+ try {
104
+ const rootHash = digest(path.resolve(this.options.sourceRoot));
105
+ this.checkpoint = normalizeKiroCheckpoint(await readBoundedJson(this.file("checkpoint.json"), KIRO_LIMITS.checkpointBytes), rootHash, this.options.destinationHash);
106
+ const pending = await readBoundedJson(this.file("pending.json"), KIRO_LIMITS.spoolBytes);
107
+ if (pending) {
108
+ if ((pending.privacyVersion !== undefined && pending.privacyVersion !== 2) ||
109
+ (pending.privacyVersion !== 2 && (this.policy().prompts || this.policy().toolDetails))) {
110
+ throw new Error("Kiro pending content uses an older privacy contract; original retry bytes and offsets are preserved");
111
+ }
112
+ if (pending.version !== 1 || pending.rootHash !== rootHash || pending.destinationHash !== this.options.destinationHash || typeof pending.body !== "string" ||
113
+ Buffer.byteLength(pending.body) > KIRO_LIMITS.envelopeBytes || pending.digest !== digest(pending.body) ||
114
+ !/^[a-f0-9-]{36}$/.test(pending.id) || !Number.isSafeInteger(pending.createdAt) ||
115
+ !Number.isSafeInteger(pending.attempts) || pending.attempts < 0 || pending.attempts > KIRO_LIMITS.maxAttempts ||
116
+ !Number.isSafeInteger(pending.nextAttemptAt) || !Array.isArray(pending.updates) || pending.updates.length > KIRO_LIMITS.sessionsPerTick ||
117
+ pending.policyHash !== this.policyHash())
118
+ throw new Error("invalid Kiro retry spool contract");
119
+ pending.updates.forEach(validateSession);
120
+ if (!pending.updates.length || new Set(pending.updates.map(update => update.id)).size !== pending.updates.length ||
121
+ pending.updates.some(update => !this.checkpoint.sessions.some(session => session.id === update.id && session.relative === update.relative)))
122
+ throw new Error("invalid Kiro spool source ownership");
123
+ this.pending = pending;
124
+ }
125
+ await cleanKiroState(this.options.stateDir);
126
+ if (this.fits(this.checkpoint))
127
+ await this.save();
128
+ else {
129
+ this.stateBytesBlocked = true;
130
+ this.capacityBlocked = true;
131
+ }
132
+ }
133
+ catch (error) {
134
+ await this.close();
135
+ throw error;
136
+ }
137
+ }
138
+ async close() {
139
+ await this.discovery.close();
140
+ this.carries.clear();
141
+ if (this.release) {
142
+ await this.release();
143
+ this.release = null;
144
+ }
145
+ }
146
+ snapshot() { return { ...this.health }; }
147
+ async metadata(session) {
148
+ const metadata = await readBoundedJson(path.join(this.options.sourceRoot, session.relative, "session.json"), 16 * 1024);
149
+ return metadata?.id === session.id && metadata.schemaVersion === "1.0.0" && metadata.dataModelVersion === 1 ? metadata : null;
150
+ }
151
+ keepCarry(id, carry) {
152
+ carry.buffer = Buffer.from(carry.buffer);
153
+ this.carries.delete(id);
154
+ this.carries.set(id, carry);
155
+ let bytes = [...this.carries.values()].reduce((n, row) => n + row.buffer.length, 0);
156
+ const active = new Set(this.checkpoint.sessions.map(row => row.id));
157
+ while (this.carries.size > KIRO_LIMITS.carrySessions || bytes > KIRO_LIMITS.carryBytes) {
158
+ const key = [...this.carries.keys()].find(key => !active.has(key)) ?? this.carries.keys().next().value;
159
+ bytes -= this.carries.get(key).buffer.length;
160
+ this.carries.delete(key);
161
+ this.health.carryEvictions++;
162
+ }
163
+ }
164
+ async observe(session) {
165
+ const file = await fs.open(path.join(this.options.sourceRoot, session.relative, "messages.jsonl"), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
166
+ try {
167
+ const stat = await file.stat();
168
+ if (!stat.isFile() || !Number.isSafeInteger(stat.size))
169
+ throw new Error("invalid Kiro source file");
170
+ const physical = `${stat.dev}:${stat.ino}`;
171
+ const tail = Buffer.alloc(Math.min(64, stat.size));
172
+ if (tail.length && (await file.read(tail, 0, tail.length, stat.size - tail.length)).bytesRead !== tail.length)
173
+ throw new Error("Kiro source changed during probe");
174
+ let prefix = true;
175
+ if (session.offset > 0 && session.anchor && stat.size >= session.offset) {
176
+ const anchor = session.offset === stat.size ? tail : Buffer.alloc(Math.min(64, session.offset));
177
+ if (session.offset !== stat.size && (await file.read(anchor, 0, anchor.length, session.offset - anchor.length)).bytesRead !== anchor.length)
178
+ prefix = false;
179
+ if (digest(anchor.toString("base64")) !== session.anchor)
180
+ prefix = false;
181
+ }
182
+ return { physical, size: stat.size, mtime: stat.mtimeMs, anchor: tail.length ? digest(tail.toString("base64")) : undefined, last: tail.at(-1), samePrefix: physical === session.physical && stat.size >= session.offset && prefix };
183
+ }
184
+ finally {
185
+ await file.close();
186
+ }
187
+ }
188
+ async rotateSessions(deadline) {
189
+ const snapshot = this.checkpoint.sessions.slice();
190
+ let changed = false;
191
+ for (let i = 0; i < Math.min(snapshot.length, KIRO_LIMITS.sessionsPerTick) && this.now() < deadline; i++) {
192
+ const session = snapshot[this.checkpoint.retirementCursor++ % snapshot.length];
193
+ const carry = this.carries.get(session.id);
194
+ let observation;
195
+ try {
196
+ observation = await this.observe(session);
197
+ }
198
+ catch {
199
+ if (!session.blocked)
200
+ continue;
201
+ }
202
+ const partialEnd = !!observation && !!carry && carry.readOffset === observation.size && carry.buffer.indexOf(10) < 0;
203
+ const progressed = session.offset > (session.activationOffset ?? session.offset);
204
+ if (!session.blocked && (!observation?.samePrefix || !(progressed || session.offset === observation.size || partialEnd)))
205
+ continue;
206
+ const parked = { ...session, records: { seen: session.records.seen.slice(-KIRO_LIMITS.parkedReplayEntries), calls: session.records.calls.slice() },
207
+ ...(observation ? { observedSize: observation.size, observedMtimeMs: observation.mtime, awaitingMore: session.offset === observation.size || partialEnd } : {}),
208
+ ...(carry?.skipping ? { skipInitialLine: true, ...(!carry.initialSkip ? { skippingOversize: true } : {}) } : {}) };
209
+ delete parked.activationOffset;
210
+ this.checkpoint.sessions = this.checkpoint.sessions.filter(row => row.id !== session.id);
211
+ this.checkpoint.parked.push(parked);
212
+ if (!session.blocked && carry && (carry.buffer.length || carry.skipping))
213
+ this.keepCarry(session.id, carry);
214
+ else
215
+ this.carries.delete(session.id);
216
+ changed = true;
217
+ }
218
+ this.checkpoint.retirementCursor %= Math.max(1, this.checkpoint.sessions.length);
219
+ return changed;
220
+ }
221
+ async admitCandidates(deadline) {
222
+ let changed = false, checked = 0;
223
+ const known = new Map([...this.checkpoint.sessions, ...this.checkpoint.parked].map(row => [row.id, row]));
224
+ while (this.candidateCursor < this.candidates.length && checked++ < KIRO_LIMITS.candidateChecksPerTick && this.now() < deadline) {
225
+ const candidate = this.candidates[this.candidateCursor];
226
+ const existing = known.get(candidate.id);
227
+ if (existing) {
228
+ if (existing.relative !== candidate.relative) {
229
+ existing.blocked = "source_conflict";
230
+ changed = true;
231
+ this.candidateCursor++;
232
+ continue;
233
+ }
234
+ if (this.checkpoint.sessions.includes(existing) || existing.blocked === "source_conflict") {
235
+ this.candidateCursor++;
236
+ continue;
237
+ }
238
+ let activate = !!existing.blocked;
239
+ try {
240
+ const stat = await this.observe(existing);
241
+ activate ||= !stat.samePrefix || stat.size !== existing.observedSize || stat.mtime !== existing.observedMtimeMs || (!existing.awaitingMore && stat.size > existing.offset);
242
+ }
243
+ catch {
244
+ this.candidateCursor++;
245
+ continue;
246
+ }
247
+ if (activate) {
248
+ if (this.checkpoint.sessions.length >= KIRO_LIMITS.sessions)
249
+ break;
250
+ this.checkpoint.parked = this.checkpoint.parked.filter(row => row.id !== existing.id);
251
+ const promoted = { ...existing, activationOffset: existing.offset };
252
+ this.checkpoint.sessions.push(promoted);
253
+ known.set(promoted.id, promoted);
254
+ changed = true;
255
+ }
256
+ this.candidateCursor++;
257
+ continue;
258
+ }
259
+ if (known.size >= KIRO_LIMITS.registeredSessions) {
260
+ this.capacityBlocked = true;
261
+ this.health.discoveryOverflow++;
262
+ this.candidateCursor++;
263
+ continue;
264
+ }
265
+ const initial = { ...candidate, physical: "", offset: 0, activationOffset: 0, records: emptyRecordState() };
266
+ if (this.options.bootstrap === "end") {
267
+ try {
268
+ const metadata = await this.metadata(initial);
269
+ if (!metadata)
270
+ initial.blocked = "unsupported_schema";
271
+ else {
272
+ const createdAt = typeof metadata.createdAt === "string" ? Date.parse(metadata.createdAt) : NaN;
273
+ if (!Number.isFinite(createdAt))
274
+ initial.blocked = "source_error";
275
+ else if (createdAt < this.startedAt) {
276
+ const stat = await this.observe(initial);
277
+ Object.assign(initial, { physical: stat.physical, offset: stat.size, generation: 1, observedSize: stat.size, observedMtimeMs: stat.mtime, awaitingMore: true, ...(stat.anchor ? { anchor: stat.anchor } : {}), ...(stat.size && stat.last !== 10 ? { skipInitialLine: true } : {}) });
278
+ delete initial.activationOffset;
279
+ this.checkpoint.parked.push(initial);
280
+ known.set(initial.id, initial);
281
+ changed = true;
282
+ this.candidateCursor++;
283
+ continue;
284
+ }
285
+ }
286
+ }
287
+ catch {
288
+ initial.blocked = "source_error";
289
+ }
290
+ if (initial.blocked) {
291
+ delete initial.activationOffset;
292
+ this.checkpoint.parked.push(initial);
293
+ known.set(initial.id, initial);
294
+ changed = true;
295
+ this.candidateCursor++;
296
+ continue;
297
+ }
298
+ }
299
+ if (this.checkpoint.sessions.length >= KIRO_LIMITS.sessions)
300
+ break;
301
+ this.checkpoint.sessions.push(initial);
302
+ known.set(initial.id, initial);
303
+ changed = true;
304
+ this.candidateCursor++;
305
+ }
306
+ return changed;
307
+ }
308
+ async flush() {
309
+ const pending = this.pending;
310
+ const now = this.now();
311
+ if (pending.updates.every(update => this.checkpoint.sessions.some(session => session.id === update.id && session.physical === update.physical && (session.generation ?? 0) === (update.generation ?? 0) && session.offset >= update.offset))) {
312
+ await fs.unlink(this.file("pending.json"));
313
+ this.pending = null;
314
+ this.health.status = "idle";
315
+ return;
316
+ }
317
+ if (now - pending.createdAt >= KIRO_LIMITS.retryHorizonMs || pending.attempts >= KIRO_LIMITS.maxAttempts) {
318
+ this.health.status = "retry_horizon_exhausted";
319
+ return;
320
+ }
321
+ if (now < pending.createdAt) {
322
+ this.health.status = "clock_rollback";
323
+ return;
324
+ }
325
+ if (now < pending.nextAttemptAt || now - this.lastPostAt < KIRO_LIMITS.requestGapMs) {
326
+ this.health.status = pending.lastOutcome ?? "pending";
327
+ return;
328
+ }
329
+ const sessions = new Map(this.checkpoint.sessions.map(session => [session.id, session]));
330
+ pending.updates.forEach(update => sessions.set(update.id, { ...update, activationOffset: update.activationOffset ?? sessions.get(update.id)?.activationOffset ?? update.offset }));
331
+ const committed = { ...this.checkpoint, sessions: [...sessions.values()] };
332
+ if (!this.fits(committed)) {
333
+ this.stateBytesBlocked = true;
334
+ this.capacityBlocked = true;
335
+ this.health.status = "capacity";
336
+ return;
337
+ }
338
+ this.lastPostAt = now;
339
+ pending.attempts++;
340
+ this.health.requests++;
341
+ pending.nextAttemptAt = now + Math.min(60_000, KIRO_LIMITS.requestGapMs * 2 ** Math.min(6, pending.attempts - 1));
342
+ await writeAtomicJson(this.file("pending.json"), pending, KIRO_LIMITS.spoolBytes);
343
+ const outcome = await this.options.post(pending.body, pending.id);
344
+ this.health.status = outcome;
345
+ pending.lastOutcome = outcome;
346
+ if (outcome !== "ok") {
347
+ if (outcome === "rejected")
348
+ pending.nextAttemptAt = Number.MAX_SAFE_INTEGER;
349
+ else if (outcome === "auth" || outcome === "budget")
350
+ pending.nextAttemptAt = now + 60_000;
351
+ await writeAtomicJson(this.file("pending.json"), pending, KIRO_LIMITS.spoolBytes);
352
+ return;
353
+ }
354
+ await writeAtomicJson(this.file("checkpoint.json"), committed, KIRO_LIMITS.checkpointBytes);
355
+ this.checkpoint = committed;
356
+ const body = JSON.parse(pending.body);
357
+ this.health.logsAcknowledged += body.resourceLogs[0].scopeLogs[0].logRecords.length;
358
+ await fs.unlink(this.file("pending.json"));
359
+ this.pending = null;
360
+ this.health.status = "idle";
361
+ }
362
+ async tick() {
363
+ if (!this.release)
364
+ throw new Error("Kiro collector is not open");
365
+ if (this.running)
366
+ throw new Error("Kiro collector ticks must not overlap");
367
+ this.running = true;
368
+ try {
369
+ this.health.lastTickAt = this.now();
370
+ if (this.stateBytesBlocked)
371
+ return this.finish();
372
+ if (this.pending) {
373
+ await this.flush();
374
+ return this.finish();
375
+ }
376
+ const deadline = this.now() + Math.min(2000, this.options.tickBudgetMs ?? 500);
377
+ let changed = await this.rotateSessions(deadline);
378
+ if (this.candidateCursor >= this.candidates.length) {
379
+ const overflow = this.discovery.overflow;
380
+ this.candidates = await this.discovery.scan(this.options.sourceRoot, this.now(), Math.min(deadline, this.now() + 100), () => this.now());
381
+ this.candidateCursor = 0;
382
+ if (this.discovery.overflow > overflow) {
383
+ this.health.discoveryOverflow += this.discovery.overflow - overflow;
384
+ this.capacityBlocked = true;
385
+ }
386
+ }
387
+ changed = await this.admitCandidates(deadline) || changed;
388
+ const logs = [], updates = [];
389
+ let encodedBytes = 4096, sourceRecords = 0;
390
+ const total = this.checkpoint.sessions.length;
391
+ const selected = Math.min(total, KIRO_LIMITS.sessionsPerTick);
392
+ for (let i = 0; i < selected && this.now() < deadline && sourceRecords < KIRO_LIMITS.recordsPerTick; i++) {
393
+ const original = this.checkpoint.sessions[this.checkpoint.cursor % total];
394
+ this.checkpoint.cursor = (this.checkpoint.cursor + 1) % Math.max(total, 1);
395
+ if (original.blocked === "source_conflict")
396
+ continue;
397
+ const staged = structuredClone(original);
398
+ const logsBefore = logs.length;
399
+ try {
400
+ const metadata = await this.metadata(staged);
401
+ if (!metadata) {
402
+ original.blocked = "unsupported_schema";
403
+ changed = true;
404
+ continue;
405
+ }
406
+ delete staged.blocked;
407
+ const file = await fs.open(path.join(this.options.sourceRoot, staged.relative, "messages.jsonl"), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
408
+ try {
409
+ const stat = await file.stat();
410
+ if (!stat.isFile() || !Number.isSafeInteger(stat.size))
411
+ throw new Error("invalid Kiro source file");
412
+ const physical = `${stat.dev}:${stat.ino}`;
413
+ staged.observedSize = stat.size;
414
+ staged.observedMtimeMs = stat.mtimeMs;
415
+ delete staged.awaitingMore;
416
+ const createdAt = typeof metadata.createdAt === "string" ? Date.parse(metadata.createdAt) : NaN;
417
+ const bootstrapEnd = !staged.physical && this.options.bootstrap === "end";
418
+ if (bootstrapEnd && !Number.isFinite(createdAt))
419
+ throw new Error("Kiro source creation time is unavailable");
420
+ let rewritten = false;
421
+ if (staged.offset > 0 && staged.anchor && stat.size >= staged.offset) {
422
+ const anchor = Buffer.alloc(Math.min(64, staged.offset));
423
+ const { bytesRead } = await file.read(anchor, 0, anchor.length, staged.offset - anchor.length);
424
+ rewritten = bytesRead !== anchor.length || digest(anchor.toString("base64")) !== staged.anchor;
425
+ }
426
+ if (staged.physical !== physical || stat.size < staged.offset || rewritten) {
427
+ staged.physical = physical;
428
+ staged.offset = 0;
429
+ staged.generation = (staged.generation ?? 0) + 1;
430
+ delete staged.anchor;
431
+ delete staged.skipInitialLine;
432
+ delete staged.skippingOversize;
433
+ this.carries.delete(staged.id);
434
+ }
435
+ if (bootstrapEnd && createdAt < this.startedAt) {
436
+ staged.offset = stat.size;
437
+ if (stat.size > 0) {
438
+ const last = Buffer.alloc(1);
439
+ await file.read(last, 0, 1, stat.size - 1);
440
+ if (last[0] !== 10)
441
+ staged.skipInitialLine = true;
442
+ }
443
+ }
444
+ let carry = this.carries.get(staged.id);
445
+ if (!carry || carry.mtime !== stat.mtimeMs || carry.physical !== physical || carry.readOffset > stat.size)
446
+ carry = { mtime: stat.mtimeMs, physical, readOffset: staged.offset, buffer: Buffer.alloc(0), skipping: staged.skipInitialLine === true, initialSkip: staged.skipInitialLine === true && !staged.skippingOversize };
447
+ const chunk = Buffer.alloc(carry.buffer.indexOf(10) >= 0 ? 0 : Math.min(KIRO_LIMITS.readBytesPerSession, Math.max(0, stat.size - carry.readOffset)));
448
+ const { bytesRead } = chunk.length ? await file.read(chunk, 0, chunk.length, carry.readOffset) : { bytesRead: 0 };
449
+ this.health.readBytes += bytesRead;
450
+ const startOffset = carry.readOffset - carry.buffer.length;
451
+ carry.readOffset += bytesRead;
452
+ const buffer = Buffer.concat([carry.buffer, chunk.subarray(0, bytesRead)]);
453
+ let cursor = 0, perSession = 0;
454
+ while (cursor < buffer.length && perSession < 128 && sourceRecords < KIRO_LIMITS.recordsPerTick && this.now() < deadline) {
455
+ const newline = buffer.indexOf(10, cursor);
456
+ if (newline < 0)
457
+ break;
458
+ if (carry.skipping || newline - cursor > KIRO_LIMITS.recordBytes) {
459
+ if (!carry.initialSkip)
460
+ this.health.oversizeRecords++;
461
+ carry.skipping = false;
462
+ carry.initialSkip = false;
463
+ delete staged.skipInitialLine;
464
+ delete staged.skippingOversize;
465
+ }
466
+ else {
467
+ const before = { seen: staged.records.seen.slice(), calls: staged.records.calls.slice() };
468
+ const counters = { ...this.recordCounters };
469
+ const emitted = applyKiroRecord(staged.records, buffer.subarray(cursor, newline), staged.id, this.policy(), this.recordCounters);
470
+ const bytes = emitted.reduce((sum, log) => sum + Buffer.byteLength(JSON.stringify(toOtlpLogs([log], {}, SCOPE))), 0);
471
+ if (logs.length + emitted.length > KIRO_LIMITS.logsPerBatch || encodedBytes + bytes > KIRO_LIMITS.envelopeBytes) {
472
+ staged.records = before;
473
+ Object.assign(this.recordCounters, counters);
474
+ break;
475
+ }
476
+ logs.push(...emitted);
477
+ encodedBytes += bytes;
478
+ }
479
+ cursor = newline + 1;
480
+ staged.offset = startOffset + cursor;
481
+ perSession++;
482
+ sourceRecords++;
483
+ }
484
+ carry.buffer = buffer.subarray(cursor);
485
+ if (carry.buffer.indexOf(10) < 0 && (carry.skipping || carry.buffer.length > KIRO_LIMITS.recordBytes)) {
486
+ carry.buffer = Buffer.alloc(0);
487
+ carry.skipping = true;
488
+ staged.offset = carry.readOffset;
489
+ staged.skipInitialLine = true;
490
+ if (!carry.initialSkip)
491
+ staged.skippingOversize = true;
492
+ }
493
+ this.keepCarry(staged.id, carry);
494
+ if (staged.offset > 0) {
495
+ const anchor = Buffer.alloc(Math.min(64, staged.offset));
496
+ const { bytesRead } = await file.read(anchor, 0, anchor.length, staged.offset - anchor.length);
497
+ if (bytesRead !== anchor.length)
498
+ throw new Error("Kiro source changed during read");
499
+ staged.anchor = digest(anchor.toString("base64"));
500
+ }
501
+ if (staged.offset !== original.offset || staged.physical !== original.physical || staged.observedSize !== original.observedSize || staged.observedMtimeMs !== original.observedMtimeMs || original.blocked)
502
+ updates.push(staged);
503
+ }
504
+ finally {
505
+ await file.close();
506
+ }
507
+ }
508
+ catch (error) {
509
+ const blocked = error instanceof KiroSourceConflictError ? "source_conflict" : "source_error";
510
+ original.blocked = blocked;
511
+ staged.blocked = blocked;
512
+ if (logs.length > logsBefore || staged.offset > original.offset) {
513
+ const prior = updates.findIndex(update => update.id === staged.id);
514
+ if (prior >= 0)
515
+ updates[prior] = staged;
516
+ else
517
+ updates.push(staged);
518
+ }
519
+ changed = true;
520
+ this.carries.delete(original.id);
521
+ }
522
+ }
523
+ const prospective = new Map(this.checkpoint.sessions.map(session => [session.id, session]));
524
+ updates.forEach(update => prospective.set(update.id, update));
525
+ if (!this.fits(this.checkpoint) || !this.fits({ ...this.checkpoint, sessions: [...prospective.values()] })) {
526
+ this.stateBytesBlocked = true;
527
+ this.capacityBlocked = true;
528
+ this.carries.clear();
529
+ return this.finish();
530
+ }
531
+ if (logs.length) {
532
+ const body = JSON.stringify(toOtlpLogs(logs, RESOURCE, SCOPE));
533
+ if (Buffer.byteLength(body) > KIRO_LIMITS.envelopeBytes)
534
+ throw new Error("Kiro encoded envelope exceeds bound");
535
+ this.pending = { version: 1, privacyVersion: 2, rootHash: this.checkpoint.rootHash, destinationHash: this.options.destinationHash, policyHash: this.policyHash(), id: randomUUID(),
536
+ body, digest: digest(body), createdAt: this.now(), attempts: 0, nextAttemptAt: this.now(), updates };
537
+ await this.save();
538
+ await writeAtomicJson(this.file("pending.json"), this.pending, KIRO_LIMITS.spoolBytes);
539
+ this.health.status = "pending";
540
+ }
541
+ else {
542
+ const sessions = new Map(this.checkpoint.sessions.map(session => [session.id, session]));
543
+ updates.forEach(update => sessions.set(update.id, update));
544
+ this.checkpoint.sessions = [...sessions.values()];
545
+ if (changed || updates.length)
546
+ await this.save();
547
+ this.health.status = "idle";
548
+ }
549
+ return this.finish();
550
+ }
551
+ finally {
552
+ this.running = false;
553
+ }
554
+ }
555
+ finish() {
556
+ this.health.pending = this.pending !== null;
557
+ this.health.trackedSessions = this.checkpoint.sessions.length;
558
+ this.health.parkedSessions = this.checkpoint.parked.length;
559
+ this.health.cachedTailSessions = this.carries.size;
560
+ this.health.cachedTailBytes = [...this.carries.values()].reduce((n, row) => n + row.buffer.length, 0);
561
+ this.health.discoveryBacklog = this.candidates.length - this.candidateCursor;
562
+ const known = [...this.checkpoint.sessions, ...this.checkpoint.parked];
563
+ this.health.skippingOversizeSessions = known.filter(row => row.skippingOversize).length;
564
+ this.health.backloggedSessions = known.filter(row => row.observedSize !== undefined && row.observedSize > row.offset && !row.awaitingMore).length;
565
+ if (this.stateBytesBlocked || (this.capacityBlocked && !this.pending))
566
+ this.health.status = "capacity";
567
+ this.health.unsupportedSessions = known.filter(session => session.blocked === "unsupported_schema").length;
568
+ this.health.sourceConflicts = known.filter(session => session.blocked === "source_conflict").length;
569
+ this.health.sourceErrors = known.filter(session => session.blocked === "source_error").length;
570
+ this.health.ignoredRecords = this.recordCounters.unknown;
571
+ this.health.malformedRecords = this.recordCounters.malformed;
572
+ this.health.duplicateRecords = this.recordCounters.duplicates;
573
+ this.health.evictedCalls = this.recordCounters.callsEvicted;
574
+ this.health.unsupportedToolDetails = this.recordCounters.unsupportedDetails;
575
+ return this.snapshot();
576
+ }
577
+ }
@@ -0,0 +1,3 @@
1
+ type Flags = Record<string, string | boolean | undefined>;
2
+ export declare function runKiroCommand(args: string[], flags: Flags, out: (line: string) => void): Promise<number>;
3
+ export {};