shadok-ai 0.19.34 → 0.19.35

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/README.md CHANGED
@@ -646,6 +646,46 @@ Enter to skip; you can add it later from the web UI).
646
646
  `SHADOK_CONNECT_BROKER` (default `https://connect.shadok.ai`). LinkedIn
647
647
  sunsets API versions, so `LINKEDIN_VERSION` in `src/linkedin.ts` must be
648
648
  bumped about once a year, or posting stops working.
649
+ - **Connected accounts (Google)** — the same idea for a Google account: connect
650
+ it once, then ask an agent to *"put a review with Bob on Thursday at 10"*,
651
+ *"draft a reply to that"* or *"write this up in a Doc"*. **Connect Google**
652
+ (shown only when the broker offers Google) opens a small dialog where you
653
+ tick what agents may work with — **Calendar** (read, add, change and delete
654
+ events), **Drive files** (the Docs and Sheets the cockpit creates — never the
655
+ rest of your Drive) and **Gmail** (write drafts and send email — never read
656
+ your mailbox) — then Google asks you to confirm each one. The account row
657
+ shows the areas Google actually granted, the same *Shared with* / *Profiles*
658
+ chips as LinkedIn, and **two settings** instead of one posting policy:
659
+ **Mail** (sending email) and **Events** (any event added, changed or
660
+ deleted, with or without attendees), each *ask first* (the default) or *on
661
+ its own* — only the account's owner can switch one to automatic, after a
662
+ confirmation that says what it means. The agent uses the seeded
663
+ `shadok-google` skill (`google.mjs accounts`, `calendar list|create|update|delete`,
664
+ `drive list`, `doc create|read|append`, `sheet create|read|append`,
665
+ `gmail draft|send` — content on stdin, never argv) and never sees the token.
666
+ What it may do falls in four classes: **reads** and **writes in your own
667
+ files and drafts** (a Gmail draft, a Doc, a Sheet) are done at once;
668
+ **sending mail** follows the Mail setting and **calendar changes** the Events
669
+ setting. With approval, an email becomes a **real draft in your Gmail** plus
670
+ an approval card showing from, to, cc, bcc, subject, the exact body and the
671
+ attachments by name; you may edit it in Gmail first — on *Send* the server
672
+ re-reads the draft, sends it if it is what the card showed, and otherwise
673
+ refreshes the card (*"Edited in Gmail since — send this version?"*) so you
674
+ always send what you are looking at. Deleting the draft in Gmail closes the
675
+ card and tells the agent; *Discard* deletes the Gmail draft too; the agent
676
+ cannot rewrite a draft that is waiting for you. An event card shows title,
677
+ start and end with their time zone, the attendees Google will email,
678
+ location and description. The log keeps a line per action — recipients and
679
+ subject, an event's title and time, a file's name — and **never a mail
680
+ body**. **While the shadok Google app is in Testing** (it is, for now) only
681
+ Google accounts on the app's test list can connect, and Google makes the
682
+ authorisation last **7 days**: the row says *Test app — reconnect weekly*
683
+ with the deadline, the owner is warned 2 days ahead, and an expired account
684
+ refuses with *"needs a reconnect"*. Reading mail or the whole Drive is
685
+ deliberately not offered here; agents that need it use the claude.ai
686
+ connectors (the `login` agent-auth mode). Operator setup for Google (Cloud
687
+ project, consent screen, the two broker secrets) is in
688
+ [`broker/README.md`](broker/README.md).
649
689
  - **Self-update** — polls npm and can update and reload itself in place.
650
690
 
651
691
  ### Telegram (optional)
@@ -1467,17 +1507,24 @@ or door that caused it; names only, never a value; filters `secret`, `action`,
1467
1507
  🕘 on each secret), `/telegram`, `/defaults`, `/first-agent` (GET —
1468
1508
  `{pending, reason}`: whether this instance's lead agent is being started
1469
1509
  right now), `/version`, `/autoupdate`,
1470
- `/connect/status` (GET — `{available}`: is the broker reachable/configured),
1471
- `/connect/linkedin/start` · `/connect/linkedin/complete` (POST, browser person
1472
- only — the OAuth hand-back; `/connect/linkedin/done` (GET) is the page the
1473
- broker returns the browser to), `/connected-accounts` (GET — the accounts
1474
- you may use, never a token, plus `softLayer`; your own accounts also carry
1475
- `expiringSoon` / `expired`, for the banner; `GET /:id/log` — that account's
1476
- last 50 publication-log entries, newest first; `PUT /:id` changes share/policy,
1477
- `DELETE /:id` disconnects — owner or admin, browser only),
1478
- `/social/accounts` (GET) and `/social/posts` (POST) — the **agent** side,
1479
- authenticated by `x-shadok-session-key` —, and `/social/drafts/:id/publish` ·
1480
- `/social/drafts/:id/discard` (POST, browser person only),
1510
+ `/connect/status` (GET — `{available, providers: {linkedin, google},
1511
+ googleTesting}`: what the broker offers; `available` is LinkedIn's),
1512
+ `/connect/<provider>/start` · `/connect/<provider>/complete` (POST, browser
1513
+ person only — the OAuth hand-back, `<provider>` = `linkedin` or `google`;
1514
+ Google's `start` also takes `areas`, a list among `calendar`, `drive`, `gmail`;
1515
+ `/connect/<provider>/done` (GET) is the page the broker returns the browser
1516
+ to), `/connected-accounts` (GET — the accounts you may use, never a token, plus
1517
+ `softLayer`; a Google account carries `areas`, `policies` and
1518
+ `refreshExpiresAt`; your own accounts also carry `expiringSoon` / `expired`,
1519
+ for the banner; `GET /:id/log` — that account's last 50 log entries, newest
1520
+ first; `PUT /:id` changes `share`, LinkedIn's `policy` or Google's
1521
+ `policies.mail` / `policies.calendar`; `DELETE /:id` disconnects, and revokes
1522
+ a Google grant at Google — owner or admin, browser only),
1523
+ `/social/accounts` (GET), `/social/posts` (POST) and `/google/actions` (POST
1524
+ `{account, action, args}`) — the **agent** side, authenticated by
1525
+ `x-shadok-session-key` —, and `/social/drafts/:id/publish` ·
1526
+ `/social/drafts/:id/discard` (POST, browser person only — a LinkedIn post, an
1527
+ email or a calendar change alike),
1481
1528
  `/update-channel` (POST `{channel}` — `alpha` or `beta`), `/permission-mode`, `/tweak/prepare` (POST — clone/refresh shadok-ai's own source,
1482
1529
  returns the cwd to start the tweak agent in). The instance-wide writes —
1483
1530
  `/autoupdate`, `/update-channel`, `/permission-mode`, `POST /ledger`, a bare
@@ -3,7 +3,7 @@
3
3
  <head>
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <title>Connect LinkedIn</title>
6
+ <title>Connect an account</title>
7
7
  <style>
8
8
  body { font: 16px/1.5 system-ui, sans-serif; background: #0f1115; color: #e6e6e6; display: grid; place-items: center; min-height: 100vh; margin: 0; }
9
9
  main { max-width: 28rem; padding: 2rem; text-align: center; }
@@ -12,27 +12,34 @@
12
12
  </head>
13
13
  <body>
14
14
  <main>
15
- <p id="msg">Finishing the LinkedIn connection…</p>
15
+ <p id="msg">Finishing the connection…</p>
16
16
  <p><a href="/">Back to the cockpit</a></p>
17
17
  </main>
18
- <!-- Served by GET /connect/linkedin/done with a per-request nonce (invariant 12).
19
- Every URL is path-relative so it works behind a TLS proxy (invariant 20). -->
18
+ <!-- Served by GET /connect/<provider>/done with a per-request nonce (invariant 12).
19
+ One page for every provider: which one is read off the path it was served
20
+ at. Every URL is path-relative so it works behind a TLS proxy (invariant 20). -->
20
21
  <script nonce="__CSP_NONCE__">
21
22
  (async () => {
22
23
  const msg = document.getElementById("msg");
24
+ const LABELS = { linkedin: "LinkedIn", google: "Google" };
25
+ const m = /^\/connect\/([a-z]+)\/done$/.exec(location.pathname);
26
+ const provider = m && LABELS[m[1]] ? m[1] : "linkedin";
27
+ const label = LABELS[provider];
28
+ document.title = "Connect " + label;
29
+ msg.textContent = "Finishing the " + label + " connection…";
23
30
  const hash = location.hash;
24
31
  // Drop the encrypted token from the address bar and the history at once.
25
32
  history.replaceState(null, "", location.pathname + location.search);
26
- let text = "The connection could not be finished — click Connect LinkedIn again.";
33
+ let text = "The connection could not be finished — click Connect " + label + " again.";
27
34
  try {
28
- const r = await fetch("/connect/linkedin/complete", {
35
+ const r = await fetch("/connect/" + provider + "/complete", {
29
36
  method: "POST",
30
37
  headers: { "content-type": "application/json" },
31
38
  credentials: "same-origin",
32
39
  body: JSON.stringify({ hash }),
33
40
  });
34
41
  const j = await r.json().catch(() => ({}));
35
- if (r.ok && j.account) text = "LinkedIn connected as " + (j.account.label || "your account") + ".";
42
+ if (r.ok && j.account) text = label + " connected as " + (j.account.label || "your account") + ".";
36
43
  else if (j.message) text = j.message;
37
44
  else if (j.error) text = j.error;
38
45
  } catch { /* keep the generic sentence */ }
@@ -0,0 +1,116 @@
1
+ ---
2
+ name: shadok-google
3
+ description: Work in a Google account the person connected in the cockpit — read and change their calendar, create and fill Google Docs and Sheets, write Gmail drafts and send email. Use when they ask you to schedule or move a meeting, check their agenda, draft or send an email, or write something into a Doc or a Sheet.
4
+ ---
5
+
6
+ # shadok-google
7
+
8
+ Acts in a Google account the person connected in the cockpit (Secrets →
9
+ Connected accounts). You never hold the account's token and it is never
10
+ available to you — do not look for it. The server calls Google on your behalf.
11
+
12
+ ## Pick the account
13
+
14
+ ```bash
15
+ node ~/.claude/skills/shadok-google/scripts/google.mjs accounts
16
+ ```
17
+
18
+ One line per account: `<id> <email> areas=<calendar,drive,gmail> mail=<approve|autonomous> events=<approve|autonomous> reconnect-by=<date>`.
19
+ `areas` is what the person granted: an action outside them is refused, and only
20
+ they can reconnect and tick the missing one. If none is listed, tell the person
21
+ to connect a Google account in Secrets → Connected accounts, or to share theirs
22
+ with this agent's group. `EXPIRED` means they must reconnect it.
23
+
24
+ ## Reading — leaves nothing, never asked about
25
+
26
+ ```bash
27
+ node ~/.claude/skills/shadok-google/scripts/google.mjs calendar list --account <id> [--from 2026-11-20] [--to 2026-11-27]
28
+ node ~/.claude/skills/shadok-google/scripts/google.mjs drive list --account <id>
29
+ node ~/.claude/skills/shadok-google/scripts/google.mjs doc read --account <id> --id <doc id>
30
+ node ~/.claude/skills/shadok-google/scripts/google.mjs sheet read --account <id> --id <sheet id> [--range Sheet1!A1:D20]
31
+ ```
32
+
33
+ `drive list` shows only files created through this cockpit — never the
34
+ person's whole Drive, which you cannot see.
35
+
36
+ ## Writing in their own files and drafts — done at once
37
+
38
+ The content goes through stdin, never argv:
39
+
40
+ ```bash
41
+ node ~/.claude/skills/shadok-google/scripts/google.mjs doc create --account <id> --title "Notes" --stdin <<'TEXT'
42
+ first paragraph
43
+ TEXT
44
+ node ~/.claude/skills/shadok-google/scripts/google.mjs doc append --account <id> --id <doc id> --stdin <<'TEXT'
45
+ more text
46
+ TEXT
47
+ node ~/.claude/skills/shadok-google/scripts/google.mjs sheet create --account <id> --title "Stock"
48
+ node ~/.claude/skills/shadok-google/scripts/google.mjs sheet append --account <id> --id <sheet id> --stdin <<'ROWS'
49
+ [["Name","Qty"],["Bolt",12]]
50
+ ROWS
51
+ node ~/.claude/skills/shadok-google/scripts/google.mjs gmail draft --account <id> --to ana@example.com --subject "Hello" --stdin <<'TEXT'
52
+ the body
53
+ TEXT
54
+ ```
55
+
56
+ `gmail draft` leaves a draft in their Gmail and sends nothing. `--update <draft id>`
57
+ rewrites one you made. Sheet cells are written as plain values: a cell starting
58
+ with `=` stays text.
59
+
60
+ ## Sending email and changing the calendar — these LEAVE the account
61
+
62
+ ```bash
63
+ node ~/.claude/skills/shadok-google/scripts/google.mjs gmail send --account <id> --to ana@example.com [--cc …] [--bcc …] --subject "Hello" [--attach /abs/file.pdf] --stdin <<'TEXT'
64
+ the exact body
65
+ TEXT
66
+ node ~/.claude/skills/shadok-google/scripts/google.mjs calendar create --account <id> --title "Review" --start 2026-11-20T10:00 --end 2026-11-20T11:00 --tz Europe/Paris [--attendee ana@example.com] [--location "Room 2"] [--stdin]
67
+ node ~/.claude/skills/shadok-google/scripts/google.mjs calendar update --account <id> --event <id> [--title …] [--start … --end …] [--tz …]
68
+ node ~/.claude/skills/shadok-google/scripts/google.mjs calendar delete --account <id> --event <id>
69
+ ```
70
+
71
+ A time without an offset needs `--tz` (an IANA name); a time with one
72
+ (`…T10:00:00+01:00`) is taken as it is. Dates only make an all-day event, and
73
+ the end is the day AFTER the last day (`--start 2026-11-20 --end 2026-11-21`
74
+ is the 20th alone). `--stdin` on a
75
+ calendar command is the event's description. Attendees are emailed by Google.
76
+ `--to`, `--cc`, `--bcc`, `--attendee` and `--attach` may be repeated;
77
+ `--attach` takes absolute paths.
78
+
79
+ Show the person the final email or event in the chat FIRST, exactly as it will
80
+ go out, unless they already approved it.
81
+
82
+ ## Never claim it is sent until you are told
83
+
84
+ With `mail=approve` a `gmail send` does not send: it puts the email in their
85
+ Gmail drafts and shows an approval card in the cockpit. With `events=approve` a
86
+ calendar change waits on a card the same way. The command says so ("waiting
87
+ for approval"). Do not say it is sent or done: a hidden notice reaches you
88
+ when the person approves or discards it. The person may edit the draft in
89
+ Gmail before sending — what goes out is their version. If you are told the
90
+ draft "is no longer in Gmail", they deleted it or sent it from Gmail
91
+ themselves: ask before sending it again. You cannot change or
92
+ delete an email that is waiting for approval; a new `gmail send` makes a new
93
+ card. Only "Sent." / "Created event …" means it already happened.
94
+
95
+ If the server refuses, the script prints its sentence and exits 1 — relay it
96
+ as it is, and do not retry in a loop. "needs a reconnect" is for the account's
97
+ owner to do in the cockpit; you cannot.
98
+
99
+ ## Authenticating a direct API call
100
+
101
+ The commands above do this for you. If you call the cockpit's API yourself,
102
+ send your session key — it is in your environment and it does not expire:
103
+
104
+ ```bash
105
+ curl -sS -H "x-shadok-session-key: $SHADOK_SESSION_KEY" \
106
+ "http://127.0.0.1:$SHADOK_PORT/social/accounts"
107
+ ```
108
+
109
+ That key is your ONLY credential, and it does not expire. You are no longer
110
+ handed a cookie or the cockpit password, and a call made with the key is made
111
+ as YOU — an agent of your own group, never an admin: account, backend and
112
+ other cockpit-admin routes answer `403`, and so do the person-only (browser)
113
+ ones such as approving an email. That is by design; ask the human. A
114
+ `401` means that header is missing — or that you were started before this
115
+ existed, in which case nothing you hold can authenticate any more and only a
116
+ human can fix it: ask them for *Reload agent* on your ⋯ menu.
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env node
2
+ // Work in a Google account the person connected in the cockpit: calendar,
3
+ // Drive files the cockpit created, Docs, Sheets, Gmail drafts and sending.
4
+ //
5
+ // The OAuth token is never here: the server holds it and calls Google on the
6
+ // agent's behalf. This script only ever sends the session key and the request.
7
+ // Bodies (a mail body, a document's text, rows, an event description) are read
8
+ // from stdin so they never sit in argv.
9
+ import path from "node:path";
10
+
11
+ const USAGE = `usage: google.mjs <command>
12
+ accounts
13
+ calendar list --account <id> [--from <date>] [--to <date>] [--calendar <id>] [--max <n>]
14
+ calendar create --account <id> --title <t> --start <when> --end <when> [--tz <zone>] [--attendee <email>]... [--location <l>] [--calendar <id>] [--stdin]
15
+ calendar update --account <id> --event <id> [--title <t>] [--start <when> --end <when>] [--tz <zone>] [--attendee <email>]... [--location <l>] [--calendar <id>] [--stdin]
16
+ calendar delete --account <id> --event <id> [--calendar <id>]
17
+ drive list --account <id> [--max <n>]
18
+ doc create --account <id> --title <t> [--stdin]
19
+ doc read --account <id> --id <doc id>
20
+ doc append --account <id> --id <doc id> --stdin
21
+ sheet create --account <id> --title <t>
22
+ sheet read --account <id> --id <sheet id> [--range <A1 range>]
23
+ sheet append --account <id> --id <sheet id> [--range <A1 range>] --stdin (stdin: JSON array of rows)
24
+ gmail draft --account <id> --to <email>... [--cc <email>]... [--bcc <email>]... --subject <s> [--attach <abs path>]... [--update <draft id>] --stdin
25
+ gmail send --account <id> --to <email>... [--cc <email>]... [--bcc <email>]... --subject <s> [--attach <abs path>]... --stdin`;
26
+ const die = (m) => { console.error(m); process.exit(1); };
27
+
28
+ async function readStdin() {
29
+ const chunks = [];
30
+ for await (const c of process.stdin) chunks.push(c);
31
+ return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
32
+ }
33
+
34
+ function connection() {
35
+ const port = process.env.SHADOK_PORT;
36
+ const key = process.env.SHADOK_SESSION_KEY;
37
+ if (!port) die("Not inside a shadok-ai agent (SHADOK_PORT unset).");
38
+ if (!key) die("SHADOK_SESSION_KEY is unset — ask the human to reload this agent.");
39
+ return { port, key };
40
+ }
41
+
42
+ async function call(method, route, payload) {
43
+ const { port, key } = connection();
44
+ let res;
45
+ try {
46
+ res = await fetch(`http://127.0.0.1:${port}${route}`, {
47
+ method,
48
+ headers: { "content-type": "application/json", "x-shadok-session-key": key },
49
+ ...(payload ? { body: JSON.stringify(payload) } : {}),
50
+ signal: AbortSignal.timeout(90_000),
51
+ });
52
+ } catch (e) {
53
+ die(`The cockpit did not answer (${e?.message ?? e}). It may be restarting — say so rather than working around it.`);
54
+ }
55
+ const body = await res.json().catch(() => ({}));
56
+ if (!res.ok) die(body.error ?? `Refused (${res.status}): no reason given`);
57
+ return body;
58
+ }
59
+
60
+ const day = (ms) => (typeof ms === "number" ? new Date(ms).toISOString().slice(0, 10) : "none");
61
+
62
+ async function accounts() {
63
+ const { accounts: list = [] } = await call("GET", "/social/accounts");
64
+ const mine = list.filter((a) => a.provider === "google");
65
+ if (!mine.length) {
66
+ console.log("No Google account is available to this agent. Ask the person to connect one in Secrets → Connected accounts, or to share theirs with this agent's group.");
67
+ return;
68
+ }
69
+ // Only these fields are ever printed, whatever else the server sent.
70
+ for (const a of mine) {
71
+ const areas = Array.isArray(a.areas) ? a.areas.join(",") : "";
72
+ const p = a.policies ?? {};
73
+ console.log(`${String(a.id).slice(0, 8)} ${a.label} areas=${areas || "none"} mail=${p.mail ?? "approve"} events=${p.calendar ?? "approve"} reconnect-by=${day(a.expiresAt)}${a.status === "expired" ? " EXPIRED" : ""}`);
74
+ }
75
+ }
76
+
77
+ // Which flags each command takes: name → kind. "list" flags may repeat.
78
+ const FLAGS = {
79
+ account: "one", from: "one", to: "list", calendar: "one", max: "num", title: "one", start: "one", end: "one", tz: "one",
80
+ attendee: "list", location: "one", event: "one", id: "one", range: "one", cc: "list", bcc: "list", subject: "one",
81
+ attach: "list", update: "one", stdin: "flag",
82
+ };
83
+
84
+ function parse(args, listTo) {
85
+ const o = { stdin: false };
86
+ for (let i = 0; i < args.length; i++) {
87
+ const m = /^--([a-z]+)$/.exec(args[i]);
88
+ const kind = m && FLAGS[m[1]];
89
+ if (!kind) die(USAGE);
90
+ const k = m[1];
91
+ if (kind === "flag") { o[k] = true; continue; }
92
+ const v = args[++i];
93
+ if (v === undefined) die(`--${k} needs a value.`);
94
+ // `--to` is a recipient (repeatable) for gmail, a date for `calendar list`.
95
+ if (kind === "list" && (k !== "to" || listTo)) (o[k] ??= []).push(v);
96
+ else if (kind === "num") {
97
+ o[k] = Number(v);
98
+ if (!Number.isFinite(o[k])) die(`--${k} must be a number.`);
99
+ } else o[k] = v;
100
+ }
101
+ if (!o.account) die("--account <id> is required (see `accounts`).");
102
+ return o;
103
+ }
104
+
105
+ const ACTIONS = {
106
+ "calendar list": "calendar.list", "calendar create": "calendar.create", "calendar update": "calendar.update", "calendar delete": "calendar.delete",
107
+ "drive list": "drive.list", "doc create": "doc.create", "doc read": "doc.read", "doc append": "doc.append",
108
+ "sheet create": "sheet.create", "sheet read": "sheet.read", "sheet append": "sheet.append", "gmail draft": "gmail.draft", "gmail send": "gmail.send",
109
+ };
110
+
111
+ function eventArgs(o, text) {
112
+ return {
113
+ ...(o.calendar ? { calendar: o.calendar } : {}),
114
+ ...(o.event ? { event: o.event } : {}),
115
+ ...(o.title !== undefined ? { title: o.title } : {}),
116
+ ...(o.start !== undefined ? { start: o.start } : {}),
117
+ ...(o.end !== undefined ? { end: o.end } : {}),
118
+ ...(o.tz ? { timeZone: o.tz } : {}),
119
+ ...(o.attendee ? { attendees: o.attendee } : {}),
120
+ ...(o.location !== undefined ? { location: o.location } : {}),
121
+ ...(text !== null ? { description: text } : {}),
122
+ };
123
+ }
124
+
125
+ function print(action, out) {
126
+ if (out.status === "pending") {
127
+ const what = action === "gmail.send" ? "The email is a Gmail draft and" : "The calendar change";
128
+ console.log(`${what} is waiting for approval in the cockpit (draft ${out.draftId}). Nothing has left the account. Do not say it is sent or done until you are told.`);
129
+ return;
130
+ }
131
+ const r = out.result ?? {};
132
+ if (action === "calendar.list") {
133
+ if (!r.events?.length) return console.log("No event in that window.");
134
+ for (const e of r.events) {
135
+ console.log(`${e.id} ${e.start} → ${e.end}${e.timeZone ? ` (${e.timeZone})` : ""} ${e.title}${e.attendees?.length ? ` [${e.attendees.join(", ")}]` : ""}${e.location ? ` @ ${e.location}` : ""}`);
136
+ }
137
+ } else if (action === "drive.list") {
138
+ if (!r.files?.length) return console.log("No file yet. Only files created through this cockpit are visible (not the person's whole Drive).");
139
+ for (const f of r.files) console.log(`${f.id} ${f.name} ${f.mimeType}${f.modifiedTime ? ` ${f.modifiedTime}` : ""}`);
140
+ } else if (action === "doc.read") {
141
+ console.log(`# ${r.name}\n${r.text}`);
142
+ } else if (action === "sheet.read") {
143
+ console.log(JSON.stringify(r.rows ?? []));
144
+ } else if (action === "doc.create" || action === "sheet.create") {
145
+ console.log(`Created ${r.id}: ${r.link}`);
146
+ } else if (action === "doc.append") {
147
+ console.log("Appended.");
148
+ } else if (action === "sheet.append") {
149
+ console.log(`Appended${r.updatedRange ? ` at ${r.updatedRange}` : ""}.`);
150
+ } else if (action === "gmail.draft") {
151
+ console.log(`Draft ${r.draftId} is in the person's Gmail drafts. Nothing was sent.`);
152
+ } else if (action === "gmail.send") {
153
+ console.log("Sent.");
154
+ } else if (action === "calendar.create" || action === "calendar.update") {
155
+ console.log(`${r.status === "created" ? "Created" : "Updated"} event ${r.event?.id ?? ""}${r.event?.link ? `: ${r.event.link}` : ""}`);
156
+ } else if (action === "calendar.delete") {
157
+ console.log("Event deleted.");
158
+ }
159
+ }
160
+
161
+ async function run(group, verb, rest) {
162
+ const action = ACTIONS[`${group} ${verb}`];
163
+ if (!action) die(USAGE);
164
+ const mail = action.startsWith("gmail.");
165
+ const o = parse(rest, mail);
166
+ const needsStdin = mail || action === "doc.append" || action === "sheet.append";
167
+ if (needsStdin && !o.stdin) die(`${group} ${verb} requires --stdin: the content is read from stdin so it never sits in argv.`);
168
+ const text = o.stdin ? await readStdin() : null;
169
+ for (const p of o.attach ?? []) if (!path.isAbsolute(p)) die(`An attachment path must be absolute; '${p}' is not.`);
170
+ let args;
171
+ if (action === "calendar.list") args = { ...(o.calendar ? { calendar: o.calendar } : {}), ...(o.from ? { from: o.from } : {}), ...(o.to ? { to: o.to } : {}), ...(o.max ? { max: o.max } : {}) };
172
+ else if (action.startsWith("calendar.")) args = eventArgs(o, text);
173
+ else if (action === "drive.list") args = { ...(o.max ? { max: o.max } : {}) };
174
+ else if (action === "doc.create") args = { title: o.title, ...(text ? { text } : {}) };
175
+ else if (action === "sheet.create") args = { title: o.title };
176
+ else if (action === "doc.read") args = { id: o.id };
177
+ else if (action === "doc.append") args = { id: o.id, text };
178
+ else if (action === "sheet.read") args = { id: o.id, ...(o.range ? { range: o.range } : {}) };
179
+ else if (action === "sheet.append") {
180
+ let rows;
181
+ try { rows = JSON.parse(text); } catch { die("sheet append reads a JSON array of rows from stdin, e.g. [[\"Name\",\"Qty\"],[\"Bolt\",12]]."); }
182
+ args = { id: o.id, rows, ...(o.range ? { range: o.range } : {}) };
183
+ } else {
184
+ if (!text || !text.trim()) die("The email body is empty.");
185
+ args = { to: o.to ?? [], cc: o.cc ?? [], bcc: o.bcc ?? [], subject: o.subject, body: text, ...(o.attach ? { attachments: o.attach } : {}), ...(o.update ? { update: o.update } : {}) };
186
+ }
187
+ print(action, await call("POST", "/google/actions", { account: o.account, action, args }));
188
+ }
189
+
190
+ const [cmd, verb, ...rest] = process.argv.slice(2);
191
+ if (cmd === "accounts") await accounts();
192
+ else if (cmd && verb) await run(cmd, verb, rest);
193
+ else die(USAGE);
@@ -0,0 +1,172 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import http from "node:http";
4
+ import path from "node:path";
5
+ import { execFile } from "node:child_process";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ const SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "scripts", "google.mjs");
9
+
10
+ async function stub(status, body) {
11
+ const seen = {};
12
+ const server = http.createServer((req, res) => {
13
+ let raw = "";
14
+ req.on("data", (c) => (raw += c));
15
+ req.on("end", () => {
16
+ seen.method = req.method;
17
+ seen.url = req.url;
18
+ seen.key = req.headers["x-shadok-session-key"];
19
+ seen.body = raw ? JSON.parse(raw) : undefined;
20
+ res.writeHead(status, { "content-type": "application/json" });
21
+ res.end(JSON.stringify(body));
22
+ });
23
+ });
24
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
25
+ return { port: server.address().port, seen, close: () => new Promise((r) => server.close(r)) };
26
+ }
27
+
28
+ function run(args, port, stdin = "") {
29
+ return new Promise((resolve) => {
30
+ const child = execFile(
31
+ process.execPath,
32
+ [SCRIPT, ...args],
33
+ { env: { ...process.env, SHADOK_PORT: String(port), SHADOK_SESSION_KEY: "key-123" } },
34
+ (e, out, err) => resolve({ code: e ? (e.code ?? 1) : 0, out, err }),
35
+ );
36
+ child.stdin.end(stdin);
37
+ });
38
+ }
39
+
40
+ /** One run against a stub that is always closed, even when an assertion throws. */
41
+ async function withStub(status, body, fn) {
42
+ const s = await stub(status, body);
43
+ try {
44
+ return await fn(s);
45
+ } finally {
46
+ await s.close();
47
+ }
48
+ }
49
+
50
+ test("gmail send: the body comes from stdin, the fields from flags, the key in the header — and pending is explained", async () => {
51
+ await withStub(200, { status: "pending", draftId: "ab12cd34" }, async (s) => {
52
+ const r = await run(["gmail", "send", "--account", "g1", "--to", "bob@example.org", "--to", "cat@example.org", "--cc", "dan@example.org", "--subject", "Numbers", "--attach", "/tmp/q3.pdf", "--stdin"], s.port, "Hi Bob,\n\nHere.\n");
53
+ assert.equal(r.code, 0, r.err);
54
+ assert.equal(s.seen.url, "/google/actions");
55
+ assert.equal(s.seen.key, "key-123");
56
+ assert.deepEqual(s.seen.body, {
57
+ account: "g1",
58
+ action: "gmail.send",
59
+ args: { to: ["bob@example.org", "cat@example.org"], cc: ["dan@example.org"], bcc: [], subject: "Numbers", body: "Hi Bob,\n\nHere.", attachments: ["/tmp/q3.pdf"] },
60
+ });
61
+ assert.match(r.out, /waiting for approval in the cockpit \(draft ab12cd34\)\. Nothing has left the account\. Do not say it is sent or done until you are told\./);
62
+ assert.doesNotMatch(r.out + r.err, /key-123/);
63
+ });
64
+ });
65
+
66
+ test("the body is never taken from argv: gmail and append commands refuse to run without --stdin", async () => {
67
+ await withStub(200, {}, async (s) => {
68
+ for (const args of [
69
+ ["gmail", "send", "--account", "g1", "--to", "a@b.co", "--subject", "x"],
70
+ ["gmail", "draft", "--account", "g1", "--to", "a@b.co", "--subject", "x"],
71
+ ["doc", "append", "--account", "g1", "--id", "d1"],
72
+ ["sheet", "append", "--account", "g1", "--id", "s1"],
73
+ ]) {
74
+ const r = await run(args, s.port);
75
+ assert.equal(r.code, 1, args.join(" "));
76
+ assert.match(r.err, /requires --stdin/);
77
+ }
78
+ const body = await run(["gmail", "send", "--account", "g1", "--to", "a@b.co", "--subject", "x", "--body", "inline"], s.port);
79
+ assert.equal(body.code, 1, "there is no --body flag");
80
+ assert.equal(s.seen.url, undefined, "nothing reached the cockpit");
81
+ });
82
+ });
83
+
84
+ test("an empty body and a relative attachment are refused locally", async () => {
85
+ await withStub(200, {}, async (s) => {
86
+ const empty = await run(["gmail", "send", "--account", "g1", "--to", "a@b.co", "--subject", "x", "--stdin"], s.port, " \n");
87
+ assert.equal(empty.code, 1);
88
+ assert.match(empty.err, /body is empty/);
89
+ const rel = await run(["gmail", "send", "--account", "g1", "--to", "a@b.co", "--subject", "x", "--attach", "q3.pdf", "--stdin"], s.port, "hi");
90
+ assert.equal(rel.code, 1);
91
+ assert.match(rel.err, /must be absolute/);
92
+ assert.equal(s.seen.url, undefined);
93
+ });
94
+ });
95
+
96
+ test("calendar create: flags become the event, stdin its description; --to is a DATE for calendar list", async () => {
97
+ await withStub(200, { status: "pending", draftId: "ee11" }, async (s) => {
98
+ const r = await run(["calendar", "create", "--account", "g1", "--title", "Review", "--start", "2026-11-20T10:00", "--end", "2026-11-20T11:00", "--tz", "Europe/Paris", "--attendee", "bob@example.org", "--location", "Room 2", "--stdin"], s.port, "Agenda\n");
99
+ assert.equal(r.code, 0, r.err);
100
+ assert.deepEqual(s.seen.body, {
101
+ account: "g1",
102
+ action: "calendar.create",
103
+ args: { title: "Review", start: "2026-11-20T10:00", end: "2026-11-20T11:00", timeZone: "Europe/Paris", attendees: ["bob@example.org"], location: "Room 2", description: "Agenda" },
104
+ });
105
+ assert.match(r.out, /The calendar change is waiting for approval/);
106
+ });
107
+ await withStub(200, { status: "done", result: { events: [{ id: "ev1", title: "Review", start: "2026-11-20T10:00:00+01:00", end: "2026-11-20T11:00:00+01:00", attendees: ["bob@example.org"] }] } }, async (s) => {
108
+ const r = await run(["calendar", "list", "--account", "g1", "--from", "2026-11-20", "--to", "2026-11-27"], s.port);
109
+ assert.deepEqual(s.seen.body, { account: "g1", action: "calendar.list", args: { from: "2026-11-20", to: "2026-11-27" } });
110
+ assert.match(r.out, /^ev1 {2}2026-11-20T10:00:00\+01:00 → 2026-11-20T11:00:00\+01:00 {2}Review {2}\[bob@example\.org\]/);
111
+ });
112
+ });
113
+
114
+ test("sheet append reads JSON rows from stdin; anything else is refused before the cockpit is called", async () => {
115
+ await withStub(200, { status: "done", result: { id: "s1", updatedRange: "Sheet1!A1:B2" } }, async (s) => {
116
+ const r = await run(["sheet", "append", "--account", "g1", "--id", "s1", "--stdin"], s.port, '[["Name","Qty"],["Bolt",12]]');
117
+ assert.deepEqual(s.seen.body, { account: "g1", action: "sheet.append", args: { id: "s1", rows: [["Name", "Qty"], ["Bolt", 12]] } });
118
+ assert.match(r.out, /Appended at Sheet1!A1:B2\./);
119
+ });
120
+ await withStub(200, {}, async (s) => {
121
+ const r = await run(["sheet", "append", "--account", "g1", "--id", "s1", "--stdin"], s.port, "Name,Qty");
122
+ assert.equal(r.code, 1);
123
+ assert.match(r.err, /JSON array of rows/);
124
+ assert.equal(s.seen.url, undefined);
125
+ });
126
+ });
127
+
128
+ test("done results are said plainly: sent, draft, created", async () => {
129
+ await withStub(200, { status: "done", result: { status: "sent", messageId: "m1" } }, async (s) => {
130
+ assert.match((await run(["gmail", "send", "--account", "g1", "--to", "a@b.co", "--subject", "x", "--stdin"], s.port, "hi")).out, /^Sent\.$/m);
131
+ });
132
+ await withStub(200, { status: "done", result: { draftId: "r9", status: "draft" } }, async (s) => {
133
+ const r = await run(["gmail", "draft", "--account", "g1", "--to", "a@b.co", "--subject", "x", "--update", "r1", "--stdin"], s.port, "hi");
134
+ assert.equal(s.seen.body.args.update, "r1");
135
+ assert.match(r.out, /Draft r9 is in the person's Gmail drafts\. Nothing was sent\./);
136
+ });
137
+ await withStub(200, { status: "done", result: { id: "doc1", name: "Notes", link: "https://docs.google.com/document/d/doc1/edit" } }, async (s) => {
138
+ const r = await run(["doc", "create", "--account", "g1", "--title", "Notes", "--stdin"], s.port, "first\n");
139
+ assert.deepEqual(s.seen.body, { account: "g1", action: "doc.create", args: { title: "Notes", text: "first" } });
140
+ assert.match(r.out, /Created doc1: https:\/\/docs\.google\.com\/document\/d\/doc1\/edit/);
141
+ });
142
+ });
143
+
144
+ test("accounts prints only the known fields of the Google accounts, never a token", async () => {
145
+ await withStub(200, { accounts: [
146
+ { id: "g1b2c3d4e5f6", label: "ana@example.org", provider: "google", kind: "member", policies: { mail: "approve", calendar: "autonomous" }, areas: ["calendar", "gmail"], expiresAt: Date.UTC(2026, 10, 20), status: "ok", token: "SECRET-TOK", refreshToken: "SECRET-REF" },
147
+ { id: "li000000", label: "Ana", provider: "linkedin", policy: "approve", expiresAt: 1, status: "ok" },
148
+ { id: "g2", label: "old@example.org", provider: "google", policies: { mail: "approve", calendar: "approve" }, areas: [], expiresAt: null, status: "expired" },
149
+ ] }, async (s) => {
150
+ const r = await run(["accounts"], s.port);
151
+ assert.equal(s.seen.url, "/social/accounts");
152
+ assert.equal(r.out, "g1b2c3d4 ana@example.org areas=calendar,gmail mail=approve events=autonomous reconnect-by=2026-11-20\ng2 old@example.org areas=none mail=approve events=approve reconnect-by=none EXPIRED\n");
153
+ assert.doesNotMatch(r.out + r.err, /SECRET|token|key-123/i);
154
+ });
155
+ await withStub(200, { accounts: [{ id: "li", provider: "linkedin" }] }, async (s) => {
156
+ assert.match((await run(["accounts"], s.port)).out, /No Google account is available to this agent/);
157
+ });
158
+ });
159
+
160
+ test("a refusal is relayed as the server's sentence, exit 1; an unknown command prints the usage", async () => {
161
+ await withStub(409, { error: "Google account 'ana@example.org' needs a reconnect (test app authorisations last 7 days) — ana can do it in Secrets → Connected accounts." }, async (s) => {
162
+ const r = await run(["drive", "list", "--account", "g1"], s.port);
163
+ assert.equal(r.code, 1);
164
+ assert.match(r.err, /needs a reconnect \(test app authorisations last 7 days\)/);
165
+ });
166
+ await withStub(200, {}, async (s) => {
167
+ const r = await run(["gmail", "read", "--account", "g1"], s.port);
168
+ assert.equal(r.code, 1);
169
+ assert.match(r.err, /usage: google\.mjs/);
170
+ assert.equal((await run(["drive", "list"], s.port)).code, 1, "--account is required");
171
+ });
172
+ });
@@ -44,7 +44,8 @@ async function call(method, route, payload) {
44
44
  const day = (ms) => new Date(ms).toISOString().slice(0, 10);
45
45
 
46
46
  async function accounts() {
47
- const { accounts: list = [] } = await call("GET", "/social/accounts");
47
+ // The route lists every connected account; Google's belong to shadok-google.
48
+ const list = ((await call("GET", "/social/accounts")).accounts ?? []).filter((a) => a.provider !== "google");
48
49
  if (!list.length) {
49
50
  console.log("No LinkedIn account is available to this agent. Ask the person to connect one in Secrets → Connected accounts, or to share theirs with this agent's group.");
50
51
  return;
@@ -135,3 +135,11 @@ test("the local post limit equals the server's MAX_COMMENTARY", async () => {
135
135
  assert.ok(local && server);
136
136
  assert.equal(local[1], server[1]);
137
137
  });
138
+
139
+ test("accounts lists LinkedIn accounts only: a Google account belongs to shadok-google", async () => {
140
+ const s = await stub(200, { accounts: [{ id: "g1", label: "ana@example.org", provider: "google", policies: {}, expiresAt: null, status: "ok" }] });
141
+ const r = await run(["accounts"], s.port);
142
+ await s.close();
143
+ assert.match(r.out, /No LinkedIn account is available to this agent/);
144
+ assert.doesNotMatch(r.out, /ana@example\.org|undefined|1970/);
145
+ });