@oaksecurity/aitm 0.0.0-stage → 2.3.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.
Files changed (63) hide show
  1. package/.env.example +11 -0
  2. package/CHANGELOG.md +100 -0
  3. package/LICENSE +21 -0
  4. package/README.md +229 -2
  5. package/SECURITY.md +49 -0
  6. package/SPEC.md +304 -0
  7. package/docs/api.md +332 -0
  8. package/docs/inputs-and-limits.md +78 -0
  9. package/docs/usage.md +351 -0
  10. package/examples/custody-architecture.md +27 -0
  11. package/package.json +67 -4
  12. package/src/api/server.js +591 -0
  13. package/src/api/web.js +38 -0
  14. package/src/application.js +32 -0
  15. package/src/assessments.js +37 -0
  16. package/src/assets/BDOGrotesk-Bold.ttf +0 -0
  17. package/src/assets/BDOGrotesk-Regular.ttf +0 -0
  18. package/src/assets/OFL.txt +93 -0
  19. package/src/assets/README.md +10 -0
  20. package/src/cli.js +224 -0
  21. package/src/client.js +88 -0
  22. package/src/config.js +105 -0
  23. package/src/doctor.js +128 -0
  24. package/src/engine/credentials.js +31 -0
  25. package/src/engine/download.js +135 -0
  26. package/src/engine/engine.js +783 -0
  27. package/src/engine/errors.js +23 -0
  28. package/src/engine/generation.js +121 -0
  29. package/src/engine/ingest.js +444 -0
  30. package/src/engine/pdf-layout.js +204 -0
  31. package/src/engine/pdf-report.js +573 -0
  32. package/src/engine/prompts.js +82 -0
  33. package/src/engine/providers.js +476 -0
  34. package/src/engine/references.js +112 -0
  35. package/src/engine/report.js +200 -0
  36. package/src/engine/schema.js +267 -0
  37. package/src/engine/store.js +115 -0
  38. package/src/engine/validate.js +397 -0
  39. package/src/engine/zip.js +70 -0
  40. package/src/index.js +5 -0
  41. package/src/source-input.js +32 -0
  42. package/src/token.js +59 -0
  43. package/src/tui/app.js +694 -0
  44. package/src/tui/editor.js +34 -0
  45. package/src/tui/file-picker.js +111 -0
  46. package/src/tui/logo.js +8 -0
  47. package/src/tui/progress.js +90 -0
  48. package/src/tui/report-reader.js +105 -0
  49. package/src/tui/select.js +63 -0
  50. package/src/tui/workbench.js +377 -0
  51. package/src/version.js +5 -0
  52. package/src/web/app.js +729 -0
  53. package/src/web/assets/BDOGrotesk-Bold.woff2 +0 -0
  54. package/src/web/assets/BDOGrotesk-Medium.woff2 +0 -0
  55. package/src/web/assets/BDOGrotesk-Regular.woff2 +0 -0
  56. package/src/web/assets/README.md +5 -0
  57. package/src/web/assets/aitm-mark.svg +12 -0
  58. package/src/web/assets/oak-white.svg +166 -0
  59. package/src/web/html.js +32 -0
  60. package/src/web/index.html +26 -0
  61. package/src/web/markdown.js +48 -0
  62. package/src/web/styles.css +1450 -0
  63. package/src/web/views.js +254 -0
@@ -0,0 +1,34 @@
1
+ import { mkdtemp, writeFile, readFile, rm } from 'node:fs/promises';
2
+ import { spawn } from 'node:child_process';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+
6
+ export async function editJSON(value, suspendTerminal) {
7
+ const directory = await mkdtemp(path.join(os.tmpdir(), 'aitm-edit-'));
8
+ const file = path.join(directory, 'artifact.json');
9
+ await writeFile(file, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
10
+ const command = process.env.VISUAL || process.env.EDITOR || 'vi';
11
+ const args = (command.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g) || []).map((s) =>
12
+ s.replace(/^(["'])(.*)\1$/, '$2'),
13
+ );
14
+ try {
15
+ await suspendTerminal(
16
+ () =>
17
+ new Promise((resolve, reject) => {
18
+ const child = spawn(args[0], [...args.slice(1), file], {
19
+ stdio: 'inherit',
20
+ shell: false,
21
+ });
22
+ child.once('error', reject);
23
+ child.once('exit', (code) =>
24
+ code === 0 ? resolve() : reject(new Error(`Editor exited with code ${code}.`)),
25
+ );
26
+ }),
27
+ );
28
+ const edited = JSON.parse(await readFile(file, 'utf8'));
29
+ await rm(directory, { recursive: true, force: true });
30
+ return edited;
31
+ } catch (error) {
32
+ throw new Error(`${error.message} Your edit is preserved at ${file}.`);
33
+ }
34
+ }
@@ -0,0 +1,111 @@
1
+ import React, { useEffect, useState } from 'react';
2
+ import { Box, Text } from 'ink';
3
+ import { readdir } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import os from 'node:os';
6
+ import { Select } from './select.js';
7
+ import { terminalText } from './logo.js';
8
+
9
+ const h = React.createElement;
10
+ export function FilePicker({
11
+ title = 'Import documents or repository ZIPs',
12
+ directory = process.cwd(),
13
+ multiple = true,
14
+ disabled = false,
15
+ onSelect,
16
+ onCancel,
17
+ }) {
18
+ const [folder, setFolder] = useState(directory),
19
+ [entries, setEntries] = useState([]),
20
+ [selected, setSelected] = useState([]),
21
+ [error, setError] = useState(''),
22
+ [loading, setLoading] = useState(true);
23
+ useEffect(() => {
24
+ let current = true;
25
+ setLoading(true);
26
+ setError('');
27
+ readdir(folder, { withFileTypes: true })
28
+ .then((items) => {
29
+ if (current)
30
+ setEntries(
31
+ items
32
+ .filter(
33
+ (e) =>
34
+ !e.isSymbolicLink() &&
35
+ !e.name.startsWith('.') &&
36
+ !['node_modules', 'vendor'].includes(e.name),
37
+ )
38
+ .sort(
39
+ (a, b) =>
40
+ Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name),
41
+ ),
42
+ );
43
+ })
44
+ .catch(() => {
45
+ if (current) {
46
+ setEntries([]);
47
+ setError('Cannot read this folder. Choose its parent or Home.');
48
+ }
49
+ })
50
+ .finally(() => {
51
+ if (current) setLoading(false);
52
+ });
53
+ return () => {
54
+ current = false;
55
+ };
56
+ }, [folder]);
57
+ const options = [
58
+ { value: ':import', label: `Import ${selected.length} selected file(s)` },
59
+ { value: ':up', label: '.. Parent folder' },
60
+ { value: ':home', label: '~ Home folder' },
61
+ ...entries.map((entry) => ({
62
+ value: entry.name,
63
+ label: entry.isDirectory()
64
+ ? `${entry.name}/`
65
+ : `${selected.includes(path.join(folder, entry.name)) ? '[x]' : '[ ]'} ${entry.name}`,
66
+ })),
67
+ ];
68
+ return h(
69
+ Box,
70
+ { flexDirection: 'column' },
71
+ h(Text, { dimColor: true, wrap: 'truncate-end' }, terminalText(folder)),
72
+ multiple
73
+ ? h(
74
+ Text,
75
+ { color: '#FFC965', wrap: 'truncate-end' },
76
+ `${selected.length} selected · Home then Enter to import`,
77
+ )
78
+ : null,
79
+ loading
80
+ ? h(Text, null, 'Reading file list…')
81
+ : h(Select, {
82
+ key: folder,
83
+ title,
84
+ disabled,
85
+ options,
86
+ hint: error || 'Enter opens a folder or imports a file. Space marks several files.',
87
+ onSelect: (value) => {
88
+ if (value === ':up') return setFolder(path.dirname(folder));
89
+ if (value === ':home') return setFolder(os.homedir());
90
+ if (value === ':import')
91
+ return selected.length
92
+ ? onSelect(selected)
93
+ : setError('Mark files with Space, or select one with Enter.');
94
+ const entry = entries.find((e) => e.name === value);
95
+ if (entry?.isDirectory()) setFolder(path.join(folder, value));
96
+ else if (entry?.isFile())
97
+ onSelect([...new Set([...selected, path.join(folder, value)])]);
98
+ },
99
+ onToggle: multiple
100
+ ? (value) => {
101
+ if (!entries.find((entry) => entry.name === value)?.isFile()) return;
102
+ const file = path.join(folder, value);
103
+ setSelected((items) =>
104
+ items.includes(file) ? items.filter((p) => p !== file) : [...items, file],
105
+ );
106
+ }
107
+ : undefined,
108
+ onCancel,
109
+ }),
110
+ );
111
+ }
@@ -0,0 +1,8 @@
1
+ export const LOGO = String.raw` _ ___ _____ __ __
2
+ / \ |_ _|_ _| \/ | o-----o
3
+ / _ \ | | | | | |\/| | |\ /|
4
+ / ___ \ | | | | | | | | | o-o |
5
+ /_/ \_\___| |_| |_| |_| o-----o`;
6
+ export const TAGLINE = 'AI Threat Modeller / TRACE / by Oak Security';
7
+ export const terminalText = (value) =>
8
+ String(value ?? '').replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, '');
@@ -0,0 +1,90 @@
1
+ import React, { useEffect, useState } from 'react';
2
+ import { Box, Text } from 'ink';
3
+ import { terminalText } from './logo.js';
4
+
5
+ const h = React.createElement;
6
+ const duration = (ms) => {
7
+ const seconds = Math.max(0, Math.floor(ms / 1000));
8
+ return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
9
+ };
10
+
11
+ export function RunProgress({ project, phases, busy, controls = true }) {
12
+ const run = project?.runs.at(-1);
13
+ const active = run && ['queued', 'running'].includes(run.status);
14
+ const [clock, setClock] = useState(Date.now());
15
+ useEffect(() => {
16
+ if (!active && !busy) return;
17
+ const timer = setInterval(() => setClock(Date.now()), 250);
18
+ return () => clearInterval(timer);
19
+ }, [active, busy]);
20
+ const spinner = ['|', '/', '-', '\\'][Math.floor(clock / 250) % 4];
21
+ if (busy)
22
+ return h(
23
+ Text,
24
+ { color: '#FFC965', wrap: 'truncate-end' },
25
+ `${spinner} ${terminalText(busy.label)} · ${duration(clock - busy.since)}`,
26
+ );
27
+ if (!run) return null;
28
+ const last = run.events.at(-1);
29
+ const current = phases.find((p) => p.id === run.phase);
30
+ const request = run.events.findLast((e) => e.type === 'request' && e.phase === run.phase);
31
+ const completed = phases.filter((p) => project.artifacts[p.id]).length;
32
+ const reviewCount = phases.reduce(
33
+ (count, phase) => count + (project.artifacts[phase.id]?.reviewNotes?.length || 0),
34
+ 0,
35
+ );
36
+ const count = Math.max(1, phases.length);
37
+ const filled = Math.round((12 * completed) / count);
38
+ const elapsed = duration(
39
+ (active ? clock : Date.parse(run.finishedAt || run.createdAt)) -
40
+ Date.parse(run.startedAt || run.createdAt),
41
+ );
42
+ const heading = active
43
+ ? `${spinner} ${current ? `Phase ${phases.indexOf(current) + 1}/${count}: ${current.title}` : 'Preparing pipeline'}`
44
+ : run.status === 'completed'
45
+ ? 'Run complete — results ready for review'
46
+ : run.status === 'awaiting_review'
47
+ ? `Review required: ${current?.title || run.phase} · a Approve, r Continue`
48
+ : run.status === 'failed'
49
+ ? `TRACE paused at ${current?.title || run.phase || 'this step'} · f Continue · l Details`
50
+ : `${run.status.toUpperCase()}: ${run.error || 'Completed artifacts are saved. Press f to resume.'}`;
51
+ let activity = '';
52
+ if (active) {
53
+ activity =
54
+ last?.type === 'progress'
55
+ ? last.characters > 0
56
+ ? `Receiving output · ${last.characters.toLocaleString()} characters`
57
+ : 'Provider connected · waiting for output'
58
+ : last?.type === 'validating'
59
+ ? 'Validating evidence and references'
60
+ : last?.type === 'validation_retry'
61
+ ? 'Checking this step again before continuing'
62
+ : last?.type === 'request'
63
+ ? `Waiting for provider response · attempt ${request?.attempt || last.attempt || 1}/2`
64
+ : last?.message || 'Starting the next phase';
65
+ if (request?.batches > 1) activity += ` · source batch ${request.batch}/${request.batches}`;
66
+ activity += request ? ` · ${request.provider}/${request.model}` : '';
67
+ }
68
+ return h(
69
+ Box,
70
+ { flexDirection: 'column' },
71
+ h(
72
+ Text,
73
+ { color: run.status === 'failed' ? 'red' : '#FFC965', bold: true, wrap: 'truncate-end' },
74
+ terminalText(heading),
75
+ ),
76
+ h(
77
+ Text,
78
+ { wrap: 'truncate-end' },
79
+ `[${'#'.repeat(filled)}${'-'.repeat(12 - filled)}] ${completed}/${count} phases ready · ${elapsed} elapsed${active && run.phaseStartedAt ? ` · phase ${duration(clock - Date.parse(run.phaseStartedAt))}` : ''}${reviewCount ? ` · ${reviewCount} source review note(s)` : ''}`,
80
+ ),
81
+ active ? h(Text, { wrap: 'truncate-end' }, terminalText(activity)) : null,
82
+ active
83
+ ? h(
84
+ Text,
85
+ { dimColor: true, wrap: 'truncate-end' },
86
+ `Last update ${last ? duration(clock - Date.parse(last.at)) : '0s'} ago · ${controls ? 'c Cancel · l Run log · q Save & quit' : 'Esc Return to pipeline controls'}`,
87
+ )
88
+ : null,
89
+ );
90
+ }
@@ -0,0 +1,105 @@
1
+ import React, { useEffect, useMemo, useState } from 'react';
2
+ import { Box, Text, useInput } from 'ink';
3
+ import { markdownReport } from '../engine/report.js';
4
+ import { terminalText } from './logo.js';
5
+
6
+ const h = React.createElement;
7
+ const plain = (value) =>
8
+ terminalText(value)
9
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
10
+ .replace(/<br>/g, '\n')
11
+ .replace(/\\\|/g, '|');
12
+
13
+ // Use the same assembled report as exports. Wide tables become readable records.
14
+ export function reportLines(markdown, width) {
15
+ const lines = [];
16
+ let headers = null;
17
+ const add = (value, level = 0) => {
18
+ for (let text of plain(value).split('\n')) {
19
+ while (text.length > width) {
20
+ const space = text.lastIndexOf(' ', width);
21
+ const end = space > 0 ? space : width;
22
+ lines.push({ text: text.slice(0, end), level });
23
+ text = text.slice(end).trimStart();
24
+ }
25
+ lines.push({ text, level });
26
+ }
27
+ };
28
+ const source = markdown.split('\n');
29
+ const separator = /^\|(?:\s*:?-+:?\s*\|)+$/;
30
+ for (const [index, line] of source.entries()) {
31
+ if (headers && separator.test(line)) continue;
32
+ if (line.startsWith('|') && (headers || separator.test(source[index + 1] || ''))) {
33
+ const cells = line
34
+ .slice(1, -1)
35
+ .split(/(?<!\\)\|/)
36
+ .map((value) => value.trim());
37
+ if (!headers) headers = cells;
38
+ else {
39
+ for (const [index, value] of cells.entries()) add(`${headers[index]}: ${value}`);
40
+ add('');
41
+ }
42
+ continue;
43
+ }
44
+ headers = null;
45
+ const heading = /^(#{1,3})\s+(.*)$/.exec(line);
46
+ if (heading) add(heading[2], heading[1].length);
47
+ else add(line);
48
+ }
49
+ return lines;
50
+ }
51
+
52
+ export function ReportReader({ project, width, height, reviewCount = 0 }) {
53
+ const lines = useMemo(() => reportLines(markdownReport(project), width), [project, width]);
54
+ const [offset, setOffset] = useState(0);
55
+ useEffect(() => setOffset(0), [project.id, project.artifacts.report.generatedAt]);
56
+ const page = Math.max(1, height - 2);
57
+ const last = Math.max(0, lines.length - page);
58
+ const start = Math.min(offset, last);
59
+ useInput((input, key) => {
60
+ if (input === 'j') setOffset(Math.min(last, start + 1));
61
+ if (input === 'k') setOffset(Math.max(0, start - 1));
62
+ if (key.pageDown || input === ' ') setOffset(Math.min(last, start + page));
63
+ if (key.pageUp) setOffset(Math.max(0, start - page));
64
+ if (key.home) setOffset(0);
65
+ if (key.end) setOffset(last);
66
+ if (input === ']') {
67
+ const next = lines.findIndex((line, index) => index > start && line.level === 2);
68
+ setOffset(next < 0 ? last : Math.min(last, next));
69
+ }
70
+ if (input === '[') {
71
+ const previous = lines.findLastIndex((line, index) => index < start && line.level === 2);
72
+ setOffset(Math.max(0, previous));
73
+ }
74
+ });
75
+ return h(
76
+ Box,
77
+ { flexDirection: 'column', height },
78
+ h(
79
+ Text,
80
+ { color: '#D85CB4', bold: true, wrap: 'truncate-end' },
81
+ `Markdown report · ${project.runs.at(-1)?.status === 'completed' ? 'Run complete' : 'Ready for review'}${reviewCount ? ` · ${reviewCount} source review note(s)` : ''} · ${start + 1}–${Math.min(lines.length, start + page)}/${lines.length}`,
82
+ ),
83
+ h(
84
+ Box,
85
+ { flexDirection: 'column', flexGrow: 1 },
86
+ ...lines.slice(start, start + page).map((line, i) =>
87
+ h(
88
+ Text,
89
+ {
90
+ key: i,
91
+ bold: Boolean(line.level),
92
+ color: line.level ? '#FFC965' : undefined,
93
+ wrap: 'truncate-end',
94
+ },
95
+ line.text || ' ',
96
+ ),
97
+ ),
98
+ ),
99
+ h(
100
+ Text,
101
+ { dimColor: true, wrap: 'truncate-end' },
102
+ 'j/k Scroll · PgUp/PgDn Page · [/] Section · Esc Menu',
103
+ ),
104
+ );
105
+ }
@@ -0,0 +1,63 @@
1
+ import React, { useState } from 'react';
2
+ import { Box, Text, useInput, useWindowSize } from 'ink';
3
+ import { terminalText } from './logo.js';
4
+
5
+ const h = React.createElement;
6
+
7
+ export function Select({
8
+ title,
9
+ options,
10
+ value,
11
+ hint,
12
+ onSelect,
13
+ onCancel,
14
+ onToggle,
15
+ disabled = false,
16
+ }) {
17
+ const [index, setIndex] = useState(
18
+ Math.max(
19
+ 0,
20
+ options.findIndex((option) => option.value === value),
21
+ ),
22
+ );
23
+ const { rows = 30 } = useWindowSize();
24
+ const page = Math.max(3, Math.min(8, rows - 16));
25
+ const start = Math.max(0, Math.min(index - Math.floor(page / 2), options.length - page));
26
+ useInput(
27
+ (input, key) => {
28
+ if (key.escape) return onCancel();
29
+ if (key.upArrow) setIndex((i) => Math.max(0, i - 1));
30
+ if (key.downArrow) setIndex((i) => Math.min(options.length - 1, i + 1));
31
+ if (key.pageUp) setIndex((i) => Math.max(0, i - page));
32
+ if (key.pageDown) setIndex((i) => Math.min(options.length - 1, i + page));
33
+ if (key.home) setIndex(0);
34
+ if (key.end) setIndex(options.length - 1);
35
+ if (key.return && options[index]) onSelect(options[index].value);
36
+ if (input === ' ' && options[index]) onToggle?.(options[index].value);
37
+ },
38
+ { isActive: !disabled },
39
+ );
40
+ return h(
41
+ Box,
42
+ { flexDirection: 'column', borderStyle: 'round', borderColor: '#FFC965', paddingX: 1 },
43
+ h(Text, { bold: true, color: '#FFC965', wrap: 'truncate-end' }, terminalText(title)),
44
+ hint ? h(Text, { dimColor: true, wrap: 'truncate-end' }, terminalText(hint)) : null,
45
+ ...options.slice(start, start + page).map((option, offset) =>
46
+ h(
47
+ Text,
48
+ {
49
+ key: option.value,
50
+ color: start + offset === index ? '#FFC965' : undefined,
51
+ bold: start + offset === index,
52
+ wrap: 'truncate-end',
53
+ },
54
+ `${start + offset === index ? '>' : ' '} ${terminalText(option.label)}`,
55
+ ),
56
+ ),
57
+ h(
58
+ Text,
59
+ { dimColor: true },
60
+ `Up/Down · Enter Select · ${onToggle ? 'Space Mark · ' : ''}Esc Cancel · ${index + 1}/${options.length}`,
61
+ ),
62
+ );
63
+ }