@faces-sh/cli 0.0.0-stage → 1.0.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 +158 -2
- package/bin/dev.js +5 -0
- package/bin/run.js +5 -0
- package/dist/base.d.ts +26 -0
- package/dist/base.js +181 -0
- package/dist/benchmark.d.ts +21 -0
- package/dist/benchmark.js +95 -0
- package/dist/billing.d.ts +17 -0
- package/dist/billing.js +101 -0
- package/dist/catalog.d.ts +35 -0
- package/dist/catalog.js +242 -0
- package/dist/client.d.ts +98 -0
- package/dist/client.js +590 -0
- package/dist/commands/account/preferences.d.ts +20 -0
- package/dist/commands/account/preferences.js +190 -0
- package/dist/commands/account/state.d.ts +11 -0
- package/dist/commands/account/state.js +24 -0
- package/dist/commands/auth/connect.d.ts +17 -0
- package/dist/commands/auth/connect.js +190 -0
- package/dist/commands/auth/connections.d.ts +12 -0
- package/dist/commands/auth/connections.js +40 -0
- package/dist/commands/auth/disconnect.d.ts +15 -0
- package/dist/commands/auth/disconnect.js +49 -0
- package/dist/commands/auth/login.d.ts +13 -0
- package/dist/commands/auth/login.js +42 -0
- package/dist/commands/auth/logout.d.ts +11 -0
- package/dist/commands/auth/logout.js +14 -0
- package/dist/commands/auth/refresh.d.ts +11 -0
- package/dist/commands/auth/refresh.js +30 -0
- package/dist/commands/auth/register.d.ts +15 -0
- package/dist/commands/auth/register.js +98 -0
- package/dist/commands/auth/whoami.d.ts +11 -0
- package/dist/commands/auth/whoami.js +108 -0
- package/dist/commands/benchmark/get.d.ts +16 -0
- package/dist/commands/benchmark/get.js +42 -0
- package/dist/commands/benchmark/list.d.ts +13 -0
- package/dist/commands/benchmark/list.js +47 -0
- package/dist/commands/benchmark/start.d.ts +22 -0
- package/dist/commands/benchmark/start.js +80 -0
- package/dist/commands/billing/balance.d.ts +11 -0
- package/dist/commands/billing/balance.js +27 -0
- package/dist/commands/billing/card/default.d.ts +15 -0
- package/dist/commands/billing/card/default.js +33 -0
- package/dist/commands/billing/card/remove.d.ts +16 -0
- package/dist/commands/billing/card/remove.js +41 -0
- package/dist/commands/billing/card-setup.d.ts +13 -0
- package/dist/commands/billing/card-setup.js +41 -0
- package/dist/commands/billing/cards.d.ts +11 -0
- package/dist/commands/billing/cards.js +34 -0
- package/dist/commands/billing/llm-costs.d.ts +14 -0
- package/dist/commands/billing/llm-costs.js +95 -0
- package/dist/commands/billing/subscription/activate.d.ts +14 -0
- package/dist/commands/billing/subscription/activate.js +91 -0
- package/dist/commands/billing/subscription/cancel.d.ts +12 -0
- package/dist/commands/billing/subscription/cancel.js +54 -0
- package/dist/commands/billing/subscription/index.d.ts +11 -0
- package/dist/commands/billing/subscription/index.js +46 -0
- package/dist/commands/billing/subscription/plan.d.ts +16 -0
- package/dist/commands/billing/subscription/plan.js +86 -0
- package/dist/commands/billing/topup.d.ts +16 -0
- package/dist/commands/billing/topup.js +60 -0
- package/dist/commands/billing/usage.d.ts +15 -0
- package/dist/commands/billing/usage.js +68 -0
- package/dist/commands/catalog/backup.d.ts +11 -0
- package/dist/commands/catalog/backup.js +169 -0
- package/dist/commands/catalog/doctor.d.ts +14 -0
- package/dist/commands/catalog/doctor.js +303 -0
- package/dist/commands/catalog/list.d.ts +11 -0
- package/dist/commands/catalog/list.js +39 -0
- package/dist/commands/catalog/restore.d.ts +17 -0
- package/dist/commands/catalog/restore.js +259 -0
- package/dist/commands/causes.d.ts +27 -0
- package/dist/commands/causes.js +135 -0
- package/dist/commands/chat/chat.d.ts +42 -0
- package/dist/commands/chat/chat.js +363 -0
- package/dist/commands/chat/messages.d.ts +26 -0
- package/dist/commands/chat/messages.js +139 -0
- package/dist/commands/chat/responses.d.ts +27 -0
- package/dist/commands/chat/responses.js +150 -0
- package/dist/commands/chat/thread.d.ts +43 -0
- package/dist/commands/chat/thread.js +458 -0
- package/dist/commands/compile/all.d.ts +14 -0
- package/dist/commands/compile/all.js +186 -0
- package/dist/commands/compile/doc/create.d.ts +19 -0
- package/dist/commands/compile/doc/create.js +58 -0
- package/dist/commands/compile/doc/delete.d.ts +15 -0
- package/dist/commands/compile/doc/delete.js +33 -0
- package/dist/commands/compile/doc/edit.d.ts +19 -0
- package/dist/commands/compile/doc/edit.js +59 -0
- package/dist/commands/compile/doc/get.d.ts +15 -0
- package/dist/commands/compile/doc/get.js +43 -0
- package/dist/commands/compile/doc/index.d.ts +24 -0
- package/dist/commands/compile/doc/index.js +211 -0
- package/dist/commands/compile/doc/list.d.ts +15 -0
- package/dist/commands/compile/doc/list.js +46 -0
- package/dist/commands/compile/doc/make.d.ts +17 -0
- package/dist/commands/compile/doc/make.js +95 -0
- package/dist/commands/compile/doc/pause.d.ts +17 -0
- package/dist/commands/compile/doc/pause.js +74 -0
- package/dist/commands/compile/doc/reset.d.ts +15 -0
- package/dist/commands/compile/doc/reset.js +33 -0
- package/dist/commands/compile/import.d.ts +20 -0
- package/dist/commands/compile/import.js +138 -0
- package/dist/commands/compile/stats.d.ts +11 -0
- package/dist/commands/compile/stats.js +75 -0
- package/dist/commands/compile/status.d.ts +17 -0
- package/dist/commands/compile/status.js +110 -0
- package/dist/commands/compile/thread/create.d.ts +16 -0
- package/dist/commands/compile/thread/create.js +42 -0
- package/dist/commands/compile/thread/delete.d.ts +15 -0
- package/dist/commands/compile/thread/delete.js +33 -0
- package/dist/commands/compile/thread/edit.d.ts +19 -0
- package/dist/commands/compile/thread/edit.js +120 -0
- package/dist/commands/compile/thread/get.d.ts +15 -0
- package/dist/commands/compile/thread/get.js +48 -0
- package/dist/commands/compile/thread/list.d.ts +14 -0
- package/dist/commands/compile/thread/list.js +38 -0
- package/dist/commands/compile/thread/make.d.ts +17 -0
- package/dist/commands/compile/thread/make.js +87 -0
- package/dist/commands/compile/thread/message.d.ts +16 -0
- package/dist/commands/compile/thread/message.js +43 -0
- package/dist/commands/compile/thread/pause.d.ts +17 -0
- package/dist/commands/compile/thread/pause.js +75 -0
- package/dist/commands/compile/thread/replace.d.ts +27 -0
- package/dist/commands/compile/thread/replace.js +114 -0
- package/dist/commands/compile/thread/reset.d.ts +15 -0
- package/dist/commands/compile/thread/reset.js +33 -0
- package/dist/commands/compile/upload.d.ts +21 -0
- package/dist/commands/compile/upload.js +162 -0
- package/dist/commands/config/clear.d.ts +12 -0
- package/dist/commands/config/clear.js +17 -0
- package/dist/commands/config/set.d.ts +15 -0
- package/dist/commands/config/set.js +43 -0
- package/dist/commands/config/show.d.ts +11 -0
- package/dist/commands/config/show.js +19 -0
- package/dist/commands/decide.d.ts +35 -0
- package/dist/commands/decide.js +242 -0
- package/dist/commands/face/attributes.d.ts +11 -0
- package/dist/commands/face/attributes.js +44 -0
- package/dist/commands/face/avatar/delete.d.ts +15 -0
- package/dist/commands/face/avatar/delete.js +38 -0
- package/dist/commands/face/avatar/get.d.ts +20 -0
- package/dist/commands/face/avatar/get.js +100 -0
- package/dist/commands/face/avatar/list.d.ts +14 -0
- package/dist/commands/face/avatar/list.js +56 -0
- package/dist/commands/face/avatar/make.d.ts +16 -0
- package/dist/commands/face/avatar/make.js +64 -0
- package/dist/commands/face/avatar/upload.d.ts +15 -0
- package/dist/commands/face/avatar/upload.js +67 -0
- package/dist/commands/face/create.d.ts +23 -0
- package/dist/commands/face/create.js +122 -0
- package/dist/commands/face/delete.d.ts +15 -0
- package/dist/commands/face/delete.js +39 -0
- package/dist/commands/face/diff.d.ts +12 -0
- package/dist/commands/face/diff.js +50 -0
- package/dist/commands/face/edit.d.ts +25 -0
- package/dist/commands/face/edit.js +155 -0
- package/dist/commands/face/get.d.ts +16 -0
- package/dist/commands/face/get.js +145 -0
- package/dist/commands/face/groups.d.ts +15 -0
- package/dist/commands/face/groups.js +34 -0
- package/dist/commands/face/list.d.ts +23 -0
- package/dist/commands/face/list.js +168 -0
- package/dist/commands/face/lock.d.ts +15 -0
- package/dist/commands/face/lock.js +35 -0
- package/dist/commands/face/neighbors.d.ts +16 -0
- package/dist/commands/face/neighbors.js +63 -0
- package/dist/commands/face/publish.d.ts +16 -0
- package/dist/commands/face/publish.js +42 -0
- package/dist/commands/face/share.d.ts +22 -0
- package/dist/commands/face/share.js +103 -0
- package/dist/commands/face/sources.d.ts +21 -0
- package/dist/commands/face/sources.js +169 -0
- package/dist/commands/face/stats.d.ts +12 -0
- package/dist/commands/face/stats.js +46 -0
- package/dist/commands/face/tag/add.d.ts +15 -0
- package/dist/commands/face/tag/add.js +40 -0
- package/dist/commands/face/tag/all.d.ts +11 -0
- package/dist/commands/face/tag/all.js +31 -0
- package/dist/commands/face/tag/list.d.ts +14 -0
- package/dist/commands/face/tag/list.js +36 -0
- package/dist/commands/face/tag/remove.d.ts +16 -0
- package/dist/commands/face/tag/remove.js +44 -0
- package/dist/commands/face/tag/set.d.ts +15 -0
- package/dist/commands/face/tag/set.js +40 -0
- package/dist/commands/face/unlock.d.ts +15 -0
- package/dist/commands/face/unlock.js +35 -0
- package/dist/commands/face/unpublish.d.ts +14 -0
- package/dist/commands/face/unpublish.js +31 -0
- package/dist/commands/face/unshare.d.ts +18 -0
- package/dist/commands/face/unshare.js +66 -0
- package/dist/commands/fidelity/get.d.ts +15 -0
- package/dist/commands/fidelity/get.js +42 -0
- package/dist/commands/fidelity/pick.d.ts +19 -0
- package/dist/commands/fidelity/pick.js +70 -0
- package/dist/commands/fidelity/run.d.ts +20 -0
- package/dist/commands/fidelity/run.js +99 -0
- package/dist/commands/fidelity/save-thread.d.ts +15 -0
- package/dist/commands/fidelity/save-thread.js +35 -0
- package/dist/commands/fidelity/start.d.ts +17 -0
- package/dist/commands/fidelity/start.js +56 -0
- package/dist/commands/fidelity/turn.d.ts +17 -0
- package/dist/commands/fidelity/turn.js +48 -0
- package/dist/commands/group/add.d.ts +16 -0
- package/dist/commands/group/add.js +83 -0
- package/dist/commands/group/create.d.ts +16 -0
- package/dist/commands/group/create.js +68 -0
- package/dist/commands/group/delete.d.ts +15 -0
- package/dist/commands/group/delete.js +39 -0
- package/dist/commands/group/edit.d.ts +18 -0
- package/dist/commands/group/edit.js +75 -0
- package/dist/commands/group/get.d.ts +14 -0
- package/dist/commands/group/get.js +29 -0
- package/dist/commands/group/list.d.ts +11 -0
- package/dist/commands/group/list.js +39 -0
- package/dist/commands/group/members.d.ts +15 -0
- package/dist/commands/group/members.js +68 -0
- package/dist/commands/group/remove.d.ts +15 -0
- package/dist/commands/group/remove.js +55 -0
- package/dist/commands/group/tag/add.d.ts +15 -0
- package/dist/commands/group/tag/add.js +30 -0
- package/dist/commands/group/tag/list.d.ts +14 -0
- package/dist/commands/group/tag/list.js +36 -0
- package/dist/commands/group/tag/remove.d.ts +15 -0
- package/dist/commands/group/tag/remove.js +30 -0
- package/dist/commands/group/tag/set.d.ts +15 -0
- package/dist/commands/group/tag/set.js +30 -0
- package/dist/commands/keys/create.d.ts +17 -0
- package/dist/commands/keys/create.js +72 -0
- package/dist/commands/keys/list.d.ts +11 -0
- package/dist/commands/keys/list.js +24 -0
- package/dist/commands/keys/revoke.d.ts +15 -0
- package/dist/commands/keys/revoke.js +49 -0
- package/dist/commands/keys/update.d.ts +17 -0
- package/dist/commands/keys/update.js +41 -0
- package/dist/commands/models/list.d.ts +15 -0
- package/dist/commands/models/list.js +98 -0
- package/dist/commands/session/close.d.ts +16 -0
- package/dist/commands/session/close.js +36 -0
- package/dist/commands/session/compact.d.ts +15 -0
- package/dist/commands/session/compact.js +58 -0
- package/dist/commands/session/create.d.ts +15 -0
- package/dist/commands/session/create.js +45 -0
- package/dist/commands/session/get.d.ts +15 -0
- package/dist/commands/session/get.js +34 -0
- package/dist/commands/style/delete.d.ts +19 -0
- package/dist/commands/style/delete.js +92 -0
- package/dist/commands/style/make.d.ts +28 -0
- package/dist/commands/style/make.js +298 -0
- package/dist/commands/style/revert.d.ts +17 -0
- package/dist/commands/style/revert.js +66 -0
- package/dist/commands/style/status.d.ts +20 -0
- package/dist/commands/style/status.js +109 -0
- package/dist/commands/style/upload.d.ts +19 -0
- package/dist/commands/style/upload.js +100 -0
- package/dist/commands/style/versions.d.ts +15 -0
- package/dist/commands/style/versions.js +104 -0
- package/dist/commands/user/follow.d.ts +14 -0
- package/dist/commands/user/follow.js +38 -0
- package/dist/commands/user/followers.d.ts +14 -0
- package/dist/commands/user/followers.js +50 -0
- package/dist/commands/user/following.d.ts +14 -0
- package/dist/commands/user/following.js +50 -0
- package/dist/commands/user/get.d.ts +14 -0
- package/dist/commands/user/get.js +49 -0
- package/dist/commands/user/unfollow.d.ts +14 -0
- package/dist/commands/user/unfollow.js +38 -0
- package/dist/config.d.ts +32 -0
- package/dist/config.js +139 -0
- package/dist/decisions.d.ts +42 -0
- package/dist/decisions.js +262 -0
- package/dist/fidelity.d.ts +50 -0
- package/dist/fidelity.js +92 -0
- package/dist/group-catalog.d.ts +22 -0
- package/dist/group-catalog.js +133 -0
- package/dist/paths.d.ts +1 -0
- package/dist/paths.js +8 -0
- package/dist/poll.d.ts +26 -0
- package/dist/poll.js +75 -0
- package/dist/routing.d.ts +15 -0
- package/dist/routing.js +135 -0
- package/dist/session.d.ts +14 -0
- package/dist/session.js +18 -0
- package/dist/style.d.ts +46 -0
- package/dist/style.js +285 -0
- package/dist/utils.d.ts +149 -0
- package/dist/utils.js +865 -0
- package/oclif.manifest.json +11070 -0
- package/package.json +127 -4
package/dist/utils.js
ADDED
|
@@ -0,0 +1,865 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { FacesAPIError, heldChatError } from './client.js';
|
|
4
|
+
import { MAX_WARM_UP_WAIT_S } from './decisions.js';
|
|
5
|
+
export const PROFILE_ADDENDUM_MAX_CHARS = 100_000;
|
|
6
|
+
export function seg(value) {
|
|
7
|
+
if (value === '' || value === '.' || value === '..') {
|
|
8
|
+
throw new Error(`"${value}" is not an id or alias.`);
|
|
9
|
+
}
|
|
10
|
+
return encodeURIComponent(value);
|
|
11
|
+
}
|
|
12
|
+
export function parseBudget(raw, fail, flag = '--budget', max = 999_999) {
|
|
13
|
+
const s = raw.trim().replace(/^\$/, '');
|
|
14
|
+
if (!/^\d+(\.\d{1,2})?$/.test(s))
|
|
15
|
+
fail(`${flag} must be a dollar amount such as 5 or 0.50 (got "${raw}").`);
|
|
16
|
+
const n = Number(s);
|
|
17
|
+
if (n > max)
|
|
18
|
+
fail(`${flag} can be at most ${max}.`);
|
|
19
|
+
return n;
|
|
20
|
+
}
|
|
21
|
+
export function parseTemperature(raw, fail) {
|
|
22
|
+
const n = Number(raw.trim());
|
|
23
|
+
if (raw.trim() === '' || !Number.isFinite(n) || n < 0 || n > 2)
|
|
24
|
+
fail(`--temperature must be a number from 0 to 2 (got "${raw}").`);
|
|
25
|
+
return n;
|
|
26
|
+
}
|
|
27
|
+
export function isMeAlias(alias) {
|
|
28
|
+
return alias.trim().toLowerCase() === 'me';
|
|
29
|
+
}
|
|
30
|
+
export const ME_MISSING = "Every account has its own face with the alias 'me', created with the account, and this one has none. " +
|
|
31
|
+
'That is not something to fix from here. Please report it: https://github.com/faces-sh/cli/issues';
|
|
32
|
+
export function table(headers, rows, right = new Set()) {
|
|
33
|
+
const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)));
|
|
34
|
+
const line = (cells) => cells.map((c, i) => (right.has(headers[i]) ? c.padStart(widths[i]) : c.padEnd(widths[i]))).join(' ').trimEnd();
|
|
35
|
+
return [line(headers), ...rows.map(line)];
|
|
36
|
+
}
|
|
37
|
+
export function isCalendarDate(s) {
|
|
38
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(s))
|
|
39
|
+
return false;
|
|
40
|
+
const d = new Date(`${s}T00:00:00Z`);
|
|
41
|
+
return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s;
|
|
42
|
+
}
|
|
43
|
+
export function usd(n) {
|
|
44
|
+
if (typeof n !== 'number' || !Number.isFinite(n))
|
|
45
|
+
return '-';
|
|
46
|
+
if (n === 0)
|
|
47
|
+
return '$0.00';
|
|
48
|
+
return Math.abs(n) >= 1 ? `$${n.toFixed(2)}` : `$${n.toFixed(4)}`;
|
|
49
|
+
}
|
|
50
|
+
export function similarityText(v) {
|
|
51
|
+
if (typeof v !== 'number' || !Number.isFinite(v))
|
|
52
|
+
return '-';
|
|
53
|
+
return String(Number(v.toFixed(4)));
|
|
54
|
+
}
|
|
55
|
+
export const BINARY_HINTS = {
|
|
56
|
+
'.pdf': 'PDF is supported, but not by this command. Use: faces compile:upload <alias> --file <path> --kind document',
|
|
57
|
+
'.docx': 'Word documents are supported, but not by this command. Use: faces compile:upload <alias> --file <path> --kind document',
|
|
58
|
+
'.doc': "Legacy '.doc' is not supported. Open it in Word or Pages and save as .docx, then upload that with: faces compile:upload <alias> --file <path> --kind document",
|
|
59
|
+
'.pages': 'Pages documents are not supported. Export it as text or PDF first.',
|
|
60
|
+
'.rtf': 'RTF is not supported. Convert it to plain text first (e.g. `textutil -convert txt file.rtf`).',
|
|
61
|
+
'.key': 'Keynote files are not supported. Export the text first.',
|
|
62
|
+
'.pptx': 'PowerPoint files are not supported. Export the text first.',
|
|
63
|
+
'.xlsx': 'Excel files are not supported. Export as .csv first.',
|
|
64
|
+
'.zip': 'Archives are not supported. Extract it and pass the text files.',
|
|
65
|
+
'.epub': 'EPUB is not supported. Convert it to text first.',
|
|
66
|
+
};
|
|
67
|
+
export function readTextFile(file) {
|
|
68
|
+
if (!fs.existsSync(file))
|
|
69
|
+
throw new Error(`File not found: ${file}`);
|
|
70
|
+
const stat = fs.statSync(file);
|
|
71
|
+
if (stat.isDirectory())
|
|
72
|
+
throw new Error(`Not a file: ${file}`);
|
|
73
|
+
const hint = BINARY_HINTS[path.extname(file).toLowerCase()];
|
|
74
|
+
if (hint)
|
|
75
|
+
throw new Error(hint);
|
|
76
|
+
const buf = fs.readFileSync(file);
|
|
77
|
+
if (buf.includes(0))
|
|
78
|
+
throw new Error('Looks like a binary file, not text. Convert it to text first.');
|
|
79
|
+
let content;
|
|
80
|
+
try {
|
|
81
|
+
content = new TextDecoder('utf-8', { fatal: true }).decode(buf);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
throw new Error(`${file} is not UTF-8 text. Convert it first, for example: iconv -f latin1 -t utf-8 ${file} > out.txt`);
|
|
85
|
+
}
|
|
86
|
+
if (content.trim() === '')
|
|
87
|
+
throw new Error(`${file} is empty, or only whitespace.`);
|
|
88
|
+
return content;
|
|
89
|
+
}
|
|
90
|
+
export function transcriptSpeakers(text) {
|
|
91
|
+
const lines = text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
92
|
+
if (lines.length === 0)
|
|
93
|
+
return null;
|
|
94
|
+
const counts = new Map();
|
|
95
|
+
const order = [];
|
|
96
|
+
let labelled = 0;
|
|
97
|
+
for (const line of lines) {
|
|
98
|
+
const m = /^([A-Za-z][\w.'-]*(?: [\w.'-]+){0,3}):\s+\S/.exec(line);
|
|
99
|
+
if (!m)
|
|
100
|
+
continue;
|
|
101
|
+
labelled++;
|
|
102
|
+
const label = m[1];
|
|
103
|
+
if (!counts.has(label))
|
|
104
|
+
order.push(label);
|
|
105
|
+
counts.set(label, (counts.get(label) ?? 0) + 1);
|
|
106
|
+
}
|
|
107
|
+
const speakers = order.filter((l) => (counts.get(l) ?? 0) >= 2);
|
|
108
|
+
if (speakers.length < 2 || labelled < 4 || labelled / lines.length < 0.3)
|
|
109
|
+
return null;
|
|
110
|
+
return speakers;
|
|
111
|
+
}
|
|
112
|
+
export function transcriptWarningLines(text, alias, file) {
|
|
113
|
+
const speakers = transcriptSpeakers(text);
|
|
114
|
+
if (!speakers)
|
|
115
|
+
return [];
|
|
116
|
+
const shown = speakers.slice(0, 4).join(', ') + (speakers.length > 4 ? ', ...' : '');
|
|
117
|
+
return [
|
|
118
|
+
`Warning: ${file ?? 'this text'} reads as an exchange between speakers (${shown}).`,
|
|
119
|
+
'A document is the face\'s own writing, so every line in it, other speakers included, is read as the face\'s words.',
|
|
120
|
+
'Upload an interview, transcript or dialogue as a thread instead, naming the face\'s speaker:',
|
|
121
|
+
threadUploadCommand(alias, file),
|
|
122
|
+
];
|
|
123
|
+
}
|
|
124
|
+
export function withoutWarnings(data) {
|
|
125
|
+
if (!data || typeof data !== 'object' || Array.isArray(data))
|
|
126
|
+
return data;
|
|
127
|
+
const { warnings: _warnings, ...rest } = data;
|
|
128
|
+
return rest;
|
|
129
|
+
}
|
|
130
|
+
function threadUploadCommand(alias, file) {
|
|
131
|
+
return ` faces compile:upload ${alias} --file ${file ?? 'FILE'} --kind thread --face-speaker NAME`;
|
|
132
|
+
}
|
|
133
|
+
export function documentWarningLines(result, text, alias, file) {
|
|
134
|
+
const body = (result && typeof result === 'object' ? result : {});
|
|
135
|
+
if (!Array.isArray(body.warnings))
|
|
136
|
+
return text === undefined ? [] : transcriptWarningLines(text, alias, file);
|
|
137
|
+
const lines = [];
|
|
138
|
+
for (const raw of body.warnings) {
|
|
139
|
+
const w = (raw && typeof raw === 'object' ? raw : {});
|
|
140
|
+
const code = typeof w.code === 'string' ? w.code : undefined;
|
|
141
|
+
const message = typeof w.message === 'string' && w.message.trim() ? w.message.trim() : undefined;
|
|
142
|
+
if (code === 'looks_like_transcript') {
|
|
143
|
+
lines.push(`Warning: ${message ?? 'This looks like a conversation between several speakers. Upload it as a thread instead of a document.'}`);
|
|
144
|
+
lines.push(threadUploadCommand(alias, file));
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (message)
|
|
148
|
+
lines.push(`Warning: ${message}`);
|
|
149
|
+
else if (typeof raw === 'string' && raw.trim())
|
|
150
|
+
lines.push(`Warning: ${raw.trim()}`);
|
|
151
|
+
else if (code)
|
|
152
|
+
lines.push(`Warning: ${code}`);
|
|
153
|
+
}
|
|
154
|
+
return lines;
|
|
155
|
+
}
|
|
156
|
+
export const COMPILE_USD_PER_MILLION = 25;
|
|
157
|
+
export const LARGE_COMPILE_USD = 1;
|
|
158
|
+
export async function compileRate(client) {
|
|
159
|
+
try {
|
|
160
|
+
const raw = (await client.get('/v1/models', { params: { kind: 'compile' } }));
|
|
161
|
+
const rows = (Array.isArray(raw) ? raw : (raw.data ?? []));
|
|
162
|
+
const rate = rows.find((m) => m.kind === 'compile')?.input_cost_per_million_tokens;
|
|
163
|
+
if (typeof rate === 'number' && rate > 0)
|
|
164
|
+
return rate;
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
}
|
|
168
|
+
return COMPILE_USD_PER_MILLION;
|
|
169
|
+
}
|
|
170
|
+
export function compileCostNote(tokens, ratePerMillion) {
|
|
171
|
+
if (typeof tokens !== 'number' || tokens <= 0)
|
|
172
|
+
return undefined;
|
|
173
|
+
const usdCost = (tokens / 1_000_000) * ratePerMillion;
|
|
174
|
+
if (usdCost < LARGE_COMPILE_USD)
|
|
175
|
+
return undefined;
|
|
176
|
+
return (`This source is ${tokens.toLocaleString('en-US')} tokens. Compiling it costs about $${usdCost.toFixed(2)} on credits ` +
|
|
177
|
+
`($${ratePerMillion} per million source tokens); on Connect or Pro the month's compile allowance is used first ` +
|
|
178
|
+
'(see faces compile:stats).');
|
|
179
|
+
}
|
|
180
|
+
export function badToolNames(names) {
|
|
181
|
+
const seen = new Set();
|
|
182
|
+
for (const raw of names) {
|
|
183
|
+
const name = raw.trim();
|
|
184
|
+
if (!name)
|
|
185
|
+
return 'A --tool name is empty.';
|
|
186
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/.test(name))
|
|
187
|
+
return `'${raw}' is not a tool name: use letters, digits, _ . : or -, with no spaces.`;
|
|
188
|
+
if (seen.has(name))
|
|
189
|
+
return `'${name}' is given twice.`;
|
|
190
|
+
seen.add(name);
|
|
191
|
+
}
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
export function badFaceName(name) {
|
|
195
|
+
if (!name.trim())
|
|
196
|
+
return 'The name is empty.';
|
|
197
|
+
if (name.length > 200)
|
|
198
|
+
return `The name is ${name.length} characters; keep it to 200 or fewer.`;
|
|
199
|
+
if (/[\u0000-\u001f\u007f\u202a-\u202e\u2066-\u2069]/.test(name))
|
|
200
|
+
return 'The name contains control or text-direction characters.';
|
|
201
|
+
return undefined;
|
|
202
|
+
}
|
|
203
|
+
export function compact(obj) {
|
|
204
|
+
if (!obj || typeof obj !== 'object' || Array.isArray(obj))
|
|
205
|
+
return obj;
|
|
206
|
+
return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== null && v !== undefined));
|
|
207
|
+
}
|
|
208
|
+
export function resolveProfileAddendum(text, file) {
|
|
209
|
+
let value;
|
|
210
|
+
if (file !== undefined) {
|
|
211
|
+
if (!fs.existsSync(file))
|
|
212
|
+
throw new Error(`File not found: ${file}`);
|
|
213
|
+
value = fs.readFileSync(file, 'utf8');
|
|
214
|
+
}
|
|
215
|
+
else if (text !== undefined) {
|
|
216
|
+
value = text;
|
|
217
|
+
}
|
|
218
|
+
if (value !== undefined && value.length > PROFILE_ADDENDUM_MAX_CHARS) {
|
|
219
|
+
throw new Error(`--profile-addendum is ${value.length} chars; max is ${PROFILE_ADDENDUM_MAX_CHARS}.`);
|
|
220
|
+
}
|
|
221
|
+
return value;
|
|
222
|
+
}
|
|
223
|
+
export function resolveCause(text, file) {
|
|
224
|
+
let value = text;
|
|
225
|
+
if (file !== undefined) {
|
|
226
|
+
if (!fs.existsSync(file))
|
|
227
|
+
throw new Error(`File not found: ${file}`);
|
|
228
|
+
value = fs.readFileSync(file, 'utf8');
|
|
229
|
+
}
|
|
230
|
+
return value !== undefined && value.trim() ? value : undefined;
|
|
231
|
+
}
|
|
232
|
+
export const CAUSE_FLAG_DESCRIPTION = 'Supply this turn\'s cause yourself, at most 30,000 tokens. The model answers on it in place of the ' +
|
|
233
|
+
'face\'s own, and no cause is charged. Needs a model named (alias@model). It comes back where a cause ' +
|
|
234
|
+
'normally does.';
|
|
235
|
+
export const CAUSE_FILE_FLAG_DESCRIPTION = 'Read --cause from a file.';
|
|
236
|
+
export function causeNeedsModel(face) {
|
|
237
|
+
return (`--cause needs a model to answer on it: ${face}@<model>. A face named alone returns only its own ` +
|
|
238
|
+
'cause, so there is nothing to supply.');
|
|
239
|
+
}
|
|
240
|
+
export function flattenAttributes(facts) {
|
|
241
|
+
const flat = {};
|
|
242
|
+
for (const [k, v] of Object.entries(facts)) {
|
|
243
|
+
if (typeof v === 'object' && v !== null && 'value' in v) {
|
|
244
|
+
flat[k] = String(v.value);
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
flat[k] = String(v);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return flat;
|
|
251
|
+
}
|
|
252
|
+
export const flattenBasicFacts = flattenAttributes;
|
|
253
|
+
export function renameFaceFields(face) {
|
|
254
|
+
if (face.basic_facts !== undefined) {
|
|
255
|
+
face.attributes = typeof face.basic_facts === 'object' && face.basic_facts !== null
|
|
256
|
+
? flattenAttributes(face.basic_facts)
|
|
257
|
+
: face.basic_facts;
|
|
258
|
+
delete face.basic_facts;
|
|
259
|
+
}
|
|
260
|
+
return face;
|
|
261
|
+
}
|
|
262
|
+
export function extractStreamDelta(parsed) {
|
|
263
|
+
if (parsed.type === 'content_block_delta') {
|
|
264
|
+
return String(parsed.delta?.text ?? '');
|
|
265
|
+
}
|
|
266
|
+
if (parsed.type === 'response.output_text.delta') {
|
|
267
|
+
return String(parsed.delta ?? '');
|
|
268
|
+
}
|
|
269
|
+
const choices = parsed.choices;
|
|
270
|
+
return String(choices?.[0]?.delta?.content ?? '');
|
|
271
|
+
}
|
|
272
|
+
export function extractStreamReasoning(parsed) {
|
|
273
|
+
if (parsed.type === 'content_block_delta') {
|
|
274
|
+
if (parsed.index !== 0)
|
|
275
|
+
return '';
|
|
276
|
+
return String(parsed.delta?.thinking ?? '');
|
|
277
|
+
}
|
|
278
|
+
if (parsed.type === 'response.reasoning_summary_text.delta') {
|
|
279
|
+
const item = parsed.item_id;
|
|
280
|
+
if (typeof item === 'string' && !item.startsWith('rs_faces_'))
|
|
281
|
+
return '';
|
|
282
|
+
return String(parsed.delta ?? '');
|
|
283
|
+
}
|
|
284
|
+
const choices = parsed.choices;
|
|
285
|
+
return String(choices?.[0]?.delta?.cause ?? '');
|
|
286
|
+
}
|
|
287
|
+
export const FACES_THINKING_SIGNATURE = 'faces-reasoning';
|
|
288
|
+
export const FACES_REASONING_ITEM_PREFIX = 'rs_faces_';
|
|
289
|
+
export function extractCause(body, endpoint) {
|
|
290
|
+
if (endpoint === '/v1/messages') {
|
|
291
|
+
const block = body.content?.find((b) => b.type === 'thinking' && b.signature === FACES_THINKING_SIGNATURE);
|
|
292
|
+
return { text: block ? String(block.thinking ?? '') : '' };
|
|
293
|
+
}
|
|
294
|
+
if (endpoint === '/v1/responses') {
|
|
295
|
+
const item = body.output?.find((o) => o.type === 'reasoning' && String(o.id ?? '').startsWith(FACES_REASONING_ITEM_PREFIX));
|
|
296
|
+
if (!item)
|
|
297
|
+
return { text: '' };
|
|
298
|
+
const text = (item.summary ?? []).map((s) => String(s.text ?? '')).join('\n');
|
|
299
|
+
return { text, id: String(item.id) };
|
|
300
|
+
}
|
|
301
|
+
const choices = body.choices;
|
|
302
|
+
return { text: String(choices?.[0]?.message?.cause ?? '') };
|
|
303
|
+
}
|
|
304
|
+
export function extractReasoning(body, endpoint) {
|
|
305
|
+
return extractCause(body, endpoint).text;
|
|
306
|
+
}
|
|
307
|
+
export const REASONING_FLAG_DESCRIPTION = 'Also show the face\'s cause: the principal why behind its response in this context. Printed to ' +
|
|
308
|
+
'stderr ahead of the reply, so the reply alone still goes to stdout.';
|
|
309
|
+
export function reasoningHeading(face) {
|
|
310
|
+
return `${face.replace(/@.*$/, '')}'s cause:`;
|
|
311
|
+
}
|
|
312
|
+
export function reasoningOnlyNote(face, llmFlag = true) {
|
|
313
|
+
const bare = face.replace(/@.*$/, '');
|
|
314
|
+
return `That is ${bare}'s cause alone: a face named without a model gives no reply. ` +
|
|
315
|
+
`For one, name the model: ${bare}@<model>${llmFlag ? ', or add --llm <model>' : ''}.`;
|
|
316
|
+
}
|
|
317
|
+
export function writeReply(model, reasoning, text, showReasoning, note) {
|
|
318
|
+
if (!text && reasoning) {
|
|
319
|
+
process.stdout.write(`${reasoning}\n`);
|
|
320
|
+
if (note)
|
|
321
|
+
process.stderr.write(`\n${note}\n`);
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (showReasoning && reasoning)
|
|
325
|
+
process.stderr.write(`${reasoningHeading(model)}\n${reasoning}\n\n`);
|
|
326
|
+
process.stdout.write(`${text}\n`);
|
|
327
|
+
}
|
|
328
|
+
export const STREAM_FLAG_DESCRIPTION = 'Stream the reply as it is written (the default). --no-stream waits for the whole reply instead. ' +
|
|
329
|
+
'Either way a face has up to 300s to answer; past that the request is stopped and can be asked again. ' +
|
|
330
|
+
'--json is never streamed.';
|
|
331
|
+
export async function postChat(client, endpoint, payload) {
|
|
332
|
+
const res = await client.postWithHeaders(endpoint, { body: payload });
|
|
333
|
+
const held = heldChatError(res.data);
|
|
334
|
+
if (held)
|
|
335
|
+
throw held;
|
|
336
|
+
return res;
|
|
337
|
+
}
|
|
338
|
+
export async function retryOnceOnWarmUp(send, say) {
|
|
339
|
+
try {
|
|
340
|
+
return await send();
|
|
341
|
+
}
|
|
342
|
+
catch (err) {
|
|
343
|
+
if (!(err instanceof FacesAPIError) || err.statusCode !== 503 || err.retryable === false)
|
|
344
|
+
throw err;
|
|
345
|
+
const wait = err.retryAfter;
|
|
346
|
+
if (wait === undefined || wait > MAX_WARM_UP_WAIT_S)
|
|
347
|
+
throw err;
|
|
348
|
+
say?.(wait);
|
|
349
|
+
await new Promise((r) => setTimeout(r, wait * 1000));
|
|
350
|
+
return send();
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
export async function* streamChat(client, endpoint, payload, onHeaders) {
|
|
354
|
+
let lines = client.stream(endpoint, payload, { onHeaders });
|
|
355
|
+
let first;
|
|
356
|
+
try {
|
|
357
|
+
first = await lines.next();
|
|
358
|
+
}
|
|
359
|
+
catch (err) {
|
|
360
|
+
if (!(err instanceof FacesAPIError) || !isMaxTokensRenameError(err.message) || payload.max_tokens === undefined)
|
|
361
|
+
throw err;
|
|
362
|
+
payload.max_completion_tokens = payload.max_tokens;
|
|
363
|
+
delete payload.max_tokens;
|
|
364
|
+
lines = client.stream(endpoint, payload, { onHeaders });
|
|
365
|
+
first = await lines.next();
|
|
366
|
+
}
|
|
367
|
+
if (first.done)
|
|
368
|
+
return;
|
|
369
|
+
yield first.value;
|
|
370
|
+
yield* lines;
|
|
371
|
+
}
|
|
372
|
+
export function sayWarmUp(seconds) {
|
|
373
|
+
process.stderr.write(`Not ready yet. Asking again in ${seconds}s.\n`);
|
|
374
|
+
}
|
|
375
|
+
export function compileHint(face, recompile, verb = 'answer') {
|
|
376
|
+
if (/[|&^()]/.test(face) || /\S\s+\S/.test(face)) {
|
|
377
|
+
return recompile
|
|
378
|
+
? `Every face in ${face} needs recompiling before it can ${verb}: compile one of each one's sources again.`
|
|
379
|
+
: `Every face in ${face} needs something compiled: faces compile:upload <alias> --file <file> for each.`;
|
|
380
|
+
}
|
|
381
|
+
if (face.includes(':')) {
|
|
382
|
+
return recompile ? `${face} needs recompiling by its owner before it can ${verb}.` : `${face} has nothing compiled yet; that is for its owner to do.`;
|
|
383
|
+
}
|
|
384
|
+
return recompile
|
|
385
|
+
? `${face} needs recompiling before it can ${verb}: compile one of its sources again ` +
|
|
386
|
+
`(list them with: faces face:sources ${face}). Asking again as it is will not help.`
|
|
387
|
+
: `Give it a first source: faces compile:upload ${face} --file <file>. A saved composite needs one on each face in its formula.`;
|
|
388
|
+
}
|
|
389
|
+
export function faceRefusalHint(err, model, style) {
|
|
390
|
+
const face = model.replace(/@[^@]*$/, '');
|
|
391
|
+
if (style && (err.errorCode === 'style_medium_unavailable' || /has no (styles? yet|.* style)/i.test(err.message))) {
|
|
392
|
+
return `Build one: faces style:make ${face} --all\nOr leave out --style to answer without a built style.`;
|
|
393
|
+
}
|
|
394
|
+
if (err.statusCode === 409) {
|
|
395
|
+
return compileHint(face, !/nothing compiled/i.test(err.message));
|
|
396
|
+
}
|
|
397
|
+
if (err.statusCode === 404 && isMeAlias(face))
|
|
398
|
+
return ME_MISSING;
|
|
399
|
+
if (err.statusCode === 504)
|
|
400
|
+
return 'The face did not finish within 300 seconds. Ask again.';
|
|
401
|
+
if (err.statusCode === 503) {
|
|
402
|
+
if (err.retryable === false)
|
|
403
|
+
return undefined;
|
|
404
|
+
return err.retryAfter !== undefined ? `Try again in ${err.retryAfter}s.` : 'Try again.';
|
|
405
|
+
}
|
|
406
|
+
return undefined;
|
|
407
|
+
}
|
|
408
|
+
export const MIN_MAX_OUTPUT_TOKENS = 16;
|
|
409
|
+
export function isMaxTokensRenameError(message) {
|
|
410
|
+
return /max_completion_tokens/.test(message) && /max_tokens/.test(message);
|
|
411
|
+
}
|
|
412
|
+
const MEDIUM_LIST = 'What sort of writing this is, spelled exactly: email, text message, social post, essay, ' +
|
|
413
|
+
'academic paper, blog post, legal document, thread reply, conversation, lecture, other. ' +
|
|
414
|
+
'Reach for lecture for sustained speech nobody interrupts (a talk, a sermon, a keynote), and ' +
|
|
415
|
+
'other for writing that is none of the named forms, read as prose with no form-specific ' +
|
|
416
|
+
'conventions assumed. Those descriptions are not accepted inputs: send the value itself.';
|
|
417
|
+
export const DOCUMENT_VS_THREAD = 'A document is the face\'s own writing (an essay, letter, paper, book or poem), and every word ' +
|
|
418
|
+
'in it is read as theirs. An interview, transcript or dialogue is a thread: upload it with ' +
|
|
419
|
+
'faces compile:upload ALIAS --file FILE --kind thread --face-speaker NAME, so only the face\'s ' +
|
|
420
|
+
'turns are used.';
|
|
421
|
+
export const STYLE_FLAG_DESCRIPTION = 'Apply the style the face has built for this medium, one of: email, text message, social post, essay, ' +
|
|
422
|
+
'academic paper, blog post, legal document, thread reply, conversation, lecture, other. Leave it out and ' +
|
|
423
|
+
'no built style is applied. A face with no style in that medium is refused, naming the ones it has ' +
|
|
424
|
+
'(see them with faces face:get). Needs a single face and a model. Adds roughly 2,000 to 3,500 input ' +
|
|
425
|
+
'tokens per request. Sets --medium too. Chat commands only: causes and decide do not use a style.';
|
|
426
|
+
export const MEDIUM_FLAG_DESCRIPTION = 'What the reply is, so it is shaped for it: email, text message, social post, essay, academic paper, ' +
|
|
427
|
+
'blog post, legal document, thread reply, conversation, lecture, other. Needs no built style. Leave it ' +
|
|
428
|
+
'out and the medium is inferred from your message. With --style, leave it out or give the same medium.';
|
|
429
|
+
export const SESSION_FLAG_DESCRIPTION = 'Add this turn to a session, by id (from faces session:create). The session must be with this face.';
|
|
430
|
+
export const COMPACTION_FLAG_DESCRIPTION = 'Read a compaction, by id (from faces session:compact), alongside the messages sent. It must be of a ' +
|
|
431
|
+
'session with this face.';
|
|
432
|
+
export function chatExtras(flags) {
|
|
433
|
+
const out = {};
|
|
434
|
+
if (flags.style)
|
|
435
|
+
out.style = flags.style;
|
|
436
|
+
if (flags.medium)
|
|
437
|
+
out.medium = flags.medium;
|
|
438
|
+
if (flags.session)
|
|
439
|
+
out.session = flags.session;
|
|
440
|
+
if (flags.compaction)
|
|
441
|
+
out.compaction = flags.compaction;
|
|
442
|
+
return out;
|
|
443
|
+
}
|
|
444
|
+
export const MEDIUM_EDIT_DESCRIPTION = () => MEDIUM_LIST + ' Omit it to leave the medium as it is.';
|
|
445
|
+
export const MEDIUM_REQUIRED_DESCRIPTION = MEDIUM_LIST +
|
|
446
|
+
' ' + DOCUMENT_VS_THREAD +
|
|
447
|
+
' A document cannot be saved without saying what it is, so this is required rather than ' +
|
|
448
|
+
'optional. Here the spelling is held to exactly: case and surrounding spaces are forgiven and ' +
|
|
449
|
+
'nothing else is, so an unknown word is refused naming all eleven rather than being folded into ' +
|
|
450
|
+
'a near match. Do not guess one: a wrong medium is not flagged afterwards. If none of the ' +
|
|
451
|
+
'named forms fit, that is what other is for. If one of them ' +
|
|
452
|
+
'does fit and you simply have not been told which, ask.';
|
|
453
|
+
export const MEDIUM_MISSING_MESSAGE = 'Say what this writing is with --medium: a document cannot be saved without one.\n' +
|
|
454
|
+
'One of: email, text message, social post, essay, academic paper, blog post, legal document, ' +
|
|
455
|
+
'thread reply, conversation, lecture, other.\n' +
|
|
456
|
+
'`other` is for writing that is none of those: it compiles, and is read as prose with no ' +
|
|
457
|
+
'form-specific conventions assumed. It is the honest answer when nothing fits, and the wrong ' +
|
|
458
|
+
'answer for a letter or a memo, which are forms with rules of their own.\n' +
|
|
459
|
+
'A document saved before this was required is declared with: faces compile:doc:edit <id> --medium <medium>.';
|
|
460
|
+
export function warnDroppedParams(headers, flagFor) {
|
|
461
|
+
const raw = headers['x-faces-dropped-params'];
|
|
462
|
+
if (!raw)
|
|
463
|
+
return;
|
|
464
|
+
const flags = raw
|
|
465
|
+
.split(',')
|
|
466
|
+
.map((p) => p.trim())
|
|
467
|
+
.filter(Boolean)
|
|
468
|
+
.map((p) => flagFor[p] ?? `--${p.replaceAll('_', '-')}`);
|
|
469
|
+
if (flags.length === 0)
|
|
470
|
+
return;
|
|
471
|
+
process.stderr.write(`Note: ${flags.join(' and ')} had no effect. This request ran on your linked ChatGPT account, ` +
|
|
472
|
+
'which does not accept them. Use --no-oauth-only to run on the paid API instead.\n');
|
|
473
|
+
}
|
|
474
|
+
export const CHAT_PARAM_FLAGS = {
|
|
475
|
+
max_output_tokens: '--max-tokens',
|
|
476
|
+
max_tokens: '--max-tokens',
|
|
477
|
+
max_completion_tokens: '--max-tokens',
|
|
478
|
+
temperature: '--temperature',
|
|
479
|
+
};
|
|
480
|
+
export async function resolveFace(client, spec, include = 'profile') {
|
|
481
|
+
const at = spec.indexOf(':');
|
|
482
|
+
const owner = at === -1 ? undefined : spec.slice(0, at);
|
|
483
|
+
const alias = at === -1 ? spec : spec.slice(at + 1);
|
|
484
|
+
const q = `include=${encodeURIComponent(include)}`;
|
|
485
|
+
if (!owner) {
|
|
486
|
+
try {
|
|
487
|
+
const face = (await client.get(`/v1/faces/${seg(alias)}?${q}`));
|
|
488
|
+
const me = await currentUsername(client);
|
|
489
|
+
const by = typeof face.owned_by === 'string' ? face.owned_by : undefined;
|
|
490
|
+
if (me && by && by !== me)
|
|
491
|
+
return { face, owned: false, handle: `${by}:${alias}` };
|
|
492
|
+
return { face, owned: true, handle: alias };
|
|
493
|
+
}
|
|
494
|
+
catch (err) {
|
|
495
|
+
if (!(err instanceof FacesAPIError) || err.statusCode !== 403)
|
|
496
|
+
throw err;
|
|
497
|
+
const found = await findForeignFace(client, alias, undefined, q);
|
|
498
|
+
if (found)
|
|
499
|
+
return found;
|
|
500
|
+
throw err;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
const found = await findForeignFace(client, alias, owner, q);
|
|
504
|
+
if (found)
|
|
505
|
+
return found;
|
|
506
|
+
throw new FacesAPIError(404, `Face ${spec} not found`);
|
|
507
|
+
}
|
|
508
|
+
let usernameCache;
|
|
509
|
+
export function currentUsername(client) {
|
|
510
|
+
usernameCache ??= (async () => {
|
|
511
|
+
try {
|
|
512
|
+
const me = (await client.get('/auth/me'));
|
|
513
|
+
const data = (me.data ?? me);
|
|
514
|
+
return typeof data.username === 'string' ? data.username : undefined;
|
|
515
|
+
}
|
|
516
|
+
catch {
|
|
517
|
+
return undefined;
|
|
518
|
+
}
|
|
519
|
+
})();
|
|
520
|
+
return usernameCache;
|
|
521
|
+
}
|
|
522
|
+
export async function ownsFace(client, spec) {
|
|
523
|
+
const me = await currentUsername(client);
|
|
524
|
+
if (!me)
|
|
525
|
+
return undefined;
|
|
526
|
+
const at = spec.indexOf(':');
|
|
527
|
+
if (at !== -1)
|
|
528
|
+
return spec.slice(0, at) === me;
|
|
529
|
+
try {
|
|
530
|
+
const face = (await client.get(`/v1/faces/${seg(spec)}`));
|
|
531
|
+
return typeof face.owned_by === 'string' ? face.owned_by === me : undefined;
|
|
532
|
+
}
|
|
533
|
+
catch {
|
|
534
|
+
return undefined;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
async function findForeignFace(client, alias, owner, q) {
|
|
538
|
+
const parts = [q, 'include_published=true', 'include_shared=true'];
|
|
539
|
+
if (owner)
|
|
540
|
+
parts.push(`from_users=${encodeURIComponent(owner)}`);
|
|
541
|
+
let rows;
|
|
542
|
+
try {
|
|
543
|
+
const data = await client.get(`/v1/faces?${parts.join('&')}`);
|
|
544
|
+
rows = (data.data ??
|
|
545
|
+
data);
|
|
546
|
+
}
|
|
547
|
+
catch {
|
|
548
|
+
return undefined;
|
|
549
|
+
}
|
|
550
|
+
const hit = rows.find((f) => f.alias === alias && (owner === undefined || f.owned_by === owner));
|
|
551
|
+
if (!hit)
|
|
552
|
+
return undefined;
|
|
553
|
+
const ownedBy = hit.owned_by;
|
|
554
|
+
return {
|
|
555
|
+
face: hit,
|
|
556
|
+
owned: false,
|
|
557
|
+
handle: ownedBy ? `${ownedBy}:${alias}` : alias,
|
|
558
|
+
owner: ownedBy,
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
export const MAX_FRONTMATTER_VALUE = 64 * 1024;
|
|
562
|
+
export function quoteYaml(value) {
|
|
563
|
+
if (/[:#[\]{}&*!|>'"%@`\n]/.test(value) || value !== value.trim() || value === '') {
|
|
564
|
+
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
565
|
+
}
|
|
566
|
+
return value;
|
|
567
|
+
}
|
|
568
|
+
export function unquoteYaml(raw) {
|
|
569
|
+
const trimmed = raw.trim();
|
|
570
|
+
const m = /^"([\S\s]*)"$/.exec(trimmed);
|
|
571
|
+
if (!m)
|
|
572
|
+
return trimmed;
|
|
573
|
+
return m[1].replace(/\\(["\\])/g, '$1');
|
|
574
|
+
}
|
|
575
|
+
export function faceStyles(face) {
|
|
576
|
+
return Array.isArray(face.styles) ? face.styles.filter((m) => typeof m === 'string') : [];
|
|
577
|
+
}
|
|
578
|
+
const CORPUS_THREAD_FIX = 'This is a corpus thread, uploaded material for building a style rather than a thread to compile. Build a ' +
|
|
579
|
+
'style from it with faces style:make, or upload the same material with --kind thread to compile it.';
|
|
580
|
+
export const COMPILE_BLOCKED_FIX = {
|
|
581
|
+
no_medium: 'Say what it is, then compile again: faces compile:doc:edit <id> --medium essay',
|
|
582
|
+
empty: 'There is nothing to compile. Add content with: faces compile:doc:edit <id> --file <path>',
|
|
583
|
+
no_user_messages: 'Nothing in it was written by the subject, so there is nothing to compile. A fresh interview holds ' +
|
|
584
|
+
'only the interviewer question; it becomes compilable on the first answer.',
|
|
585
|
+
corpus_thread: CORPUS_THREAD_FIX,
|
|
586
|
+
already_compiled: 'To compile it again: edit it, or faces compile:doc:reset <id> (compile:thread:reset for a thread) ' +
|
|
587
|
+
'and then make it.',
|
|
588
|
+
};
|
|
589
|
+
export function compileBlockedLabel(reason) {
|
|
590
|
+
if (!reason)
|
|
591
|
+
return '';
|
|
592
|
+
const words = {
|
|
593
|
+
no_medium: 'no medium declared',
|
|
594
|
+
empty: 'no content',
|
|
595
|
+
no_user_messages: 'nothing by the subject',
|
|
596
|
+
corpus_thread: 'corpus thread',
|
|
597
|
+
too_short: 'under 50 words',
|
|
598
|
+
};
|
|
599
|
+
return words[reason] ?? reason;
|
|
600
|
+
}
|
|
601
|
+
export function freshnessOf(s) {
|
|
602
|
+
const { version, synced_version: syncedVersion } = s;
|
|
603
|
+
if (version === null || version === undefined)
|
|
604
|
+
return 'unknown';
|
|
605
|
+
if (syncedVersion === null || syncedVersion === undefined)
|
|
606
|
+
return 'unknown';
|
|
607
|
+
return syncedVersion < version ? 'stale' : 'current';
|
|
608
|
+
}
|
|
609
|
+
export function revisionsBehind(s) {
|
|
610
|
+
if (freshnessOf(s) !== 'stale')
|
|
611
|
+
return null;
|
|
612
|
+
return s.version - s.synced_version;
|
|
613
|
+
}
|
|
614
|
+
export function messagesAfterSync(messages, syncedAt) {
|
|
615
|
+
if (!messages?.length || !syncedAt)
|
|
616
|
+
return { newer: 0, unknown: 0 };
|
|
617
|
+
const sync = toEpoch(syncedAt);
|
|
618
|
+
if (sync === null)
|
|
619
|
+
return { newer: 0, unknown: messages.length };
|
|
620
|
+
let newer = 0;
|
|
621
|
+
let unknown = 0;
|
|
622
|
+
for (const m of messages) {
|
|
623
|
+
const t = m.timestamp ? toEpoch(m.timestamp) : null;
|
|
624
|
+
if (t === null)
|
|
625
|
+
unknown++;
|
|
626
|
+
else if (t > sync)
|
|
627
|
+
newer++;
|
|
628
|
+
}
|
|
629
|
+
return { newer, unknown };
|
|
630
|
+
}
|
|
631
|
+
function toEpoch(iso) {
|
|
632
|
+
const naive = iso.trim().replace(/(?:Z|[+-]\d{2}:?\d{2})$/, '');
|
|
633
|
+
const ms = Date.parse(naive);
|
|
634
|
+
return Number.isNaN(ms) ? null : ms;
|
|
635
|
+
}
|
|
636
|
+
export function freshnessLines(s, recompile, id) {
|
|
637
|
+
const lines = [];
|
|
638
|
+
const behind = revisionsBehind(s);
|
|
639
|
+
if (behind !== null) {
|
|
640
|
+
lines.push(`Stale: the text is ${behind} revision(s) ahead of the last compile.`);
|
|
641
|
+
if (s.compilable !== false)
|
|
642
|
+
lines.push(` Bring the compile up to date with: ${recompile}`);
|
|
643
|
+
}
|
|
644
|
+
if (s.compilable === false) {
|
|
645
|
+
lines.push(`A compile would be refused: ${compileBlockedLabel(s.compile_blocked_reason)}.`);
|
|
646
|
+
const fix = s.compile_blocked_reason ? COMPILE_BLOCKED_FIX[s.compile_blocked_reason] : undefined;
|
|
647
|
+
if (fix)
|
|
648
|
+
lines.push(` ${id ? fix.replaceAll('<id>', id) : fix}`);
|
|
649
|
+
}
|
|
650
|
+
return lines;
|
|
651
|
+
}
|
|
652
|
+
export function freshnessSummary(items, noun) {
|
|
653
|
+
let stale = 0;
|
|
654
|
+
const blocked = new Map();
|
|
655
|
+
for (const s of items) {
|
|
656
|
+
if (revisionsBehind(s) !== null)
|
|
657
|
+
stale++;
|
|
658
|
+
if (s.compilable === false) {
|
|
659
|
+
const why = compileBlockedLabel(s.compile_blocked_reason) || 'refused';
|
|
660
|
+
blocked.set(why, (blocked.get(why) ?? 0) + 1);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
const lines = [];
|
|
664
|
+
if (stale > 0)
|
|
665
|
+
lines.push(`${stale} ${noun}(s) changed since the last compile and need recompiling.`);
|
|
666
|
+
if (blocked.size > 0) {
|
|
667
|
+
const parts = [...blocked.entries()].sort((a, b) => b[1] - a[1]).map(([why, n]) => `${n} ${why}`);
|
|
668
|
+
lines.push(`${[...blocked.values()].reduce((a, b) => a + b, 0)} the server would refuse: ${parts.join(', ')}.`);
|
|
669
|
+
}
|
|
670
|
+
return lines;
|
|
671
|
+
}
|
|
672
|
+
export const UPLOAD_WARNING_HELP = {
|
|
673
|
+
unattributed_lines: {
|
|
674
|
+
says: 'lines before the first recognised "Speaker:" prefix. They are not in the thread.',
|
|
675
|
+
fix: 'If they matter, give them a speaker prefix and upload again.',
|
|
676
|
+
},
|
|
677
|
+
face_speaker_not_found: {
|
|
678
|
+
says: 'the name given as --face-speaker matched nobody in the file, so this face has no turns of its own.',
|
|
679
|
+
fix: 'Check how the name is spelled in the file and re-upload with --face-speaker set to that.',
|
|
680
|
+
},
|
|
681
|
+
};
|
|
682
|
+
export function uploadWarningLines(result) {
|
|
683
|
+
const items = Array.isArray(result.warnings) ? result.warnings : [];
|
|
684
|
+
const count = typeof result.warning_count === 'number' ? result.warning_count : items.length;
|
|
685
|
+
if (count === 0 && items.length === 0)
|
|
686
|
+
return [];
|
|
687
|
+
const lines = [`Warning: ${count} part(s) of the file did not become messages.`];
|
|
688
|
+
for (const w of items) {
|
|
689
|
+
const code = typeof w.code === 'string' ? w.code : 'unknown';
|
|
690
|
+
const help = UPLOAD_WARNING_HELP[code];
|
|
691
|
+
const said = typeof w.message === 'string' && w.message !== '' ? w.message : help?.says;
|
|
692
|
+
lines.push(` ${code}: ${said ?? 'see --json for detail.'}`);
|
|
693
|
+
if (help?.fix)
|
|
694
|
+
lines.push(` ${help.fix}`);
|
|
695
|
+
}
|
|
696
|
+
if (count > items.length) {
|
|
697
|
+
lines.push(` Showing ${items.length} of ${count}; the rest are in the same shape.`);
|
|
698
|
+
}
|
|
699
|
+
return lines;
|
|
700
|
+
}
|
|
701
|
+
export function readablePatternError(message) {
|
|
702
|
+
const m = /^(?:query|body) → ([a-z_]+): String should match pattern '\^\(([^)]+)\)\$'$/.exec(message.trim());
|
|
703
|
+
if (!m)
|
|
704
|
+
return message;
|
|
705
|
+
const [, field, alternatives] = m;
|
|
706
|
+
const values = alternatives.split('|').filter(Boolean);
|
|
707
|
+
if (values.length === 0)
|
|
708
|
+
return message;
|
|
709
|
+
return `--${field.replaceAll('_', '-')} must be one of: ${values.join(', ')}`;
|
|
710
|
+
}
|
|
711
|
+
const COMPILE_STATUSES = new Set([
|
|
712
|
+
'not_compiled',
|
|
713
|
+
'transcribing',
|
|
714
|
+
'queued',
|
|
715
|
+
'compiling',
|
|
716
|
+
'compiled',
|
|
717
|
+
'paused',
|
|
718
|
+
'failed',
|
|
719
|
+
]);
|
|
720
|
+
export function compileStatusOf(status) {
|
|
721
|
+
if (status === null || status === undefined || status === '')
|
|
722
|
+
return null;
|
|
723
|
+
const s = String(status);
|
|
724
|
+
return COMPILE_STATUSES.has(s) ? s : 'compiling';
|
|
725
|
+
}
|
|
726
|
+
export function compileProgressLabel(g, now = Date.now()) {
|
|
727
|
+
const status = compileStatusOf(g.status);
|
|
728
|
+
if (status === 'queued') {
|
|
729
|
+
const at = startsAtMs(g.starts_at);
|
|
730
|
+
if (g.rush === true)
|
|
731
|
+
return 'queued, rush';
|
|
732
|
+
if (at !== undefined && at > now)
|
|
733
|
+
return `queued, starts ${localTime(g.starts_at)}`;
|
|
734
|
+
return 'queued';
|
|
735
|
+
}
|
|
736
|
+
if (status === 'compiled' || status === 'not_compiled') {
|
|
737
|
+
return status.replace('_', ' ');
|
|
738
|
+
}
|
|
739
|
+
const gated = g.measurable === undefined ? true : Boolean(g.measurable);
|
|
740
|
+
const word = status ?? '';
|
|
741
|
+
if (gated && typeof g.progress === 'number' && Number.isFinite(g.progress)) {
|
|
742
|
+
const pct = `${Math.floor(Math.min(1, Math.max(0, g.progress)) * 100)}%`;
|
|
743
|
+
return word ? `${word}, ${pct}` : pct;
|
|
744
|
+
}
|
|
745
|
+
return word || 'working, progress not known yet';
|
|
746
|
+
}
|
|
747
|
+
export function readableLimit(n, unit = '') {
|
|
748
|
+
if (typeof n !== 'number')
|
|
749
|
+
return n === null || n === undefined ? '-' : String(n);
|
|
750
|
+
if (n < 0)
|
|
751
|
+
return 'unlimited';
|
|
752
|
+
return unit ? `${n} ${unit}` : String(n);
|
|
753
|
+
}
|
|
754
|
+
export const RUSH_FLAG_DESCRIPTION = 'Start the compile now, at the rush rate, rather than at its scheduled start. faces compile:stats shows ' +
|
|
755
|
+
'both rates. A rush covered by a plan\'s compile allowance pays only the difference, from credit. Where ' +
|
|
756
|
+
'a compile starts at once anyway, this changes nothing and costs nothing extra.';
|
|
757
|
+
function startsAtMs(iso) {
|
|
758
|
+
if (typeof iso !== 'string' || !iso)
|
|
759
|
+
return undefined;
|
|
760
|
+
const zoned = /(Z|[+-]\d{2}:?\d{2})$/i.test(iso) ? iso : `${iso}Z`;
|
|
761
|
+
const ms = Date.parse(zoned);
|
|
762
|
+
return Number.isNaN(ms) ? undefined : ms;
|
|
763
|
+
}
|
|
764
|
+
export function localTime(iso) {
|
|
765
|
+
const ms = startsAtMs(iso);
|
|
766
|
+
if (ms === undefined)
|
|
767
|
+
return typeof iso === 'string' ? iso : '-';
|
|
768
|
+
const d = new Date(ms);
|
|
769
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
770
|
+
const tz = new Intl.DateTimeFormat('en-US', { timeZoneName: 'short' }).formatToParts(d)
|
|
771
|
+
.find((x) => x.type === 'timeZoneName')?.value;
|
|
772
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}${tz ? ` ${tz}` : ''}`;
|
|
773
|
+
}
|
|
774
|
+
function untilText(ms) {
|
|
775
|
+
const mins = Math.ceil(ms / 60_000);
|
|
776
|
+
if (mins <= 0)
|
|
777
|
+
return 'now';
|
|
778
|
+
if (mins < 60)
|
|
779
|
+
return `in ${mins} min`;
|
|
780
|
+
const h = Math.floor(mins / 60);
|
|
781
|
+
const m = mins % 60;
|
|
782
|
+
return m ? `in ${h} h ${m} min` : `in ${h} h`;
|
|
783
|
+
}
|
|
784
|
+
export function startsAtLine(iso, now = Date.now()) {
|
|
785
|
+
const ms = startsAtMs(iso);
|
|
786
|
+
if (ms === undefined)
|
|
787
|
+
return undefined;
|
|
788
|
+
return ms > now
|
|
789
|
+
? `Scheduled start: ${localTime(iso)} (${untilText(ms - now)})`
|
|
790
|
+
: `Started: ${localTime(iso)}`;
|
|
791
|
+
}
|
|
792
|
+
export function msUntilStart(iso, now = Date.now()) {
|
|
793
|
+
const ms = startsAtMs(iso);
|
|
794
|
+
return ms === undefined ? 0 : Math.max(0, ms - now);
|
|
795
|
+
}
|
|
796
|
+
export function makeScheduleLines(resp, askedRush, now = Date.now()) {
|
|
797
|
+
const lines = [];
|
|
798
|
+
if (resp.rush === true) {
|
|
799
|
+
lines.push('Rush: it starts now, at the rush rate.');
|
|
800
|
+
}
|
|
801
|
+
else {
|
|
802
|
+
const start = startsAtLine(resp.starts_at, now);
|
|
803
|
+
if (start)
|
|
804
|
+
lines.push(start);
|
|
805
|
+
if (askedRush && (resp.starts_at === null || resp.starts_at === undefined)) {
|
|
806
|
+
lines.push('It starts now at the standard rate, so --rush changed nothing and costs nothing extra.');
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
return lines;
|
|
810
|
+
}
|
|
811
|
+
export function makeRefusalMessage(err, id) {
|
|
812
|
+
const fix = err.errorCode ? COMPILE_BLOCKED_FIX[err.errorCode] : undefined;
|
|
813
|
+
if (fix)
|
|
814
|
+
return `${err.message}\n${fix.replace('<id>', id)}`;
|
|
815
|
+
if (err.errorCode === 'insufficient_credit_for_rush') {
|
|
816
|
+
const premium = err.details?.rush_premium_usd;
|
|
817
|
+
const line = typeof premium === 'number' ? `\nRush premium: ${usd(premium)}, paid from credit.` : '';
|
|
818
|
+
return `${err.message}${line}`;
|
|
819
|
+
}
|
|
820
|
+
if (err.errorCode === 'compile_already_started') {
|
|
821
|
+
return (`${err.message.split('\n')[0]}\n` +
|
|
822
|
+
'It has already started, so --rush no longer applies: it carries on as it is, and nothing extra was charged.');
|
|
823
|
+
}
|
|
824
|
+
if (err.statusCode === 409 && /already in progress/i.test(err.message)) {
|
|
825
|
+
return `HTTP 409: ${err.message}\nIf it is waiting for its scheduled start, make it again with --rush to start it now.`;
|
|
826
|
+
}
|
|
827
|
+
return `HTTP ${err.statusCode}: ${err.message}`;
|
|
828
|
+
}
|
|
829
|
+
export function compileLimitText(n) {
|
|
830
|
+
if (typeof n !== 'number')
|
|
831
|
+
return n === null || n === undefined ? '-' : String(n);
|
|
832
|
+
if (n < 0)
|
|
833
|
+
return 'unlimited';
|
|
834
|
+
if (n === 0)
|
|
835
|
+
return 'none on this plan (compiles are paid per source token)';
|
|
836
|
+
return `${n.toLocaleString('en-US')} source tokens`;
|
|
837
|
+
}
|
|
838
|
+
export function compileFieldLine(key, value, now = Date.now()) {
|
|
839
|
+
switch (key) {
|
|
840
|
+
case 'tokens_limit':
|
|
841
|
+
return typeof value === 'number' ? `compile allowance this month: ${compileLimitText(value)}` : undefined;
|
|
842
|
+
case 'tokens_used':
|
|
843
|
+
return typeof value === 'number' ? `compiled this month: ${value.toLocaleString('en-US')} source tokens` : undefined;
|
|
844
|
+
case 'starts_at': {
|
|
845
|
+
if (value === null || value === undefined)
|
|
846
|
+
return null;
|
|
847
|
+
const line = startsAtLine(value, now);
|
|
848
|
+
return line ? line.replace(/^Scheduled start:/, 'scheduled start:').replace(/^Started:/, 'started:') : undefined;
|
|
849
|
+
}
|
|
850
|
+
case 'rush':
|
|
851
|
+
if (value === false)
|
|
852
|
+
return null;
|
|
853
|
+
return value === true ? 'rush: yes, at the rush rate' : undefined;
|
|
854
|
+
case 'rush_premium_usd':
|
|
855
|
+
if (value === null || value === undefined)
|
|
856
|
+
return null;
|
|
857
|
+
if (typeof value !== 'number')
|
|
858
|
+
return undefined;
|
|
859
|
+
return value === 0
|
|
860
|
+
? 'rush now: no extra charge on this plan (make again with --rush)'
|
|
861
|
+
: `rush now: ${usd(value)} from credit (make again with --rush)`;
|
|
862
|
+
default:
|
|
863
|
+
return undefined;
|
|
864
|
+
}
|
|
865
|
+
}
|