@oalo-ai/cli 0.7.0 → 0.9.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.
@@ -7,22 +7,117 @@ import { resolve as resolveConfig, controlPlane, HOW_TO_CONNECT } from "../confi
7
7
  import { dim } from "../events.js";
8
8
 
9
9
  const USAGE =
10
- "usage: oalo db query \"<sql>\" [--env dev|prod] [--limit <n>] [--json]\n" +
11
- " oalo db tables [--env dev|prod]\n" +
12
- " oalo db dump [--env dev|prod] [--out <file.sql>]\n" +
13
- " oalo db restore <file> --env dev|prod [--schema <name>] [--check] [--yes]\n" +
14
- " oalo db restore --from-env <VAR> --env dev|prod [--schema <name>] [--check] [--yes]";
15
-
16
- /** `oalo db dump` and `oalo db restore`. */
10
+ "usage: oalo db query \"<sql>\" [--env dev|prod] [--app <slug>] [--limit <n>] [--json]\n" +
11
+ " oalo db tables [--env dev|prod] [--app <slug>]\n" +
12
+ " oalo db schemas [--json]\n" +
13
+ " oalo db grant <owner-app|workspace> --to <grantee-app> [--read-only]\n" +
14
+ " oalo db revoke <owner-app|workspace> --from <grantee-app>\n" +
15
+ " oalo db dump [--env dev|prod] [--app <slug>] [--out <file.sql>]\n" +
16
+ " oalo db restore <file> --env dev|prod [--app <slug>] [--schema <name>] [--check] [--yes]\n" +
17
+ " oalo db restore --from-env <VAR> --env dev|prod [--app <slug>] [--schema <name>] [--check] [--yes]";
18
+
19
+ /** `oalo db dump`, `oalo db restore`, `oalo db query`, `oalo db tables`, `oalo db schemas`, `oalo db grant`, `oalo db revoke`. */
17
20
  export async function db(flags, rest, opts = {}) {
18
21
  const sub = rest[1];
19
22
  if (sub === "query") return query(flags, rest[2], opts);
20
23
  if (sub === "tables") return query(flags, TABLES_SQL, opts, { tables: true });
24
+ if (sub === "schemas") return schemas(flags, opts);
25
+ if (sub === "grant") return grant(flags, rest[2], opts);
26
+ if (sub === "revoke") return revoke(flags, rest[2], opts);
21
27
  if (sub === "dump") return dump(flags, opts);
22
28
  if (sub === "restore") return restore(flags, rest, opts);
23
29
  return fail(USAGE, 2);
24
30
  }
25
31
 
32
+ async function schemas(flags, opts) {
33
+ const { url, token } = controlPlane(resolveConfig(flags));
34
+ if (!url || !token) return fail(`oalo db schemas needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2);
35
+
36
+ const doFetch = opts.fetch || fetch;
37
+ let res;
38
+ try {
39
+ res = await doFetch(`${url.replace(/\/$/, "")}/api/cli/v1/db/schemas`, {
40
+ headers: { authorization: `Bearer ${token}` },
41
+ });
42
+ } catch (e) {
43
+ return fail(`could not reach ${url} (${e.message})`, 1);
44
+ }
45
+ const body = await res.json().catch(() => ({}));
46
+ if (!res.ok) return fail(body?.error?.message || `could not list schemas (HTTP ${res.status})`, 1);
47
+ if (flags.json) return void console.log(JSON.stringify(body, null, 2));
48
+
49
+ const rows = [
50
+ ["workspace", "dev", "prod"],
51
+ ...(body.apps || []).map((a) => [a.slug, a.dev_schema, a.prod_schema]),
52
+ ];
53
+ printTable(["app", "dev_schema", "prod_schema"], rows);
54
+
55
+ const grants = body.grants || [];
56
+ if (grants.length > 0) {
57
+ console.log("");
58
+ printTable(
59
+ ["owner", "grantee", "access", "env_var"],
60
+ grants.map((g) => [g.owner, g.grantee, g.access, g.env_var || ""]),
61
+ );
62
+ }
63
+ }
64
+
65
+ async function grant(flags, owner, opts) {
66
+ const grantee = typeof flags.to === "string" ? flags.to.trim() : "";
67
+ if (typeof owner !== "string" || !owner.trim() || !grantee) {
68
+ return fail("usage: oalo db grant <owner-app|workspace> --to <grantee-app> [--read-only]", 2);
69
+ }
70
+ const { url, token } = controlPlane(resolveConfig(flags));
71
+ if (!url || !token) return fail(`oalo db grant needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2);
72
+
73
+ const access = flags["read-only"] ? "read" : "write";
74
+ const doFetch = opts.fetch || fetch;
75
+ let res;
76
+ try {
77
+ res = await doFetch(`${url.replace(/\/$/, "")}/api/cli/v1/db/grants`, {
78
+ method: "POST",
79
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
80
+ body: JSON.stringify({ owner: owner.trim(), grantee, access }),
81
+ });
82
+ } catch (e) {
83
+ return fail(`could not reach ${url} (${e.message})`, 1);
84
+ }
85
+ const body = await res.json().catch(() => ({}));
86
+ if (!res.ok) return fail(body?.error?.message || `could not grant schema access (HTTP ${res.status})`, 1);
87
+ if (flags.json) return void console.log(JSON.stringify(body, null, 2));
88
+
89
+ console.log(
90
+ `granted ${body.access} on ${body.owner} (${body.dev_schema} / ${body.prod_schema}) to ${body.grantee}. ` +
91
+ dim(`Restart or redeploy ${body.grantee} to receive ${body.env_var} in its environment.`),
92
+ );
93
+ }
94
+
95
+ async function revoke(flags, owner, opts) {
96
+ const grantee = typeof flags.from === "string" ? flags.from.trim() : "";
97
+ if (typeof owner !== "string" || !owner.trim() || !grantee) {
98
+ return fail("usage: oalo db revoke <owner-app|workspace> --from <grantee-app>", 2);
99
+ }
100
+ const { url, token } = controlPlane(resolveConfig(flags));
101
+ if (!url || !token) return fail(`oalo db revoke needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2);
102
+
103
+ const doFetch = opts.fetch || fetch;
104
+ let res;
105
+ try {
106
+ res = await doFetch(`${url.replace(/\/$/, "")}/api/cli/v1/db/grants`, {
107
+ method: "DELETE",
108
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
109
+ body: JSON.stringify({ owner: owner.trim(), grantee }),
110
+ });
111
+ } catch (e) {
112
+ return fail(`could not reach ${url} (${e.message})`, 1);
113
+ }
114
+ const body = await res.json().catch(() => ({}));
115
+ if (!res.ok) return fail(body?.error?.message || `could not revoke schema access (HTTP ${res.status})`, 1);
116
+ if (flags.json) return void console.log(JSON.stringify(body, null, 2));
117
+
118
+ console.log(`revoked ${body.owner} schema access from ${body.grantee}.`);
119
+ }
120
+
26
121
  // The env's tables: an app's own and the Oalo models', with Postgres's row
27
122
  // estimate (blank until it has counted; `select count(*)` for the exact number).
28
123
  const TABLES_SQL =
@@ -45,13 +140,14 @@ async function query(flags, sql, opts, { tables = false } = {}) {
45
140
  if (!url || !token) return fail(`oalo db ${tables ? "tables" : "query"} needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2);
46
141
 
47
142
  const limit = tables ? 1000 : Number.parseInt(flags.limit, 10) || undefined;
143
+ const app = typeof flags.app === "string" && flags.app.trim() ? flags.app.trim() : undefined;
48
144
  const doFetch = opts.fetch || fetch;
49
145
  let res;
50
146
  try {
51
147
  res = await doFetch(`${url.replace(/\/$/, "")}/api/cli/v1/db/query`, {
52
148
  method: "POST",
53
149
  headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
54
- body: JSON.stringify({ env, sql, ...(limit ? { limit } : {}) }),
150
+ body: JSON.stringify({ env, sql, ...(app ? { app } : {}), ...(limit ? { limit } : {}) }),
55
151
  });
56
152
  } catch (e) {
57
153
  return fail(`could not reach ${url} (${e.message})`, 1);
@@ -94,13 +190,15 @@ async function dump(flags, opts) {
94
190
  if (!url || !token) return fail(`oalo db dump needs a CLI token.\n\n${HOW_TO_CONNECT}`, 2);
95
191
 
96
192
  const host = new URL(url).hostname.split(".")[0];
97
- const out = typeof flags.out === "string" ? flags.out : `${host}-${env}-${new Date().toISOString().slice(0, 10)}.sql`;
193
+ const app = typeof flags.app === "string" && flags.app.trim() ? flags.app.trim() : undefined;
194
+ const out = typeof flags.out === "string" ? flags.out : `${host}-${app ? `${app}-` : ""}${env}-${new Date().toISOString().slice(0, 10)}.sql`;
98
195
  if (existsSync(out) && !flags.force) return fail(`${out} exists. Choose another --out, or add --force to replace it.`, 2);
99
196
 
100
197
  const doFetch = opts.fetch || fetch;
198
+ const dumpQ = new URLSearchParams({ env, ...(app ? { app } : {}) });
101
199
  let res;
102
200
  try {
103
- res = await doFetch(`${url.replace(/\/$/, "")}/api/cli/v1/db/dump?env=${env}`, { headers: { authorization: `Bearer ${token}` } });
201
+ res = await doFetch(`${url.replace(/\/$/, "")}/api/cli/v1/db/dump?${dumpQ}`, { headers: { authorization: `Bearer ${token}` } });
104
202
  } catch (e) {
105
203
  return fail(`could not reach ${url} (${e.message})`, 1);
106
204
  }
@@ -188,7 +286,8 @@ async function restore(flags, rest, opts) {
188
286
  }
189
287
 
190
288
  const scrub = scrubber(source.url);
191
- const q = new URLSearchParams({ env, ...(typeof flags.schema === "string" ? { schema: flags.schema } : {}), ...(check ? { check: "true" } : {}) });
289
+ const app = typeof flags.app === "string" && flags.app.trim() ? flags.app.trim() : undefined;
290
+ const q = new URLSearchParams({ env, ...(app ? { app } : {}), ...(typeof flags.schema === "string" ? { schema: flags.schema } : {}), ...(check ? { check: "true" } : {}) });
192
291
  const endpoint = `${url.replace(/\/$/, "")}/api/cli/v1/db/restore?${q}`;
193
292
  console.error(dim(`${check ? "checking" : "restoring"} ${source.file ? `${source.file} (${size(source.bytes)})` : `the database at ${source.host}`} ${check ? "against" : "into"} ${env} on ${url}`));
194
293
 
@@ -0,0 +1,493 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawn } from "node:child_process";
3
+ import { writeFileSync } from "node:fs";
4
+ import { createInterface } from "node:readline";
5
+ import { OaloChannel } from "../channel.js";
6
+ import { resolve as resolveConfig, controlPlane, HOW_TO_CONNECT } from "../config.js";
7
+ import { dim, bold } from "../events.js";
8
+ import { createVault, scrubText } from "../privacy/anonymize.js";
9
+
10
+ const COLOR = process.stdout.isTTY && !process.env.NO_COLOR;
11
+ const green = (s) => (COLOR ? `\x1b[32m${s}\x1b[0m` : s);
12
+ const yellow = (s) => (COLOR ? `\x1b[33m${s}\x1b[0m` : s);
13
+ const cyan = (s) => (COLOR ? `\x1b[36m${s}\x1b[0m` : s);
14
+
15
+ const VALID_PRIVACY = ["standard", "zdr", "local_only"];
16
+
17
+ /**
18
+ * `oalo forthwith`: real-time local call assistant for external Zoom, Meet,
19
+ * Teams, or phone calls, backed by Oalo's Call Copilot, Pre-Call Dossier, and
20
+ * SHA-256 notarized call records.
21
+ *
22
+ * oalo forthwith start [--title "..."] [--contact <email|phone|id>] [--booking <id>]
23
+ * [--privacy standard|zdr|local_only] [--local] [--offline]
24
+ * [--stt-cmd "<cmd>"] [--speaker "<name>"] [--scrub-pii] [--no-telemetry] [--json]
25
+ * oalo forthwith list [--kind external|one_on_one|live_class] [--status live|ended] [--json]
26
+ * oalo forthwith show <call-id> [--json]
27
+ * oalo forthwith share <call-id> --on|--off [--json]
28
+ * oalo forthwith verify <call-id> [--json]
29
+ */
30
+ export async function forthwith(flags, rest, opts = {}) {
31
+ if (flags["no-telemetry"] || process.env.OALO_NO_TELEMETRY === "1") {
32
+ process.env.OALO_NO_TELEMETRY = "1";
33
+ }
34
+
35
+ const sub = rest[1] || "start";
36
+ switch (sub) {
37
+ case "start":
38
+ return await startCall(flags, opts);
39
+ case "list":
40
+ return await listCalls(flags, opts);
41
+ case "show":
42
+ return await showCall(flags, rest, opts);
43
+ case "share":
44
+ return await shareCall(flags, rest, opts);
45
+ case "verify":
46
+ return await verifyCall(flags, rest, opts);
47
+ default:
48
+ return fail(
49
+ "usage: oalo forthwith start | list | show <call-id> | share <call-id> --on|--off | verify <call-id>",
50
+ 2,
51
+ flags,
52
+ );
53
+ }
54
+ }
55
+
56
+ async function connect(flags, opts) {
57
+ const cfg = resolveConfig(flags);
58
+ const { url, token } = controlPlane(cfg);
59
+ if (!url || !token) {
60
+ throw Object.assign(new Error(`oalo forthwith needs a CLI token.\n\n${HOW_TO_CONNECT}`), { exitCode: 2 });
61
+ }
62
+ const ch = (opts.channel || ((o) => new OaloChannel(o)))({ url, token });
63
+ await ch.connect();
64
+ return { ch, url };
65
+ }
66
+
67
+ // ── start ───────────────────────────────────────────────────────────────────
68
+
69
+ async function startCall(flags, opts) {
70
+ const title = typeof flags.title === "string" && flags.title.trim() ? flags.title.trim() : "External call";
71
+ const privacyMode = flags.local
72
+ ? "local_only"
73
+ : typeof flags.privacy === "string"
74
+ ? flags.privacy.trim().toLowerCase()
75
+ : "standard";
76
+
77
+ if (!VALID_PRIVACY.includes(privacyMode)) {
78
+ return fail(`--privacy must be one of ${VALID_PRIVACY.join(", ")} (got ${privacyMode})`, 2, flags);
79
+ }
80
+
81
+ const scrubLocal = !!flags["scrub-pii"];
82
+ const defaultSpeaker = typeof flags.speaker === "string" && flags.speaker.trim() ? flags.speaker.trim() : "Speaker";
83
+ const vault = createVault();
84
+
85
+ // Offline / air-gapped zero-egress capture mode: no network calls at all.
86
+ if (flags.offline) {
87
+ return await runOfflineSession({ title, defaultSpeaker, scrubLocal, vault, flags, opts });
88
+ }
89
+
90
+ let ch;
91
+ try {
92
+ ({ ch } = await connect(flags, opts));
93
+ } catch (e) {
94
+ return fail(e.message, e.exitCode || 1, flags);
95
+ }
96
+
97
+ let copilotChan = null;
98
+ let call = null;
99
+ let dossier = null;
100
+ let sttChild = null;
101
+ let finished = false;
102
+
103
+ const emitJson = (event, data) => {
104
+ if (flags.json) console.log(JSON.stringify({ event, ...data }));
105
+ };
106
+
107
+ try {
108
+ const createParams = {
109
+ kind: "external",
110
+ title,
111
+ privacy_mode: privacyMode,
112
+ };
113
+ if (typeof flags.booking === "string") createParams.booking_id = flags.booking;
114
+
115
+ const created = await ch.call("calls:create", createParams);
116
+ call = created.call;
117
+
118
+ // Attach optional contact so the Pre-Call Dossier loads their CRM history.
119
+ if (typeof flags.contact === "string" && flags.contact.trim()) {
120
+ const ref = flags.contact.trim();
121
+ const participant = {
122
+ id: call.id,
123
+ role: "guest",
124
+ external_ref: ref,
125
+ display_name: ref,
126
+ };
127
+ if (ref.includes("@")) participant.email = ref;
128
+ await ch.call("calls:add_participant", participant);
129
+ }
130
+
131
+ // Start Copilot session and fetch minute-0 Pre-Call Dossier.
132
+ const dossierRes = await ch.call("calls:dossier", { id: call.id });
133
+ dossier = dossierRes.dossier || dossierRes;
134
+
135
+ // Subscribe to live host whisper cards if using a live Phoenix socket.
136
+ if (ch.socket && typeof ch.socket.channel === "function") {
137
+ copilotChan = ch.socket.channel(`call_copilot:${call.id}`, {});
138
+ copilotChan.on("suggestion", (card) => {
139
+ if (flags.json) emitJson("suggestion", { card });
140
+ else printWhisperCard(card);
141
+ });
142
+ copilotChan.on("attendee_card", (card) => {
143
+ if (flags.json) emitJson("attendee_card", { card });
144
+ else printAttendeeCard(card);
145
+ });
146
+ await new Promise((resolve) => {
147
+ copilotChan
148
+ .join(5000)
149
+ .receive("ok", () => resolve())
150
+ .receive("error", () => resolve())
151
+ .receive("timeout", () => resolve());
152
+ });
153
+ }
154
+
155
+ if (flags.json) {
156
+ emitJson("started", { call, dossier });
157
+ } else {
158
+ console.log(bold(`oalo forthwith: ${call.title}`) + " " + dim(`(${call.id}, privacy=${call.privacy_mode || privacyMode})`));
159
+ if (scrubLocal) console.log(dim("Local PII scrubbing ON: SSNs, Luhn cards, emails, phones, and IPs are tokenized before upload."));
160
+ printDossier(dossier);
161
+ console.log(dim("Streaming transcript. Commands: /ask <question>, /share <title> | <content> [| <url>], /brief, /end"));
162
+ }
163
+
164
+ const handleLine = async (rawLine) => {
165
+ const line = String(rawLine || "").trim();
166
+ if (!line) return false;
167
+
168
+ if (line === "/end" || line === "/quit" || line === "/exit") {
169
+ return true;
170
+ }
171
+ if (line === "/brief") {
172
+ if (flags.json) emitJson("dossier", { dossier });
173
+ else printDossier(dossier);
174
+ return false;
175
+ }
176
+ if (line.startsWith("/ask ")) {
177
+ const question = line.slice(5).trim();
178
+ if (!question) return false;
179
+ const qText = scrubLocal ? scrubText(question, vault).text : question;
180
+ const r = await ch.call("calls:copilot:ask", { id: call.id, question: qText });
181
+ if (flags.json) emitJson("ask", { question: qText, card: r.card || null });
182
+ else if (r.card) printWhisperCard(r.card);
183
+ else console.log(dim("(copilot had no suggestion for that question)"));
184
+ return false;
185
+ }
186
+ if (line.startsWith("/share ")) {
187
+ const parts = line.slice(7).split("|").map((s) => s.trim());
188
+ const [cardTitle, content, url] = parts;
189
+ if (!cardTitle || !content) {
190
+ if (!flags.json) console.error(dim("usage: /share <title> | <content> [| <url>]"));
191
+ return false;
192
+ }
193
+ const payload = { id: call.id, title: cardTitle, content };
194
+ if (url) payload.url = url;
195
+ const r = await ch.call("calls:copilot:share", payload);
196
+ if (flags.json) emitJson("shared", { card: r.card });
197
+ else printAttendeeCard(r.card);
198
+ return false;
199
+ }
200
+
201
+ const { speaker, text } = parseSpeakerLine(line, defaultSpeaker);
202
+ const outText = scrubLocal ? scrubText(text, vault).text : text;
203
+ await ch.call("calls:copilot:transcript", { id: call.id, speaker, text: outText });
204
+ if (flags.json) emitJson("transcript", { speaker, text: outText });
205
+ return false;
206
+ };
207
+
208
+ const finalize = async () => {
209
+ if (finished || !call) return;
210
+ finished = true;
211
+ try {
212
+ if (sttChild && !sttChild.killed) sttChild.kill("SIGTERM");
213
+ } catch {
214
+ /* ignore */
215
+ }
216
+ try {
217
+ const ended = await ch.call("calls:end", { id: call.id });
218
+ let proof = null;
219
+ try {
220
+ proof = await ch.call("calls:notarization", { id: call.id });
221
+ } catch {
222
+ /* notarization may still be finalizing */
223
+ }
224
+ if (flags.json) {
225
+ emitJson("ended", { call: ended.call, notarization: proof });
226
+ } else {
227
+ console.log("\n" + green("Call ended and notarized:") + ` ${ended.call?.id || call.id}`);
228
+ if (ended.call?.summary) console.log(` summary: ${ended.call.summary}`);
229
+ if (proof?.sha256 || ended.call?.notarization_hash) {
230
+ console.log(` sha256: ${proof?.sha256 || ended.call.notarization_hash}${proof?.verified ? " (verified)" : ""}`);
231
+ }
232
+ }
233
+ } catch (e) {
234
+ if (!flags.json) console.error(`could not finalize call cleanly: ${e.message}`);
235
+ }
236
+ };
237
+
238
+ const inputStream = opts.input || process.stdin;
239
+ const onSigint = () => {
240
+ finalize().finally(() => {
241
+ try { copilotChan?.leave(); } catch { /* ignore */ }
242
+ ch.close();
243
+ process.exit(0);
244
+ });
245
+ };
246
+ if (!opts.input) process.once("SIGINT", onSigint);
247
+
248
+ if (typeof flags["stt-cmd"] === "string" && flags["stt-cmd"].trim()) {
249
+ sttChild = spawn(flags["stt-cmd"], { shell: true, stdio: ["ignore", "pipe", "inherit"] });
250
+ const rl = createInterface({ input: sttChild.stdout, crlfDelay: Infinity });
251
+ for await (const line of rl) {
252
+ const stop = await handleLine(line);
253
+ if (stop) break;
254
+ }
255
+ } else {
256
+ const rl = createInterface({ input: inputStream, crlfDelay: Infinity });
257
+ for await (const line of rl) {
258
+ const stop = await handleLine(line);
259
+ if (stop) break;
260
+ }
261
+ }
262
+
263
+ if (!opts.input) process.removeListener("SIGINT", onSigint);
264
+ await finalize();
265
+ } catch (e) {
266
+ return fail(e.message, 1, flags);
267
+ } finally {
268
+ try { copilotChan?.leave(); } catch { /* ignore */ }
269
+ ch.close();
270
+ }
271
+ }
272
+
273
+ async function runOfflineSession({ title, defaultSpeaker, scrubLocal, vault, flags, opts }) {
274
+ const startedAt = new Date().toISOString();
275
+ const segments = [];
276
+ const inputStream = opts.input || process.stdin;
277
+
278
+ if (!flags.json) {
279
+ console.log(bold(`oalo forthwith (offline local mode): ${title}`));
280
+ console.log(dim("Zero network egress. Transcript stays strictly on this machine and will be notarized locally with SHA-256."));
281
+ if (scrubLocal) console.log(dim("Local PII scrubbing ON."));
282
+ }
283
+
284
+ const rl = createInterface({ input: inputStream, crlfDelay: Infinity });
285
+ for await (const rawLine of rl) {
286
+ const line = String(rawLine || "").trim();
287
+ if (!line) continue;
288
+ if (line === "/end" || line === "/quit" || line === "/exit") break;
289
+ const { speaker, text } = parseSpeakerLine(line, defaultSpeaker);
290
+ const outText = scrubLocal ? scrubText(text, vault).text : text;
291
+ segments.push({ ts: new Date().toISOString(), speaker, text: outText });
292
+ }
293
+
294
+ const endedAt = new Date().toISOString();
295
+ const payload = {
296
+ mode: "offline_local",
297
+ title,
298
+ started_at: startedAt,
299
+ ended_at: endedAt,
300
+ scrubbed_pii: scrubLocal,
301
+ segments,
302
+ };
303
+ const sha256 = createHash("sha256").update(JSON.stringify(payload)).digest("hex");
304
+ const record = { ...payload, notarization: { algorithm: "sha256", sha256, verified: true } };
305
+
306
+ const outFile = typeof flags.out === "string" && flags.out.trim() ? flags.out.trim() : null;
307
+ if (outFile) {
308
+ writeFileSync(outFile, JSON.stringify(record, null, 2) + "\n", { mode: 0o600 });
309
+ }
310
+
311
+ if (flags.json) {
312
+ console.log(JSON.stringify(record, null, 2));
313
+ } else {
314
+ console.log(green(`Offline call saved (${segments.length} segment(s))`));
315
+ console.log(` sha256: ${sha256}`);
316
+ if (outFile) console.log(` file: ${outFile}`);
317
+ }
318
+ }
319
+
320
+ // ── list / show / share / verify ────────────────────────────────────────────
321
+
322
+ async function listCalls(flags, opts) {
323
+ let ch;
324
+ try {
325
+ ({ ch } = await connect(flags, opts));
326
+ } catch (e) {
327
+ return fail(e.message, e.exitCode || 1, flags);
328
+ }
329
+ try {
330
+ const params = {};
331
+ if (typeof flags.kind === "string") params.kind = flags.kind;
332
+ if (typeof flags.status === "string") params.status = flags.status;
333
+ const r = await ch.call("calls:list", params);
334
+ const calls = r.calls || [];
335
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
336
+ if (!calls.length) return void console.log("no calls found");
337
+ for (const c of calls) {
338
+ const share = c.shared_with_participants ? "shared" : "private";
339
+ console.log(`${c.id} ${(c.status || "?").padEnd(6)} ${(c.kind || "?").padEnd(10)} ${c.title || "(untitled)"} ${dim(`[${c.privacy_mode || "standard"}, ${share}]`)}`);
340
+ }
341
+ } catch (e) {
342
+ return fail(e.message, 1, flags);
343
+ } finally {
344
+ ch.close();
345
+ }
346
+ }
347
+
348
+ async function showCall(flags, rest, opts) {
349
+ const id = rest[2];
350
+ if (!id) return fail("usage: oalo forthwith show <call-id> [--json]", 2, flags);
351
+
352
+ let ch;
353
+ try {
354
+ ({ ch } = await connect(flags, opts));
355
+ } catch (e) {
356
+ return fail(e.message, e.exitCode || 1, flags);
357
+ }
358
+ try {
359
+ const r = await ch.call("calls:get", { id });
360
+ const c = r.call;
361
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
362
+ console.log(bold(`${c.title || "(untitled)"}`) + " " + dim(`(${c.id})`));
363
+ console.log(` kind: ${c.kind}`);
364
+ console.log(` status: ${c.status}`);
365
+ console.log(` privacy: ${c.privacy_mode || "standard"}`);
366
+ console.log(` sharing: ${c.shared_with_participants ? "shared with verified participants" : "host only"}`);
367
+ if (c.notarization_hash) console.log(` sha256: ${c.notarization_hash}`);
368
+ if (c.summary) console.log(` summary: ${c.summary}`);
369
+ if (Array.isArray(c.action_items) && c.action_items.length) {
370
+ console.log(" action items:");
371
+ for (const a of c.action_items) console.log(` - ${typeof a === "string" ? a : JSON.stringify(a)}`);
372
+ }
373
+ } catch (e) {
374
+ return fail(e.message, 1, flags);
375
+ } finally {
376
+ ch.close();
377
+ }
378
+ }
379
+
380
+ async function shareCall(flags, rest, opts) {
381
+ const id = rest[2];
382
+ if (!id || (!!flags.on === !!flags.off)) {
383
+ return fail("usage: oalo forthwith share <call-id> --on | --off [--json]", 2, flags);
384
+ }
385
+
386
+ let ch;
387
+ try {
388
+ ({ ch } = await connect(flags, opts));
389
+ } catch (e) {
390
+ return fail(e.message, e.exitCode || 1, flags);
391
+ }
392
+ try {
393
+ const shared = !!flags.on;
394
+ const r = await ch.call("calls:set_sharing", { id, shared_with_participants: shared });
395
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
396
+ console.log(`${id}: recording and transcript sharing ${shared ? "enabled for verified participants" : "restricted to host only"}`);
397
+ } catch (e) {
398
+ return fail(e.message, 1, flags);
399
+ } finally {
400
+ ch.close();
401
+ }
402
+ }
403
+
404
+ async function verifyCall(flags, rest, opts) {
405
+ const id = rest[2];
406
+ if (!id) return fail("usage: oalo forthwith verify <call-id> [--json]", 2, flags);
407
+
408
+ let ch;
409
+ try {
410
+ ({ ch } = await connect(flags, opts));
411
+ } catch (e) {
412
+ return fail(e.message, e.exitCode || 1, flags);
413
+ }
414
+ try {
415
+ const r = await ch.call("calls:notarization", { id });
416
+ if (flags.json) return void console.log(JSON.stringify(r, null, 2));
417
+ const status = r.verified ? green("VERIFIED") : yellow("MISMATCH");
418
+ console.log(`${id}: ${status}`);
419
+ if (r.sha256) console.log(` sha256: ${r.sha256}`);
420
+ if (r.algorithm) console.log(` algorithm: ${r.algorithm}`);
421
+ if (!r.verified) process.exitCode = 1;
422
+ } catch (e) {
423
+ return fail(e.message, 1, flags);
424
+ } finally {
425
+ ch.close();
426
+ }
427
+ }
428
+
429
+ // ── formatting helpers ──────────────────────────────────────────────────────
430
+
431
+ export function parseSpeakerLine(line, defaultSpeaker = "Speaker") {
432
+ const m = line.match(/^([A-Za-z0-9 _.-]{1,32}):\s+(.+)$/);
433
+ if (m) return { speaker: m[1].trim(), text: m[2].trim() };
434
+ return { speaker: defaultSpeaker, text: line };
435
+ }
436
+
437
+ function printDossier(d) {
438
+ if (!d) return;
439
+ console.log(cyan("--- Pre-Call Dossier ---"));
440
+ const contacts = d.contacts || d.participants || [];
441
+ if (contacts.length) {
442
+ for (const c of contacts) {
443
+ const label = c.name || c.display_name || c.email || c.external_ref || c.id;
444
+ const bits = [c.company, c.email, c.status].filter(Boolean).join(", ");
445
+ console.log(` Contact: ${bold(label)}${bits ? ` (${bits})` : ""}`);
446
+ if (Array.isArray(c.tags) && c.tags.length) console.log(` tags: ${c.tags.join(", ")}`);
447
+ }
448
+ }
449
+ const deals = d.open_deals || d.deals || [];
450
+ if (deals.length) {
451
+ console.log(" Open deals:");
452
+ for (const deal of deals.slice(0, 5)) {
453
+ console.log(` - ${deal.title || deal.name || deal.id} (${deal.stage || deal.status || "open"}${deal.value ? `, ${deal.value}` : ""})`);
454
+ }
455
+ }
456
+ const past = d.past_calls || [];
457
+ if (past.length) {
458
+ console.log(" Recent calls:");
459
+ for (const p of past.slice(0, 3)) {
460
+ console.log(` - ${p.title || p.id}: ${p.summary || "(no summary)"}`);
461
+ }
462
+ }
463
+ const bookings = d.upcoming_bookings || d.bookings || [];
464
+ if (bookings.length) {
465
+ console.log(" Bookings:");
466
+ for (const b of bookings.slice(0, 3)) {
467
+ console.log(` - ${b.title || b.service || b.id} (${b.starts_at || b.start_time || ""})`);
468
+ }
469
+ }
470
+ if (!contacts.length && !deals.length && !past.length && !bookings.length) {
471
+ console.log(dim(" No linked contact history yet. Pass --contact <email> to preload CRM context."));
472
+ }
473
+ console.log(cyan("------------------------"));
474
+ }
475
+
476
+ function printWhisperCard(card) {
477
+ const kind = card.kind || card.type || "whisper";
478
+ console.log("\n" + yellow(`[COPILOT ${kind.toUpperCase()}]`) + " " + bold(card.title || "Suggestion"));
479
+ if (card.content || card.body) console.log(` ${card.content || card.body}`);
480
+ if (card.next_step) console.log(dim(` Next step: ${card.next_step}`));
481
+ }
482
+
483
+ function printAttendeeCard(card) {
484
+ console.log("\n" + green("[SHARED CARD]") + " " + bold(card.title || "Resource"));
485
+ if (card.content) console.log(` ${card.content}`);
486
+ if (card.url) console.log(dim(` ${card.url}`));
487
+ }
488
+
489
+ function fail(msg, code, flags) {
490
+ if (flags?.json) console.log(JSON.stringify({ error: msg }));
491
+ else console.error(msg);
492
+ process.exitCode = code;
493
+ }