agenttrace-journal 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +73 -2
- package/bin/agenttrace.js +32 -0
- package/bin/server.js +197 -0
- package/dist/capture.d.ts +6 -0
- package/dist/capture.js +69 -0
- package/dist/files.d.ts +1 -0
- package/dist/files.js +37 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +246 -0
- package/dist/store.d.ts +12 -0
- package/dist/store.js +42 -0
- package/dist/types.d.ts +109 -0
- package/dist/types.js +1 -0
- package/package.json +34 -4
- package/viewer/app.js +481 -0
- package/viewer/index.html +341 -0
- package/viewer/style.css +97 -0
- package/viewer/trace-data.js +124 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AgentTrace contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,74 @@
|
|
|
1
|
-
#
|
|
1
|
+
# AgentTrace
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
AgentTrace records what a Node.js agent did and shows the evidence in a local browser viewer. Instrument a run and its tool boundaries to capture nested tool calls, command exit codes, changes to tracked files, model usage, decisions, and verification checks.
|
|
4
|
+
|
|
5
|
+
## Try it
|
|
6
|
+
|
|
7
|
+
Requires Node.js 22 or later and an ESM application. From this repository:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm ci
|
|
11
|
+
npm run build
|
|
12
|
+
npm run viewer
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Open the loopback URL printed by the CLI. The viewer starts empty and updates as your agent writes trace journals to the selected directory.
|
|
16
|
+
|
|
17
|
+
To install a release tarball in another project, run `npm install /absolute/path/to/agenttrace-journal-0.1.0.tgz`. Build a tarball with `npm pack`. Run `npx agenttrace view` from the agent's project directory to open its traces.
|
|
18
|
+
|
|
19
|
+
## Instrument a run
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
23
|
+
import { createTracer } from 'agenttrace-journal';
|
|
24
|
+
|
|
25
|
+
const trace = createTracer({ directory: '.agenttrace' });
|
|
26
|
+
const writeReport = trace.wrapTool('write report', async (rows: string[]) => {
|
|
27
|
+
await trace.trackFiles(['report.json'], () =>
|
|
28
|
+
writeFile('report.json', JSON.stringify({ rows })),
|
|
29
|
+
);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
await trace.run('Refresh report', async () => {
|
|
33
|
+
trace.note('Write the report, then verify the artifact.');
|
|
34
|
+
await writeReport(['first row']);
|
|
35
|
+
|
|
36
|
+
await trace.command(process.execPath, ['--version']);
|
|
37
|
+
await trace.check('Report contains rows', async () => {
|
|
38
|
+
const report = JSON.parse(await readFile('report.json', 'utf8'));
|
|
39
|
+
return Array.isArray(report.rows) && report.rows.length > 0;
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
A run retains the callback's return value and rethrows its original error. A recorded failed check marks the run failed even when the callback handles the error. A run also records failure if any instrumented operations are still pending when its callback settles. Handled tool or command failures remain visible in the log. Await the instrumented operations that belong to the run and add checks for the outputs that establish whether your task succeeded.
|
|
45
|
+
|
|
46
|
+
## SDK
|
|
47
|
+
|
|
48
|
+
| API | Capture behavior |
|
|
49
|
+
| --- | --- |
|
|
50
|
+
| `run(name, work)` | Creates a trace, scopes nested calls using async context, and drains writes before settling. Await the work that belongs to the run. |
|
|
51
|
+
| `tool(name, work, input?)` | Records timing, nesting and outcome around a callback. Use it inside an existing tool handler to preserve that handler's signature. |
|
|
52
|
+
| `wrapTool(name, handler)` | Returns an async wrapper that records timing, nesting and outcome on every invocation. |
|
|
53
|
+
| `command(executable, args?, options?)` | Executes a binary with an argument array and records its exit status. Returns stdout and stderr to the caller. Supports `cwd`, `timeoutMs`, `signal` and `files`. A nonzero exit or launch error rejects with `CommandFailedError`. Output buffering is capped at 1 MiB per stream. |
|
|
54
|
+
| `trackFiles(paths, work, cwd?)` | Records creation, modification or deletion by comparing SHA-256 fingerprints of explicit regular files before and after the callback. Supports up to 64 paths and 8 MiB per file. Transient writes between snapshots can go unseen. |
|
|
55
|
+
| `check(name, verify)` | Records an output assertion. Returning `false` throws `CheckFailedError`. An assertion that throws retains its original error. |
|
|
56
|
+
| `note(message)` | Records an application-supplied decision, plan or reasoning summary. |
|
|
57
|
+
| `reportSuccess(message)` | Records the agent's explicit success statement. The viewer pairs it with a failed verification when both are recorded. |
|
|
58
|
+
| `usage(usage)` | Records provider-reported input/output tokens and optional USD cost. |
|
|
59
|
+
| `traceId()` | Returns the ID of the active run for correlation. |
|
|
60
|
+
|
|
61
|
+
Pass `rates: { [model]: { inputUsdPerMillion, outputUsdPerMillion } }` to estimate cost when the provider supplies tokens alone. An explicit `costUsd` takes precedence. The viewer shows the count of unpriced requests alongside any known subtotal. Supply provider totals when pricing includes caching, reasoning, or other categories beyond the two token rates.
|
|
62
|
+
|
|
63
|
+
## Local data and limits
|
|
64
|
+
|
|
65
|
+
- Traces are versioned NDJSON in `.agenttrace/` by default. Add that directory to your application's Git ignore rules. Each run gets a separate journal. The viewer can open a journal while the agent is running and labels journals without a terminal event as unfinished.
|
|
66
|
+
- Capture is limited to calls routed through the SDK and files explicitly listed by the application. Each run retains up to 2,000 records before the terminal summary. The summary reports dropped records. Failed storage writes emit an AgentTrace warning by default or call `onError` when configured.
|
|
67
|
+
- Tool inputs and outputs, command arguments, and error messages require `capturePayloads: true`. Run/tool names, paths, notes and model names are recorded by default. Use the `redact` callback and review sensitive inputs before enabling payload capture. Command output and file contents stay outside the journal.
|
|
68
|
+
- Use `agenttrace view --dir /path/to/traces --port 4318`. The viewer binds to `127.0.0.1`, reads from the selected directory, and exports selected traces as JSON. Local processes can access the viewer while it runs. Keep the journal directory and any exports under your application's retention and access controls.
|
|
69
|
+
|
|
70
|
+
## Development
|
|
71
|
+
|
|
72
|
+
Run `npm test` to build the TypeScript package and exercise SDK behavior and the local viewer API. Run `npm pack --dry-run` to inspect package contents. The consumer package has zero runtime dependencies.
|
|
73
|
+
|
|
74
|
+
MIT licensed.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { startViewer } from './server.js';
|
|
5
|
+
|
|
6
|
+
const help = `Usage
|
|
7
|
+
agenttrace view [--dir .agenttrace] [--port 4318]
|
|
8
|
+
|
|
9
|
+
The viewer listens on 127.0.0.1. Use --port 0 to choose a free port.`;
|
|
10
|
+
|
|
11
|
+
try {
|
|
12
|
+
const args = parseArgs({
|
|
13
|
+
allowPositionals: true,
|
|
14
|
+
options: { dir: { type: 'string' }, port: { type: 'string' }, help: { type: 'boolean', short: 'h' } },
|
|
15
|
+
});
|
|
16
|
+
const [command, extra] = args.positionals;
|
|
17
|
+
const directory = resolve(args.values.dir ?? '.agenttrace');
|
|
18
|
+
if (args.values.help || !command) {
|
|
19
|
+
console.log(help);
|
|
20
|
+
} else if (extra || command !== 'view') {
|
|
21
|
+
throw new Error(help);
|
|
22
|
+
} else {
|
|
23
|
+
const port = args.values.port ?? '4318';
|
|
24
|
+
if (!/^\d+$/.test(port) || Number(port) > 65535) throw new Error('Port must be an integer from 0 to 65535');
|
|
25
|
+
const server = await startViewer(directory, Number(port));
|
|
26
|
+
console.log('AgentTrace at http://127.0.0.1:' + server.address().port);
|
|
27
|
+
console.log('Reading ' + directory);
|
|
28
|
+
}
|
|
29
|
+
} catch (error) {
|
|
30
|
+
console.error('AgentTrace: ' + error.message);
|
|
31
|
+
process.exitCode = 1;
|
|
32
|
+
}
|
package/bin/server.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { open, readFile, readdir } from 'node:fs/promises';
|
|
3
|
+
import { createServer } from 'node:http';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
|
|
6
|
+
const ID = /^[a-f0-9]{8}-[a-f0-9]{4}-[47][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
|
|
7
|
+
const SAMPLE = 8192;
|
|
8
|
+
const MAX_BYTES = 12 * 1024 * 1024;
|
|
9
|
+
const PAGE_SIZE = 60;
|
|
10
|
+
const TOTAL_COUNTS = ['inputTokens', 'outputTokens', 'pricedRequests', 'unpricedRequests',
|
|
11
|
+
'failedOperations', 'failedChecks', 'droppedEvents', 'events'];
|
|
12
|
+
const assets = new Map([
|
|
13
|
+
['/', ['index.html', 'text/html; charset=utf-8']],
|
|
14
|
+
['/app.js', ['app.js', 'text/javascript; charset=utf-8']],
|
|
15
|
+
['/trace-data.js', ['trace-data.js', 'text/javascript; charset=utf-8']],
|
|
16
|
+
['/style.css', ['style.css', 'text/css; charset=utf-8']],
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
async function readAt(file, bytes, offset) {
|
|
20
|
+
const buffer = Buffer.alloc(bytes);
|
|
21
|
+
let read = 0;
|
|
22
|
+
while (read < bytes) {
|
|
23
|
+
const { bytesRead } = await file.read(buffer, read, bytes - read, offset + read);
|
|
24
|
+
if (!bytesRead) break;
|
|
25
|
+
read += bytesRead;
|
|
26
|
+
}
|
|
27
|
+
return buffer.subarray(0, read).toString('utf8');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const text = (value) => typeof value === 'string';
|
|
31
|
+
const optionalText = (value) => value === undefined || text(value);
|
|
32
|
+
const nonnegative = (value) => Number.isFinite(value) && value >= 0;
|
|
33
|
+
const count = (value) => Number.isSafeInteger(value) && value >= 0;
|
|
34
|
+
const isStatus = (value) => value === 'passed' || value === 'failed';
|
|
35
|
+
|
|
36
|
+
function validEvent(event) {
|
|
37
|
+
if (!event || !text(event.at) || !Number.isFinite(Date.parse(event.at)) ||
|
|
38
|
+
!nonnegative(event.offsetMs) || !optionalText(event.parentId)) return false;
|
|
39
|
+
switch (event.type) {
|
|
40
|
+
case 'run.start': return event.version === 1 && text(event.id) && text(event.name);
|
|
41
|
+
case 'run.end': {
|
|
42
|
+
const { totals } = event;
|
|
43
|
+
return isStatus(event.status) && optionalText(event.error) && totals &&
|
|
44
|
+
TOTAL_COUNTS.every((key) => count(totals[key])) && nonnegative(totals.costUsd) &&
|
|
45
|
+
(totals.pendingOperations === undefined || count(totals.pendingOperations));
|
|
46
|
+
}
|
|
47
|
+
case 'span.start': return text(event.id) && text(event.name) && ['tool', 'command', 'check'].includes(event.kind);
|
|
48
|
+
case 'span.end': return text(event.id) && isStatus(event.status) && nonnegative(event.elapsedMs) && optionalText(event.error);
|
|
49
|
+
case 'note':
|
|
50
|
+
case 'claim': return text(event.message);
|
|
51
|
+
case 'usage': {
|
|
52
|
+
const { model, inputTokens, outputTokens, costUsd } = event.usage ?? {};
|
|
53
|
+
return text(model) && count(inputTokens) && count(outputTokens) && (costUsd === undefined || nonnegative(costUsd));
|
|
54
|
+
}
|
|
55
|
+
case 'file': return text(event.path) && ['created', 'modified', 'deleted'].includes(event.change) &&
|
|
56
|
+
optionalText(event.before) && optionalText(event.after);
|
|
57
|
+
case 'command.exit': return (event.code === null || Number.isSafeInteger(event.code)) &&
|
|
58
|
+
(event.signal === null || text(event.signal));
|
|
59
|
+
case 'capture.error': return text(event.operation);
|
|
60
|
+
default: return false;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function parse(line) {
|
|
65
|
+
try {
|
|
66
|
+
const event = JSON.parse(line);
|
|
67
|
+
return validEvent(event) ? event : null;
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function readTrace(directory, id, detail, query = '') {
|
|
74
|
+
const file = await open(join(directory, id + '.ndjson'),
|
|
75
|
+
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
76
|
+
try {
|
|
77
|
+
const stat = await file.stat();
|
|
78
|
+
if (!stat.isFile() || stat.size > MAX_BYTES) return null;
|
|
79
|
+
const beginning = await readAt(file, Math.min(SAMPLE, stat.size), 0);
|
|
80
|
+
const firstNewline = beginning.indexOf('\n');
|
|
81
|
+
if (firstNewline === -1) return null;
|
|
82
|
+
const start = parse(beginning.slice(0, firstNewline));
|
|
83
|
+
if (start?.type !== 'run.start' || start.id !== id) return null;
|
|
84
|
+
if (query && !id.includes(query) && !start.name.toLowerCase().includes(query)) return null;
|
|
85
|
+
|
|
86
|
+
const remaining = detail ? stat.size : Math.min(SAMPLE, stat.size);
|
|
87
|
+
const body = await readAt(file, remaining, stat.size - remaining);
|
|
88
|
+
const lines = body.split('\n');
|
|
89
|
+
lines.pop(); // Ignore a partially written final line.
|
|
90
|
+
if (remaining !== stat.size) lines.shift();
|
|
91
|
+
const end = parse(lines.at(-1));
|
|
92
|
+
const complete = end?.type === 'run.end';
|
|
93
|
+
const summary = {
|
|
94
|
+
id, name: start.name, startedAt: start.at, updatedAt: stat.mtime.toISOString(),
|
|
95
|
+
status: complete ? end.status : 'open',
|
|
96
|
+
durationMs: complete ? end.offsetMs : null,
|
|
97
|
+
totals: complete ? end.totals : null,
|
|
98
|
+
error: complete ? end.error : undefined,
|
|
99
|
+
};
|
|
100
|
+
if (!detail) return summary;
|
|
101
|
+
const events = lines.map(parse).filter(Boolean);
|
|
102
|
+
return { ...summary, events, malformedLines: lines.length - events.length };
|
|
103
|
+
} finally {
|
|
104
|
+
await file.close();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function list(directory, cursor, query) {
|
|
109
|
+
let entries;
|
|
110
|
+
try {
|
|
111
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (error.code === 'ENOENT') return { traces: [], next: null, total: 0, directory };
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
// Time-ordered run IDs keep newly started runs on the first page.
|
|
117
|
+
const ids = entries.filter((entry) => entry.isFile() && entry.name.endsWith('.ndjson'))
|
|
118
|
+
.map((entry) => entry.name.slice(0, -7)).filter((id) => ID.test(id)).sort().reverse();
|
|
119
|
+
let index = cursor ? ids.findIndex((id) => id < cursor) : 0;
|
|
120
|
+
if (index === -1) index = ids.length;
|
|
121
|
+
const traces = [];
|
|
122
|
+
while (index < ids.length && traces.length <= PAGE_SIZE) {
|
|
123
|
+
const batch = ids.slice(index, index + Math.min(8, PAGE_SIZE + 1 - traces.length));
|
|
124
|
+
const items = await Promise.all(batch.map((id) => readTrace(directory, id, false, query).catch((error) => {
|
|
125
|
+
if (['ENOENT', 'ELOOP', 'EACCES'].includes(error.code)) return null;
|
|
126
|
+
throw error;
|
|
127
|
+
})));
|
|
128
|
+
traces.push(...items.filter(Boolean));
|
|
129
|
+
index += batch.length;
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
next: traces.length > PAGE_SIZE ? traces[PAGE_SIZE - 1].id : null,
|
|
133
|
+
traces: traces.slice(0, PAGE_SIZE),
|
|
134
|
+
total: ids.length,
|
|
135
|
+
directory,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function startViewer(directory, port) {
|
|
140
|
+
const server = createServer(async (request, response) => {
|
|
141
|
+
response.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self'; style-src 'self' https://fonts.googleapis.com; style-src-attr 'unsafe-inline'; font-src https://fonts.gstatic.com; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'");
|
|
142
|
+
response.setHeader('X-Content-Type-Options', 'nosniff');
|
|
143
|
+
response.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
|
|
144
|
+
response.setHeader('Referrer-Policy', 'no-referrer');
|
|
145
|
+
response.setHeader('Cache-Control', 'no-store');
|
|
146
|
+
|
|
147
|
+
function send(status, data, type = 'application/json; charset=utf-8') {
|
|
148
|
+
response.writeHead(status, { 'Content-Type': type });
|
|
149
|
+
response.end(type.startsWith('application/json') ? JSON.stringify(data) : data);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const host = '127.0.0.1:' + server.address()?.port;
|
|
153
|
+
if (request.headers.host !== host || request.headers['sec-fetch-site'] === 'cross-site' ||
|
|
154
|
+
(request.headers.origin && request.headers.origin !== 'http://' + host)) {
|
|
155
|
+
return send(403, { error: 'Open the local viewer URL printed by AgentTrace' });
|
|
156
|
+
}
|
|
157
|
+
if (request.method !== 'GET') {
|
|
158
|
+
response.setHeader('Allow', 'GET');
|
|
159
|
+
return send(405, { error: 'Use GET' });
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
try {
|
|
163
|
+
const url = new URL(request.url, 'http://' + host);
|
|
164
|
+
if (url.pathname === '/api/traces') {
|
|
165
|
+
const cursor = url.searchParams.get('after');
|
|
166
|
+
const query = (url.searchParams.get('q') ?? '').trim();
|
|
167
|
+
if (cursor !== null && !ID.test(cursor)) return send(400, { error: 'Invalid page cursor' });
|
|
168
|
+
if (query.length > 256) return send(400, { error: 'Search query is too long' });
|
|
169
|
+
return send(200, await list(directory, cursor, query.toLowerCase()));
|
|
170
|
+
}
|
|
171
|
+
const detail = /^\/api\/traces\/([^/]+)$/.exec(url.pathname);
|
|
172
|
+
if (detail && ID.test(detail[1])) {
|
|
173
|
+
const trace = await readTrace(directory, detail[1], true).catch((error) => {
|
|
174
|
+
if (['ENOENT', 'ELOOP', 'EACCES'].includes(error.code)) return null;
|
|
175
|
+
throw error;
|
|
176
|
+
});
|
|
177
|
+
return trace ? send(200, trace) : send(404, { error: 'Trace unavailable' });
|
|
178
|
+
}
|
|
179
|
+
const asset = assets.get(url.pathname);
|
|
180
|
+
if (asset) return send(200, await readFile(new URL('../viewer/' + asset[0], import.meta.url)), asset[1]);
|
|
181
|
+
return send(404, { error: 'Page unavailable' });
|
|
182
|
+
} catch (error) {
|
|
183
|
+
console.error('AgentTrace viewer:', error.code ?? error.name);
|
|
184
|
+
if (!response.headersSent) send(500, { error: 'Could not read the trace directory' });
|
|
185
|
+
else response.destroy();
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
server.requestTimeout = 10_000;
|
|
189
|
+
server.headersTimeout = 5_000;
|
|
190
|
+
return new Promise((accept, reject) => {
|
|
191
|
+
server.once('error', reject);
|
|
192
|
+
server.listen(port, '127.0.0.1', () => {
|
|
193
|
+
server.removeListener('error', reject);
|
|
194
|
+
accept(server);
|
|
195
|
+
});
|
|
196
|
+
});
|
|
197
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Json, TraceOptions } from './types.js';
|
|
2
|
+
export declare function createCapture(redact: TraceOptions['redact']): {
|
|
3
|
+
clean: (value: string, limit?: number) => string;
|
|
4
|
+
payload: (value: unknown) => Json;
|
|
5
|
+
commandArgs: (args: readonly string[]) => string[];
|
|
6
|
+
};
|
package/dist/capture.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
const SECRET_KEY = /^token$|password|passphrase|secret|credential|authorization|cookie|api.?key|access.?token|refresh.?token|private.?key/i;
|
|
2
|
+
const SECRET_TEXT = /\b(?:Bearer\s+[\w.+/=-]+|(?:sk-(?:proj-)?|gh[pousr]_|github_pat_|xox[baprs]-)[\w-]{8,}|(?:api[_-]?key|password|secret|access[_-]?token)\s*[:=]\s*[^\s,;]+)/gi;
|
|
3
|
+
export function createCapture(redact) {
|
|
4
|
+
function clean(value, limit = 256) {
|
|
5
|
+
const sanitize = (input) => input.replace(SECRET_TEXT, '[redacted]');
|
|
6
|
+
try {
|
|
7
|
+
return sanitize(redact ? redact(sanitize(value)) : value).slice(0, limit);
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return '[redaction failed]';
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function payload(value) {
|
|
14
|
+
const seen = new WeakSet();
|
|
15
|
+
let budget = 60;
|
|
16
|
+
function visit(item, depth) {
|
|
17
|
+
if (--budget < 0 || depth > 4)
|
|
18
|
+
return '[truncated]';
|
|
19
|
+
if (typeof item === 'string')
|
|
20
|
+
return clean(item);
|
|
21
|
+
if (typeof item === 'number')
|
|
22
|
+
return Number.isFinite(item) ? item : null;
|
|
23
|
+
if (typeof item === 'boolean' || item === null)
|
|
24
|
+
return item;
|
|
25
|
+
if (typeof item === 'bigint')
|
|
26
|
+
return String(item);
|
|
27
|
+
if (typeof item !== 'object')
|
|
28
|
+
return '[' + typeof item + ']';
|
|
29
|
+
if (seen.has(item))
|
|
30
|
+
return '[reference]';
|
|
31
|
+
seen.add(item);
|
|
32
|
+
if (Array.isArray(item)) {
|
|
33
|
+
return Array.from({ length: Math.min(item.length, 12) }, (_, index) => {
|
|
34
|
+
const descriptor = Object.getOwnPropertyDescriptor(item, index);
|
|
35
|
+
return descriptor && 'value' in descriptor ? visit(descriptor.value, depth + 1) : '[unavailable]';
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
const result = Object.create(null);
|
|
39
|
+
for (const key of Object.keys(item).slice(0, 12)) {
|
|
40
|
+
const descriptor = Object.getOwnPropertyDescriptor(item, key);
|
|
41
|
+
result[clean(key, 64)] = SECRET_KEY.test(key)
|
|
42
|
+
? '[redacted]'
|
|
43
|
+
: descriptor && 'value' in descriptor ? visit(descriptor.value, depth + 1) : '[accessor]';
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
const captured = visit(value, 0);
|
|
49
|
+
return Buffer.byteLength(JSON.stringify(captured)) <= 4096 ? captured : '[payload exceeded 4 KiB]';
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return '[unavailable]';
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function commandArgs(args) {
|
|
56
|
+
let sensitive = false;
|
|
57
|
+
return args.slice(0, 12).map((arg) => {
|
|
58
|
+
const hide = sensitive;
|
|
59
|
+
const flag = /^--?([^=]+)(?:=|$)/.exec(arg);
|
|
60
|
+
sensitive = Boolean(flag && !arg.includes('=') && SECRET_KEY.test(flag[1] ?? ''));
|
|
61
|
+
if (hide)
|
|
62
|
+
return '[redacted]';
|
|
63
|
+
if (flag && SECRET_KEY.test(flag[1] ?? '') && arg.includes('='))
|
|
64
|
+
return flag[1] + '=[redacted]';
|
|
65
|
+
return arg;
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return { clean, payload, commandArgs };
|
|
69
|
+
}
|
package/dist/files.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function fingerprint(path: string): Promise<string | undefined>;
|
package/dist/files.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { open } from 'node:fs/promises';
|
|
4
|
+
const MAX_FILE_BYTES = 8 * 1024 * 1024;
|
|
5
|
+
export async function fingerprint(path) {
|
|
6
|
+
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
|
|
7
|
+
.catch((error) => {
|
|
8
|
+
if (error.code === 'ENOENT')
|
|
9
|
+
return undefined;
|
|
10
|
+
throw error;
|
|
11
|
+
});
|
|
12
|
+
if (!handle)
|
|
13
|
+
return undefined;
|
|
14
|
+
try {
|
|
15
|
+
const initial = await handle.stat();
|
|
16
|
+
if (!initial.isFile() || initial.size > MAX_FILE_BYTES)
|
|
17
|
+
throw new Error('Unsupported file type or size');
|
|
18
|
+
const hash = createHash('sha256');
|
|
19
|
+
const buffer = Buffer.allocUnsafe(64 * 1024);
|
|
20
|
+
let bytes = 0;
|
|
21
|
+
while (bytes <= MAX_FILE_BYTES) {
|
|
22
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, bytes);
|
|
23
|
+
if (!bytesRead)
|
|
24
|
+
break;
|
|
25
|
+
bytes += bytesRead;
|
|
26
|
+
hash.update(buffer.subarray(0, bytesRead));
|
|
27
|
+
}
|
|
28
|
+
const final = await handle.stat();
|
|
29
|
+
if (bytes > MAX_FILE_BYTES || final.size !== initial.size || final.mtimeMs !== initial.mtimeMs ||
|
|
30
|
+
final.ctimeMs !== initial.ctimeMs || final.size !== bytes)
|
|
31
|
+
throw new Error('File changed during capture');
|
|
32
|
+
return hash.digest('hex');
|
|
33
|
+
}
|
|
34
|
+
finally {
|
|
35
|
+
await handle.close();
|
|
36
|
+
}
|
|
37
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { CommandOptions, CommandResult, TraceOptions, Usage } from './types.js';
|
|
2
|
+
export type * from './types.js';
|
|
3
|
+
type Awaitable<T> = T | PromiseLike<T>;
|
|
4
|
+
export declare class CheckFailedError extends Error {
|
|
5
|
+
constructor(message?: string);
|
|
6
|
+
}
|
|
7
|
+
export declare class CommandFailedError extends Error {
|
|
8
|
+
readonly code: number | null;
|
|
9
|
+
readonly signal: string | null;
|
|
10
|
+
readonly stdout: string;
|
|
11
|
+
readonly stderr: string;
|
|
12
|
+
constructor(code: number | null, signal: string | null, stdout: string, stderr: string, cause: Error);
|
|
13
|
+
}
|
|
14
|
+
export declare function createTracer(options?: TraceOptions): {
|
|
15
|
+
run: <T>(name: string, work: () => Awaitable<T>) => Promise<T>;
|
|
16
|
+
tool: <T>(name: string, work: () => Awaitable<T>, input?: unknown) => Promise<T>;
|
|
17
|
+
wrapTool: <This, Args extends unknown[], T>(name: string, work: (this: This, ...args: Args) => Awaitable<T>) => (this: This, ...args: Args) => Promise<T>;
|
|
18
|
+
command: (executable: string, args?: readonly string[], config?: CommandOptions) => Promise<CommandResult>;
|
|
19
|
+
trackFiles: <T>(paths: readonly string[], work: () => Awaitable<T>, cwd?: string) => Promise<T>;
|
|
20
|
+
check: (name: string, verify: () => Awaitable<boolean | void>) => Promise<void>;
|
|
21
|
+
note: (message: string) => void;
|
|
22
|
+
reportSuccess: (message: string) => void;
|
|
23
|
+
usage: (data: Usage) => void;
|
|
24
|
+
traceId: () => string | undefined;
|
|
25
|
+
};
|
|
26
|
+
export type Tracer = ReturnType<typeof createTracer>;
|