@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.
- package/.env.example +11 -0
- package/CHANGELOG.md +100 -0
- package/LICENSE +21 -0
- package/README.md +229 -2
- package/SECURITY.md +49 -0
- package/SPEC.md +304 -0
- package/docs/api.md +332 -0
- package/docs/inputs-and-limits.md +78 -0
- package/docs/usage.md +351 -0
- package/examples/custody-architecture.md +27 -0
- package/package.json +67 -4
- package/src/api/server.js +591 -0
- package/src/api/web.js +38 -0
- package/src/application.js +32 -0
- package/src/assessments.js +37 -0
- package/src/assets/BDOGrotesk-Bold.ttf +0 -0
- package/src/assets/BDOGrotesk-Regular.ttf +0 -0
- package/src/assets/OFL.txt +93 -0
- package/src/assets/README.md +10 -0
- package/src/cli.js +224 -0
- package/src/client.js +88 -0
- package/src/config.js +105 -0
- package/src/doctor.js +128 -0
- package/src/engine/credentials.js +31 -0
- package/src/engine/download.js +135 -0
- package/src/engine/engine.js +783 -0
- package/src/engine/errors.js +23 -0
- package/src/engine/generation.js +121 -0
- package/src/engine/ingest.js +444 -0
- package/src/engine/pdf-layout.js +204 -0
- package/src/engine/pdf-report.js +573 -0
- package/src/engine/prompts.js +82 -0
- package/src/engine/providers.js +476 -0
- package/src/engine/references.js +112 -0
- package/src/engine/report.js +200 -0
- package/src/engine/schema.js +267 -0
- package/src/engine/store.js +115 -0
- package/src/engine/validate.js +397 -0
- package/src/engine/zip.js +70 -0
- package/src/index.js +5 -0
- package/src/source-input.js +32 -0
- package/src/token.js +59 -0
- package/src/tui/app.js +694 -0
- package/src/tui/editor.js +34 -0
- package/src/tui/file-picker.js +111 -0
- package/src/tui/logo.js +8 -0
- package/src/tui/progress.js +90 -0
- package/src/tui/report-reader.js +105 -0
- package/src/tui/select.js +63 -0
- package/src/tui/workbench.js +377 -0
- package/src/version.js +5 -0
- package/src/web/app.js +729 -0
- package/src/web/assets/BDOGrotesk-Bold.woff2 +0 -0
- package/src/web/assets/BDOGrotesk-Medium.woff2 +0 -0
- package/src/web/assets/BDOGrotesk-Regular.woff2 +0 -0
- package/src/web/assets/README.md +5 -0
- package/src/web/assets/aitm-mark.svg +12 -0
- package/src/web/assets/oak-white.svg +166 -0
- package/src/web/html.js +32 -0
- package/src/web/index.html +26 -0
- package/src/web/markdown.js +48 -0
- package/src/web/styles.css +1450 -0
- package/src/web/views.js +254 -0
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Copyright 2020 The BDO Grotesk Project Authors (https://github.com/LCTipografi/BDO-Grotesk)
|
|
2
|
+
|
|
3
|
+
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
|
4
|
+
This license is copied below, and is also available with a FAQ at:
|
|
5
|
+
http://scripts.sil.org/OFL
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
-----------------------------------------------------------
|
|
9
|
+
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
|
10
|
+
-----------------------------------------------------------
|
|
11
|
+
|
|
12
|
+
PREAMBLE
|
|
13
|
+
The goals of the Open Font License (OFL) are to stimulate worldwide
|
|
14
|
+
development of collaborative font projects, to support the font creation
|
|
15
|
+
efforts of academic and linguistic communities, and to provide a free and
|
|
16
|
+
open framework in which fonts may be shared and improved in partnership
|
|
17
|
+
with others.
|
|
18
|
+
|
|
19
|
+
The OFL allows the licensed fonts to be used, studied, modified and
|
|
20
|
+
redistributed freely as long as they are not sold by themselves. The
|
|
21
|
+
fonts, including any derivative works, can be bundled, embedded,
|
|
22
|
+
redistributed and/or sold with any software provided that any reserved
|
|
23
|
+
names are not used by derivative works. The fonts and derivatives,
|
|
24
|
+
however, cannot be released under any other type of license. The
|
|
25
|
+
requirement for fonts to remain under this license does not apply
|
|
26
|
+
to any document created using the fonts or their derivatives.
|
|
27
|
+
|
|
28
|
+
DEFINITIONS
|
|
29
|
+
"Font Software" refers to the set of files released by the Copyright
|
|
30
|
+
Holder(s) under this license and clearly marked as such. This may
|
|
31
|
+
include source files, build scripts and documentation.
|
|
32
|
+
|
|
33
|
+
"Reserved Font Name" refers to any names specified as such after the
|
|
34
|
+
copyright statement(s).
|
|
35
|
+
|
|
36
|
+
"Original Version" refers to the collection of Font Software components as
|
|
37
|
+
distributed by the Copyright Holder(s).
|
|
38
|
+
|
|
39
|
+
"Modified Version" refers to any derivative made by adding to, deleting,
|
|
40
|
+
or substituting -- in part or in whole -- any of the components of the
|
|
41
|
+
Original Version, by changing formats or by porting the Font Software to a
|
|
42
|
+
new environment.
|
|
43
|
+
|
|
44
|
+
"Author" refers to any designer, engineer, programmer, technical
|
|
45
|
+
writer or other person who contributed to the Font Software.
|
|
46
|
+
|
|
47
|
+
PERMISSION & CONDITIONS
|
|
48
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
49
|
+
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
|
50
|
+
redistribute, and sell modified and unmodified copies of the Font
|
|
51
|
+
Software, subject to the following conditions:
|
|
52
|
+
|
|
53
|
+
1) Neither the Font Software nor any of its individual components,
|
|
54
|
+
in Original or Modified Versions, may be sold by itself.
|
|
55
|
+
|
|
56
|
+
2) Original or Modified Versions of the Font Software may be bundled,
|
|
57
|
+
redistributed and/or sold with any software, provided that each copy
|
|
58
|
+
contains the above copyright notice and this license. These can be
|
|
59
|
+
included either as stand-alone text files, human-readable headers or
|
|
60
|
+
in the appropriate machine-readable metadata fields within text or
|
|
61
|
+
binary files as long as those fields can be easily viewed by the user.
|
|
62
|
+
|
|
63
|
+
3) No Modified Version of the Font Software may use the Reserved Font
|
|
64
|
+
Name(s) unless explicit written permission is granted by the corresponding
|
|
65
|
+
Copyright Holder. This restriction only applies to the primary font name as
|
|
66
|
+
presented to the users.
|
|
67
|
+
|
|
68
|
+
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
|
69
|
+
Software shall not be used to promote, endorse or advertise any
|
|
70
|
+
Modified Version, except to acknowledge the contribution(s) of the
|
|
71
|
+
Copyright Holder(s) and the Author(s) or with their explicit written
|
|
72
|
+
permission.
|
|
73
|
+
|
|
74
|
+
5) The Font Software, modified or unmodified, in part or in whole,
|
|
75
|
+
must be distributed entirely under this license, and must not be
|
|
76
|
+
distributed under any other license. The requirement for fonts to
|
|
77
|
+
remain under this license does not apply to any document created
|
|
78
|
+
using the Font Software.
|
|
79
|
+
|
|
80
|
+
TERMINATION
|
|
81
|
+
This license becomes null and void if any of the above conditions are
|
|
82
|
+
not met.
|
|
83
|
+
|
|
84
|
+
DISCLAIMER
|
|
85
|
+
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
86
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
|
87
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
|
88
|
+
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
|
89
|
+
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
90
|
+
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
|
91
|
+
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
92
|
+
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
|
93
|
+
OTHER DEALINGS IN THE FONT SOFTWARE.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
BDO Grotesk is the existing Oak Security report typeface. These regular and bold
|
|
2
|
+
TrueType assets are the print counterparts of the web fonts used in the original
|
|
3
|
+
AiTM application. AiTM embeds subsets of these fonts in exported PDFs. No fonts
|
|
4
|
+
are fetched at runtime. The terminal uses the user's chosen terminal font.
|
|
5
|
+
|
|
6
|
+
BDO Grotesk is by Deni Anggara / Lokal Container and is licensed separately under
|
|
7
|
+
[SIL Open Font License 1.1](OFL.txt), not the application's MIT license. The bundled
|
|
8
|
+
fonts retain their embedded copyright: © 2017 Lokal Container. The accompanying
|
|
9
|
+
upstream license also credits the BDO Grotesk Project Authors (2020).
|
|
10
|
+
[Upstream font project](https://github.com/LCTipografi/BDO-Grotesk).
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { execFile } from 'node:child_process';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import { loadConfig, configureKeys } from './config.js';
|
|
7
|
+
import { Providers } from './engine/providers.js';
|
|
8
|
+
import { startApplication, openAssessment } from './application.js';
|
|
9
|
+
import { LOGO, TAGLINE, terminalText } from './tui/logo.js';
|
|
10
|
+
import { sourceInput } from './source-input.js';
|
|
11
|
+
import { VERSION } from './version.js';
|
|
12
|
+
|
|
13
|
+
const HELP = `${LOGO}\n${TAGLINE}
|
|
14
|
+
|
|
15
|
+
Usage: aitm [path-or-url] [options] Open the project chooser; a source argument is optional
|
|
16
|
+
aitm web [path-or-url] Open the web project chooser
|
|
17
|
+
aitm serve Run just the engine and local API
|
|
18
|
+
aitm configure Enter OpenAI and Anthropic keys privately
|
|
19
|
+
aitm doctor [--live] Check Node.js, Git, keys, storage and the port
|
|
20
|
+
aitm token [--rotate] Print (or replace) the private API access token
|
|
21
|
+
|
|
22
|
+
Options:
|
|
23
|
+
--project ID Open a saved project by ID
|
|
24
|
+
--full Start/resume the full pipeline with top 3 attack trees
|
|
25
|
+
--no-open With web, print the URL without opening a browser
|
|
26
|
+
--port NUMBER Local API port (default 8790)
|
|
27
|
+
--allowed-host HOST:PORT
|
|
28
|
+
Also accept this loopback Host header, for an SSH forward
|
|
29
|
+
to a different local port (for example 127.0.0.1:9000)
|
|
30
|
+
--data-dir DIR Private storage (default ~/.local/share/aitm-v2)
|
|
31
|
+
--help, -h Show this help
|
|
32
|
+
--version Show the version
|
|
33
|
+
|
|
34
|
+
Examples: aitm
|
|
35
|
+
aitm ./my-repo
|
|
36
|
+
aitm "./design notes.pdf" --full
|
|
37
|
+
aitm https://github.com/organisation/repository
|
|
38
|
+
aitm https://example.org/whitepaper.pdf
|
|
39
|
+
|
|
40
|
+
Starting without a source opens the project chooser; the current folder is never
|
|
41
|
+
imported automatically. Create/open projects and add several public URLs,
|
|
42
|
+
code/doc files or ZIP repositories through the import dialogs. An explicit source
|
|
43
|
+
argument opens an assessment containing that source; --project opens one by ID.
|
|
44
|
+
The engine, TUI and API run together. q saves and quits; unfinished work is
|
|
45
|
+
cancelled and completed steps are retained. No background server is left running.
|
|
46
|
+
Inside the TUI: o projects, n new project, i add sources, b manage sources,
|
|
47
|
+
s settings/API keys, p provider/model lists, f full pipeline,
|
|
48
|
+
v view Markdown, x export, ? help.
|
|
49
|
+
The browser and API need the private access token. AiTM prints a URL that
|
|
50
|
+
contains it. Scripts send Authorization: Bearer "$(aitm token)".
|
|
51
|
+
AI runs send source content to your selected provider. Results remain drafts
|
|
52
|
+
until reviewed. Use aitm serve for an API that runs without the TUI.
|
|
53
|
+
`;
|
|
54
|
+
|
|
55
|
+
async function withActivity(label, action) {
|
|
56
|
+
let frame = 0;
|
|
57
|
+
const draw = () =>
|
|
58
|
+
process.stdout.write(`\r\u001b[2K${['|', '/', '-', '\\'][frame++ % 4]} ${terminalText(label)}`);
|
|
59
|
+
draw();
|
|
60
|
+
const timer = setInterval(draw, 150);
|
|
61
|
+
try {
|
|
62
|
+
return await action();
|
|
63
|
+
} finally {
|
|
64
|
+
clearInterval(timer);
|
|
65
|
+
process.stdout.write('\r\u001b[2K');
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function main() {
|
|
70
|
+
const { values, positionals } = parseArgs({
|
|
71
|
+
allowPositionals: true,
|
|
72
|
+
options: {
|
|
73
|
+
help: { type: 'boolean', short: 'h' },
|
|
74
|
+
version: { type: 'boolean' },
|
|
75
|
+
port: { type: 'string' },
|
|
76
|
+
'data-dir': { type: 'string' },
|
|
77
|
+
full: { type: 'boolean' },
|
|
78
|
+
project: { type: 'string' },
|
|
79
|
+
'no-open': { type: 'boolean' },
|
|
80
|
+
'allowed-host': { type: 'string', multiple: true },
|
|
81
|
+
live: { type: 'boolean' },
|
|
82
|
+
rotate: { type: 'boolean' },
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
if (values.help) return console.log(HELP);
|
|
86
|
+
if (values.version) return console.log(VERSION);
|
|
87
|
+
const web = positionals[0] === 'web';
|
|
88
|
+
if (positionals.length > (web ? 2 : 1))
|
|
89
|
+
throw new Error(
|
|
90
|
+
'Choose one source argument: aitm [path-or-url]. Add more sources through the import dialogs.',
|
|
91
|
+
);
|
|
92
|
+
const command = positionals[0];
|
|
93
|
+
if (command === 'configure') return configureKeys();
|
|
94
|
+
if (values.live && command !== 'doctor') throw new Error('--live is only for aitm doctor.');
|
|
95
|
+
if (values.rotate && command !== 'token') throw new Error('--rotate is only for aitm token.');
|
|
96
|
+
if (command === 'doctor') {
|
|
97
|
+
const { doctor } = await import('./doctor.js');
|
|
98
|
+
if (await doctor({ port: values.port, dataDir: values['data-dir'], live: values.live }))
|
|
99
|
+
process.exitCode = 1;
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (command === 'token') {
|
|
103
|
+
console.log(loadConfig().apiToken({ rotate: values.rotate }));
|
|
104
|
+
if (values.rotate)
|
|
105
|
+
console.error(
|
|
106
|
+
'New token saved. Restart running AiTM instances; open their new URL in the browser.',
|
|
107
|
+
);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const headless = command === 'serve';
|
|
111
|
+
const explicitSource = web ? positionals[1] : headless ? undefined : command;
|
|
112
|
+
if (values.project && (explicitSource || headless))
|
|
113
|
+
throw new Error('Use --project with the TUI or web, without a source argument.');
|
|
114
|
+
if (values.full && !explicitSource && !values.project)
|
|
115
|
+
throw new Error(
|
|
116
|
+
'Choose a saved project with --project or provide an explicit source before using --full.',
|
|
117
|
+
);
|
|
118
|
+
if (values['no-open'] && !web) throw new Error('--no-open is only for aitm web.');
|
|
119
|
+
if (headless && values.full)
|
|
120
|
+
throw new Error('Use aitm <source> --full, or start a run through the API.');
|
|
121
|
+
if (!headless && !web && (!process.stdin.isTTY || !process.stdout.isTTY))
|
|
122
|
+
throw new Error('The TUI needs an interactive terminal. Use aitm serve for the headless API.');
|
|
123
|
+
const config = loadConfig();
|
|
124
|
+
const port = Number(values.port || config.port);
|
|
125
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
126
|
+
throw new Error('Port must be between 1 and 65535.');
|
|
127
|
+
const app = await startApplication({
|
|
128
|
+
dataDir: path.resolve(values['data-dir'] || config.dataDir),
|
|
129
|
+
providers: new Providers(config),
|
|
130
|
+
port,
|
|
131
|
+
token: config.apiToken(),
|
|
132
|
+
allowedHosts: values['allowed-host'],
|
|
133
|
+
});
|
|
134
|
+
const keys = Object.entries(config.keySources)
|
|
135
|
+
.map(([provider, source]) => `${provider === 'openai' ? 'OpenAI' : 'Anthropic'} ${source}`)
|
|
136
|
+
.join(' · ');
|
|
137
|
+
let ui,
|
|
138
|
+
stopping = false;
|
|
139
|
+
let resolveSignal;
|
|
140
|
+
const signalReceived = new Promise((resolve) => {
|
|
141
|
+
resolveSignal = resolve;
|
|
142
|
+
});
|
|
143
|
+
const stop = () => {
|
|
144
|
+
stopping = true;
|
|
145
|
+
ui?.unmount();
|
|
146
|
+
resolveSignal();
|
|
147
|
+
// Abort intake/provider I/O as soon as the signal arrives.
|
|
148
|
+
app.close().catch(() => {});
|
|
149
|
+
};
|
|
150
|
+
process.once('SIGINT', stop);
|
|
151
|
+
process.once('SIGTERM', stop);
|
|
152
|
+
try {
|
|
153
|
+
if (headless) {
|
|
154
|
+
console.log(
|
|
155
|
+
`AiTM engine and API: ${app.url}\nWeb workbench: ${app.webUrl()}\nAPI clients: Authorization: Bearer "$(aitm token)"\nData: ${app.engine.store.directory}\nKeys: ${keys}\nCtrl+C to save and quit.`,
|
|
156
|
+
);
|
|
157
|
+
await signalReceived;
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
let project,
|
|
161
|
+
reused = false;
|
|
162
|
+
if (values.project) project = app.engine.get(values.project);
|
|
163
|
+
else if (explicitSource)
|
|
164
|
+
({ project, reused } = await withActivity('Opening selected source', () =>
|
|
165
|
+
openAssessment(app.engine, sourceInput(explicitSource)),
|
|
166
|
+
));
|
|
167
|
+
if (stopping) return;
|
|
168
|
+
if (values.full) app.engine.run(project.id, { mode: 'full' });
|
|
169
|
+
if (web) {
|
|
170
|
+
const url = app.webUrl(project ? `#/projects/${project.id}/overview` : '');
|
|
171
|
+
console.log(
|
|
172
|
+
`AiTM web workbench: ${url}\nThe URL contains your private access token. Do not share it.\nData: ${app.engine.store.directory}\nKeys: ${keys}\nCtrl+C to save and quit.`,
|
|
173
|
+
);
|
|
174
|
+
if (!values['no-open']) {
|
|
175
|
+
const [program, args] =
|
|
176
|
+
process.platform === 'darwin'
|
|
177
|
+
? ['open', [url]]
|
|
178
|
+
: process.platform === 'win32'
|
|
179
|
+
? ['rundll32', ['url.dll,FileProtocolHandler', url]]
|
|
180
|
+
: ['xdg-open', [url]];
|
|
181
|
+
try {
|
|
182
|
+
await promisify(execFile)(program, args);
|
|
183
|
+
} catch {
|
|
184
|
+
console.log('Open the workbench URL above in your browser.');
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
await signalReceived;
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const [{ default: React }, { render }, { Workbench }] = await Promise.all([
|
|
191
|
+
import('react'),
|
|
192
|
+
import('ink'),
|
|
193
|
+
import('./tui/workbench.js'),
|
|
194
|
+
]);
|
|
195
|
+
if (stopping) return;
|
|
196
|
+
ui = render(
|
|
197
|
+
React.createElement(Workbench, {
|
|
198
|
+
engine: app.engine,
|
|
199
|
+
projectId: project?.id,
|
|
200
|
+
apiUrl: app.url,
|
|
201
|
+
webUrl: app.webUrl(),
|
|
202
|
+
initialNotice: project?.artifacts.report
|
|
203
|
+
? 'Report ready. v View Markdown · x Export · ? Help.'
|
|
204
|
+
: reused
|
|
205
|
+
? 'Saved assessment reopened. f Continue TRACE · u Refresh source snapshot.'
|
|
206
|
+
: 'Source loaded. f Run full pipeline · e Edit scope · ? Help.',
|
|
207
|
+
}),
|
|
208
|
+
{ alternateScreen: true },
|
|
209
|
+
);
|
|
210
|
+
await Promise.race([ui.waitUntilExit(), signalReceived]);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
if (!stopping) throw error;
|
|
213
|
+
} finally {
|
|
214
|
+
await app.close();
|
|
215
|
+
process.removeListener('SIGINT', stop);
|
|
216
|
+
process.removeListener('SIGTERM', stop);
|
|
217
|
+
}
|
|
218
|
+
console.log('AiTM saved and closed. Open the same source to continue.');
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
main().catch((error) => {
|
|
222
|
+
console.error(`AiTM: ${terminalText(error.message)}`);
|
|
223
|
+
process.exitCode = 1;
|
|
224
|
+
});
|
package/src/client.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { readToken } from './token.js';
|
|
2
|
+
|
|
3
|
+
export class ApiClient {
|
|
4
|
+
// The token defaults to AITM_TOKEN, then to the token file of the current user.
|
|
5
|
+
constructor(url = 'http://127.0.0.1:8790', { token } = {}) {
|
|
6
|
+
const parsed = new URL(url);
|
|
7
|
+
if (
|
|
8
|
+
parsed.protocol !== 'http:' ||
|
|
9
|
+
!['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname) ||
|
|
10
|
+
parsed.username ||
|
|
11
|
+
parsed.password ||
|
|
12
|
+
parsed.pathname !== '/' ||
|
|
13
|
+
parsed.search ||
|
|
14
|
+
parsed.hash
|
|
15
|
+
)
|
|
16
|
+
throw new Error('Use a loopback HTTP API URL, for example http://127.0.0.1:8790.');
|
|
17
|
+
this.url = parsed.origin;
|
|
18
|
+
this.token = token;
|
|
19
|
+
}
|
|
20
|
+
authorization() {
|
|
21
|
+
this.token ??= process.env.AITM_TOKEN || readToken();
|
|
22
|
+
return this.token ? { authorization: `Bearer ${this.token}` } : {};
|
|
23
|
+
}
|
|
24
|
+
async request(method, path, body, { signal, format = 'json' } = {}) {
|
|
25
|
+
let response;
|
|
26
|
+
try {
|
|
27
|
+
response = await fetch(this.url + path, {
|
|
28
|
+
method,
|
|
29
|
+
signal,
|
|
30
|
+
redirect: 'error',
|
|
31
|
+
headers: {
|
|
32
|
+
...this.authorization(),
|
|
33
|
+
...(body === undefined ? {} : { 'content-type': 'application/json' }),
|
|
34
|
+
},
|
|
35
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
36
|
+
});
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (signal?.aborted) throw error;
|
|
39
|
+
throw new Error('Cannot reach the AiTM API. Open aitm or aitm serve, and check the API URL.');
|
|
40
|
+
}
|
|
41
|
+
if (!response.ok) {
|
|
42
|
+
const data = await response.json().catch(() => ({}));
|
|
43
|
+
throw new Error(data.error?.message || `API request failed (${response.status}).`);
|
|
44
|
+
}
|
|
45
|
+
return format === 'text'
|
|
46
|
+
? response.text()
|
|
47
|
+
: format === 'buffer'
|
|
48
|
+
? Buffer.from(await response.arrayBuffer())
|
|
49
|
+
: response.json();
|
|
50
|
+
}
|
|
51
|
+
get(path, options) {
|
|
52
|
+
return this.request('GET', path, undefined, options);
|
|
53
|
+
}
|
|
54
|
+
post(path, body = {}) {
|
|
55
|
+
return this.request('POST', path, body);
|
|
56
|
+
}
|
|
57
|
+
projectPath(id) {
|
|
58
|
+
return `/v1/projects/${encodeURIComponent(id)}`;
|
|
59
|
+
}
|
|
60
|
+
async *events(projectId, runId, { after = 0, signal } = {}) {
|
|
61
|
+
const url = `${this.url}${this.projectPath(projectId)}/runs/${encodeURIComponent(runId)}/events?after=${after}`;
|
|
62
|
+
const response = await fetch(url, {
|
|
63
|
+
signal,
|
|
64
|
+
redirect: 'error',
|
|
65
|
+
headers: this.authorization(),
|
|
66
|
+
});
|
|
67
|
+
if (!response.ok) throw new Error(`Cannot stream progress (HTTP ${response.status}).`);
|
|
68
|
+
const decoder = new TextDecoder();
|
|
69
|
+
let pending = '';
|
|
70
|
+
try {
|
|
71
|
+
for await (const chunk of response.body) {
|
|
72
|
+
pending = (pending + decoder.decode(chunk, { stream: true })).replace(/\r\n/g, '\n');
|
|
73
|
+
let end;
|
|
74
|
+
while ((end = pending.indexOf('\n\n')) >= 0) {
|
|
75
|
+
const lines = pending.slice(0, end).split('\n');
|
|
76
|
+
pending = pending.slice(end + 2);
|
|
77
|
+
const data = lines
|
|
78
|
+
.filter((l) => l.startsWith('data:'))
|
|
79
|
+
.map((l) => l.slice(5).trimStart())
|
|
80
|
+
.join('\n');
|
|
81
|
+
if (data) yield JSON.parse(data);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (!signal?.aborted) throw error;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { parseEnv } from 'node:util';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { createInterface } from 'node:readline/promises';
|
|
7
|
+
import { Writable } from 'node:stream';
|
|
8
|
+
import { credentialPatch } from './engine/credentials.js';
|
|
9
|
+
import { configDir, readPrivate, writePrivate, loadToken, tokenFile } from './token.js';
|
|
10
|
+
|
|
11
|
+
export { configDir };
|
|
12
|
+
export const defaultDataDir = () =>
|
|
13
|
+
path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share'), 'aitm-v2');
|
|
14
|
+
const privateFile = readPrivate;
|
|
15
|
+
|
|
16
|
+
function storedKeys(directory) {
|
|
17
|
+
const stored = privateFile(path.join(directory, 'keys.json'));
|
|
18
|
+
try {
|
|
19
|
+
return stored ? credentialPatch(JSON.parse(stored)) : {};
|
|
20
|
+
} catch {
|
|
21
|
+
throw new Error(
|
|
22
|
+
'The saved credential file is invalid. Check keys.json in the AiTM configuration directory.',
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function saveKeys(patch, { directory = configDir() } = {}) {
|
|
28
|
+
const changes = credentialPatch(patch);
|
|
29
|
+
if (!Object.keys(changes).length) return;
|
|
30
|
+
const next = { ...storedKeys(directory), ...changes };
|
|
31
|
+
writePrivate(directory, 'keys.json', JSON.stringify(next));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function loadConfig({
|
|
35
|
+
env = process.env,
|
|
36
|
+
cwd = process.cwd(),
|
|
37
|
+
directory = configDir(),
|
|
38
|
+
packageRoot = fileURLToPath(new URL('..', import.meta.url)),
|
|
39
|
+
} = {}) {
|
|
40
|
+
const file = [path.resolve(cwd, '.env.local'), path.join(packageRoot, '.env.local')].find((p) =>
|
|
41
|
+
existsSync(p),
|
|
42
|
+
);
|
|
43
|
+
const local = file ? parseEnv(privateFile(file)) : {};
|
|
44
|
+
const stored = storedKeys(directory);
|
|
45
|
+
const combined = { ...local, ...env };
|
|
46
|
+
const names = { openai: 'OPENAI_API_KEY', anthropic: 'ANTHROPIC_API_KEY' };
|
|
47
|
+
const keys = Object.fromEntries(
|
|
48
|
+
Object.entries(names).map(([provider, variable]) => [
|
|
49
|
+
provider,
|
|
50
|
+
stored[provider] || env[variable] || local[variable] || '',
|
|
51
|
+
]),
|
|
52
|
+
);
|
|
53
|
+
return {
|
|
54
|
+
keys,
|
|
55
|
+
keySources: Object.fromEntries(
|
|
56
|
+
Object.entries(names).map(([provider, variable]) => [
|
|
57
|
+
provider,
|
|
58
|
+
stored[provider]
|
|
59
|
+
? 'saved settings'
|
|
60
|
+
: env[variable]
|
|
61
|
+
? 'environment'
|
|
62
|
+
: local[variable]
|
|
63
|
+
? '.env.local'
|
|
64
|
+
: 'not configured',
|
|
65
|
+
]),
|
|
66
|
+
),
|
|
67
|
+
keyFile: path.join(directory, 'keys.json'),
|
|
68
|
+
tokenFile: tokenFile(directory),
|
|
69
|
+
apiToken: (options) => loadToken(directory, options),
|
|
70
|
+
saveCredentials: (patch) => saveKeys(patch, { directory }),
|
|
71
|
+
anthropicWorkspaceId: stored.anthropicWorkspaceId ?? combined.ANTHROPIC_WORKSPACE_ID ?? '',
|
|
72
|
+
dataDir: path.resolve(combined.AITM_DATA_DIR || defaultDataDir()),
|
|
73
|
+
port: Number(combined.AITM_PORT || 8790),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function configureKeys() {
|
|
78
|
+
if (!process.stdin.isTTY) throw new Error('Run aitm configure in an interactive terminal.');
|
|
79
|
+
const sink = new Writable({
|
|
80
|
+
write(chunk, encoding, callback) {
|
|
81
|
+
callback();
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
const input = createInterface({ input: process.stdin, output: sink, terminal: true });
|
|
85
|
+
const keys = {};
|
|
86
|
+
try {
|
|
87
|
+
for (const [provider, name] of [
|
|
88
|
+
['openai', 'OpenAI'],
|
|
89
|
+
['anthropic', 'Anthropic'],
|
|
90
|
+
]) {
|
|
91
|
+
process.stdout.write(`${name} API key (hidden; Enter keeps existing): `);
|
|
92
|
+
const key = (await input.question('')).trim();
|
|
93
|
+
process.stdout.write('\n');
|
|
94
|
+
if (key) Object.assign(keys, credentialPatch({ [provider]: key }));
|
|
95
|
+
}
|
|
96
|
+
} finally {
|
|
97
|
+
input.close();
|
|
98
|
+
}
|
|
99
|
+
saveKeys(keys);
|
|
100
|
+
console.log(
|
|
101
|
+
Object.keys(keys).length
|
|
102
|
+
? 'Keys saved privately. Saved settings take precedence over environment variables and .env.local. Reopen a running AiTM session to load CLI changes, or use s Settings to update immediately.'
|
|
103
|
+
: 'No keys changed.',
|
|
104
|
+
);
|
|
105
|
+
}
|
package/src/doctor.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { accessSync, constants, existsSync } from 'node:fs';
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { promisify } from 'node:util';
|
|
4
|
+
import net from 'node:net';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import lockfile from 'proper-lockfile';
|
|
7
|
+
import { loadConfig } from './config.js';
|
|
8
|
+
import { readToken } from './token.js';
|
|
9
|
+
import { Providers } from './engine/providers.js';
|
|
10
|
+
import { DEFAULT_MODELS } from './engine/schema.js';
|
|
11
|
+
import { NODE_RANGE, VERSION } from './version.js';
|
|
12
|
+
|
|
13
|
+
const NAMES = { openai: 'OpenAI', anthropic: 'Anthropic' };
|
|
14
|
+
|
|
15
|
+
function portState(port) {
|
|
16
|
+
return new Promise((resolve) => {
|
|
17
|
+
const probe = net.createServer();
|
|
18
|
+
probe.once('error', (error) => resolve(error.code === 'EADDRINUSE' ? 'busy' : error.code));
|
|
19
|
+
probe.listen(port, '127.0.0.1', () => probe.close(() => resolve('free')));
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Read-only checks of the local setup. Returns the number of failures.
|
|
24
|
+
export async function doctor({
|
|
25
|
+
load = loadConfig,
|
|
26
|
+
port,
|
|
27
|
+
dataDir,
|
|
28
|
+
live = false,
|
|
29
|
+
write = console.log,
|
|
30
|
+
fetchImpl = fetch,
|
|
31
|
+
} = {}) {
|
|
32
|
+
let failures = 0;
|
|
33
|
+
const ok = (text) => write(`ok ${text}`);
|
|
34
|
+
const warn = (text) => write(`warn ${text}`);
|
|
35
|
+
const fail = (text) => {
|
|
36
|
+
failures++;
|
|
37
|
+
write(`FAIL ${text}`);
|
|
38
|
+
};
|
|
39
|
+
write(`AiTM ${VERSION} doctor`);
|
|
40
|
+
|
|
41
|
+
const minimum = (/\d+(?:\.\d+){0,2}/.exec(NODE_RANGE)?.[0] || '0').split('.').map(Number);
|
|
42
|
+
const node = process.versions.node;
|
|
43
|
+
const current = node.split('.').map(Number);
|
|
44
|
+
const index = [0, 1, 2].find((i) => current[i] !== (minimum[i] || 0));
|
|
45
|
+
if (index === undefined || current[index] > (minimum[index] || 0))
|
|
46
|
+
ok(`Node.js ${node} (requires ${NODE_RANGE})`);
|
|
47
|
+
else fail(`Node.js ${node} is too old. Install Node.js ${NODE_RANGE}.`);
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
const { stdout } = await promisify(execFile)('git', ['--version']);
|
|
51
|
+
ok(stdout.trim());
|
|
52
|
+
} catch {
|
|
53
|
+
warn('Git is not on PATH. Repository URLs cannot be imported; local sources still work.');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
let config;
|
|
57
|
+
try {
|
|
58
|
+
config = load();
|
|
59
|
+
} catch (error) {
|
|
60
|
+
fail(error.message);
|
|
61
|
+
}
|
|
62
|
+
if (config) {
|
|
63
|
+
for (const [provider, name] of Object.entries(NAMES)) {
|
|
64
|
+
const source = config.keySources[provider];
|
|
65
|
+
if (config.keys[provider]) ok(`${name} key: ${source}`);
|
|
66
|
+
else warn(`${name} key: not configured`);
|
|
67
|
+
}
|
|
68
|
+
if (!Object.values(config.keys).some(Boolean))
|
|
69
|
+
warn('No provider key. Run aitm configure, or add a key in Settings, before a run.');
|
|
70
|
+
ok(
|
|
71
|
+
existsSync(config.keyFile)
|
|
72
|
+
? `Key file: ${config.keyFile} (owner-only)`
|
|
73
|
+
: `Key file: ${config.keyFile} (not created yet)`,
|
|
74
|
+
);
|
|
75
|
+
try {
|
|
76
|
+
ok(
|
|
77
|
+
readToken(path.dirname(config.tokenFile))
|
|
78
|
+
? `API access token: ${config.tokenFile} (owner-only)`
|
|
79
|
+
: `API access token: created on first start in ${config.tokenFile}`,
|
|
80
|
+
);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
fail(error.message);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const directory = path.resolve(dataDir || config.dataDir);
|
|
86
|
+
if (!existsSync(directory)) ok(`Data directory: ${directory} (created on first start)`);
|
|
87
|
+
else
|
|
88
|
+
try {
|
|
89
|
+
accessSync(directory, constants.R_OK | constants.W_OK);
|
|
90
|
+
if (await lockfile.check(directory, { stale: 10000 }))
|
|
91
|
+
warn(`Data directory: ${directory} is in use by a running AiTM instance.`);
|
|
92
|
+
else ok(`Data directory: ${directory}`);
|
|
93
|
+
} catch {
|
|
94
|
+
fail(`Data directory: ${directory} is not readable and writable.`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const selected = Number(port || config.port);
|
|
98
|
+
const state = await portState(selected);
|
|
99
|
+
if (state === 'free') ok(`Port ${selected} is free.`);
|
|
100
|
+
else if (state === 'busy') {
|
|
101
|
+
const health = await fetchImpl(`http://127.0.0.1:${selected}/v1/health`, {
|
|
102
|
+
signal: AbortSignal.timeout(2000),
|
|
103
|
+
})
|
|
104
|
+
.then((response) => response.json())
|
|
105
|
+
.catch(() => null);
|
|
106
|
+
if (health?.service === 'aitm')
|
|
107
|
+
warn(`Port ${selected}: AiTM ${health.version} runs here. Open its URL, or use --port.`);
|
|
108
|
+
else fail(`Port ${selected} is in use by another program. Use --port NUMBER.`);
|
|
109
|
+
} else fail(`Port ${selected} cannot be opened (${state}).`);
|
|
110
|
+
|
|
111
|
+
if (live) {
|
|
112
|
+
const providers = new Providers(config);
|
|
113
|
+
for (const [provider, name] of Object.entries(NAMES)) {
|
|
114
|
+
if (!config.keys[provider]) continue;
|
|
115
|
+
const model = DEFAULT_MODELS[provider].fastModel;
|
|
116
|
+
try {
|
|
117
|
+
await providers.test(provider, model, AbortSignal.timeout(60000));
|
|
118
|
+
ok(`${name} request with ${model} completed.`);
|
|
119
|
+
} catch (error) {
|
|
120
|
+
fail(`${name} request with ${model}: ${providers.redact(error.message)}`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
} else if (Object.values(config.keys).some(Boolean))
|
|
124
|
+
write(' Run aitm doctor --live to send one small request to each configured provider.');
|
|
125
|
+
}
|
|
126
|
+
write(failures ? `Result: ${failures} problem(s) to correct.` : 'Result: ready.');
|
|
127
|
+
return failures;
|
|
128
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { insist } from './errors.js';
|
|
2
|
+
|
|
3
|
+
// Validate without ever reflecting credential values in an error.
|
|
4
|
+
export function credentialPatch(input) {
|
|
5
|
+
insist(
|
|
6
|
+
input && typeof input === 'object' && !Array.isArray(input),
|
|
7
|
+
'Invalid credential settings.',
|
|
8
|
+
);
|
|
9
|
+
const result = {};
|
|
10
|
+
for (const [name, value] of Object.entries(input)) {
|
|
11
|
+
insist(
|
|
12
|
+
['openai', 'anthropic', 'anthropicWorkspaceId'].includes(name),
|
|
13
|
+
'Unknown credential setting.',
|
|
14
|
+
);
|
|
15
|
+
insist(typeof value === 'string', 'Credential settings must be text.');
|
|
16
|
+
const text = value.trim();
|
|
17
|
+
if (name === 'anthropicWorkspaceId') {
|
|
18
|
+
insist(
|
|
19
|
+
!text || /^wrkspc_[A-Za-z0-9]+$/.test(text),
|
|
20
|
+
'Anthropic workspace ID must start with wrkspc_.',
|
|
21
|
+
);
|
|
22
|
+
} else {
|
|
23
|
+
insist(
|
|
24
|
+
text.length > 0 && text.length <= 2048 && /^[\x21-\x7e]+$/.test(text),
|
|
25
|
+
'An API key must be nonempty text without spaces or control characters.',
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
result[name] = text;
|
|
29
|
+
}
|
|
30
|
+
return result;
|
|
31
|
+
}
|