goals-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +125 -2
  3. package/dist/args.js +96 -0
  4. package/dist/auth/command.js +16 -0
  5. package/dist/auth/help.js +82 -0
  6. package/dist/auth/list.js +41 -0
  7. package/dist/auth/login.js +203 -0
  8. package/dist/auth/logout.js +25 -0
  9. package/dist/auth/select.js +30 -0
  10. package/dist/auth/status.js +43 -0
  11. package/dist/auth/use.js +10 -0
  12. package/dist/cli.js +112 -0
  13. package/dist/commands/export-help.js +49 -0
  14. package/dist/commands/export.js +194 -0
  15. package/dist/commands/goal-flags.js +111 -0
  16. package/dist/commands/goal-format.js +95 -0
  17. package/dist/commands/goal-help.js +214 -0
  18. package/dist/commands/goal-read.js +80 -0
  19. package/dist/commands/goal-write.js +186 -0
  20. package/dist/commands/goal.js +15 -0
  21. package/dist/commands/initiative-help.js +38 -0
  22. package/dist/commands/initiative.js +81 -0
  23. package/dist/commands/list-output.js +13 -0
  24. package/dist/commands/skill-help.js +18 -0
  25. package/dist/commands/skill.js +36 -0
  26. package/dist/credentials.js +270 -0
  27. package/dist/deps.js +46 -0
  28. package/dist/dispatch.js +16 -0
  29. package/dist/endpoints.js +82 -0
  30. package/dist/errors.js +29 -0
  31. package/dist/help.js +105 -0
  32. package/dist/http.js +199 -0
  33. package/dist/iso-week.js +18 -0
  34. package/dist/open-browser.js +47 -0
  35. package/dist/output.js +29 -0
  36. package/dist/vendor/cli-contract/index.js +26 -0
  37. package/dist/vendor/quarterly-markdown/dateFormat.js +101 -0
  38. package/dist/vendor/quarterly-markdown/generate.js +450 -0
  39. package/dist/vendor/quarterly-markdown/htmlToPlainText.js +101 -0
  40. package/dist/vendor/quarterly-markdown/index.js +4 -0
  41. package/dist/vendor/quarterly-markdown/types.js +1 -0
  42. package/dist/vendor/quarterly-markdown/year.js +45 -0
  43. package/dist/version.js +9 -0
  44. package/package.json +37 -4
  45. package/skills/goals-cli/REFERENCE.md +212 -0
  46. package/skills/goals-cli/SKILL.md +12 -0
package/dist/http.js ADDED
@@ -0,0 +1,199 @@
1
+ import { CliError, safeMessage } from './errors.js';
2
+ const INVALID_RESPONSE = 'Invalid Goals response';
3
+ const UNAUTHORIZED = 'Credentials are invalid, expired or revoked; run `goals auth login` again.';
4
+ const NETWORK_FAILURE = 'Unable to contact Goals; please retry.';
5
+ const TIMEOUT_FAILURE = 'Goals did not respond in time; please retry.';
6
+ function isRecord(value) {
7
+ return typeof value === 'object' && value !== null;
8
+ }
9
+ function isString(value) {
10
+ return typeof value === 'string';
11
+ }
12
+ function isNumber(value) {
13
+ return typeof value === 'number' && Number.isFinite(value);
14
+ }
15
+ function hasFields(record, fields) {
16
+ return Object.entries(fields).every(([key, type]) => type === 'string' ? isString(record[key]) : isNumber(record[key]));
17
+ }
18
+ const LOGIN_REQUEST_FIELDS = {
19
+ requestId: 'string',
20
+ deviceCode: 'string',
21
+ userCode: 'string',
22
+ expiresAt: 'number',
23
+ intervalMs: 'number',
24
+ };
25
+ function isLoginRequestResponse(value) {
26
+ return isRecord(value) && hasFields(value, LOGIN_REQUEST_FIELDS);
27
+ }
28
+ const APPROVED_FIELDS = {
29
+ token: 'string',
30
+ tokenId: 'string',
31
+ expiresAt: 'number',
32
+ };
33
+ function isAccount(value) {
34
+ if (!isRecord(value))
35
+ return false;
36
+ const emailOk = value.email === undefined || isString(value.email);
37
+ return hasFields(value, { userId: 'string', name: 'string' }) && emailOk;
38
+ }
39
+ function isApproved(value) {
40
+ if (!isRecord(value) || value.status !== 'approved')
41
+ return false;
42
+ return hasFields(value, APPROVED_FIELDS) && isAccount(value.account);
43
+ }
44
+ function parseApproved(json) {
45
+ if (!isApproved(json))
46
+ throw new CliError(INVALID_RESPONSE);
47
+ return json;
48
+ }
49
+ function parsePending(json) {
50
+ if (!isRecord(json) || !isNumber(json.intervalMs))
51
+ throw new CliError(INVALID_RESPONSE);
52
+ return { status: 'pending', intervalMs: json.intervalMs };
53
+ }
54
+ function parseGone(json) {
55
+ const consumed = isRecord(json) && json.status === 'consumed';
56
+ return { status: consumed ? 'consumed' : 'expired' };
57
+ }
58
+ const EXCHANGE_PARSERS = {
59
+ 200: parseApproved,
60
+ 202: parsePending,
61
+ 403: () => ({ status: 'denied' }),
62
+ 404: () => ({ status: 'not_found' }),
63
+ 410: parseGone,
64
+ };
65
+ function backendMessage(json) {
66
+ return isRecord(json) && isRecord(json.error) ? json.error.message : undefined;
67
+ }
68
+ function genericFailure(label, status, json) {
69
+ return new CliError(safeMessage(backendMessage(json), `Goals ${label} request failed (HTTP ${status})`));
70
+ }
71
+ function parseExchange(status, json) {
72
+ const parser = EXCHANGE_PARSERS[status];
73
+ if (parser === undefined)
74
+ throw genericFailure('login poll', status, json);
75
+ return parser(json);
76
+ }
77
+ function parseCallData(json) {
78
+ if (!isRecord(json) || json.ok !== true)
79
+ throw new CliError(INVALID_RESPONSE);
80
+ return json.data;
81
+ }
82
+ function parseCall(status, op, json) {
83
+ if (status === 200)
84
+ return parseCallData(json);
85
+ if (status === 401)
86
+ throw new CliError(UNAUTHORIZED);
87
+ throw genericFailure(op, status, json);
88
+ }
89
+ function requestHeaders(token) {
90
+ const headers = {
91
+ 'Content-Type': 'application/json',
92
+ Accept: 'application/json',
93
+ 'Cache-Control': 'no-store',
94
+ };
95
+ if (token !== undefined)
96
+ headers.Authorization = `Bearer ${token}`;
97
+ return headers;
98
+ }
99
+ function requestInit(request, signal) {
100
+ return {
101
+ method: 'POST',
102
+ headers: requestHeaders(request.token),
103
+ body: request.body === undefined ? undefined : JSON.stringify(request.body),
104
+ redirect: 'error',
105
+ signal,
106
+ };
107
+ }
108
+ async function readJsonBody(response) {
109
+ const text = await response.text();
110
+ try {
111
+ return JSON.parse(text);
112
+ }
113
+ catch {
114
+ return undefined;
115
+ }
116
+ }
117
+ /** Forwards an optional caller signal into the request controller; returns the listener. */
118
+ function linkAbort(controller, external) {
119
+ const forward = () => controller.abort();
120
+ external?.addEventListener('abort', forward, { once: true });
121
+ if (external?.aborted)
122
+ controller.abort();
123
+ return forward;
124
+ }
125
+ /** One POST that owns its timeout, cancellation and body read. */
126
+ function createSend(deps, timeoutMs) {
127
+ return async function send(request) {
128
+ const controller = new AbortController();
129
+ let timedOut = false;
130
+ const timer = setTimeout(() => {
131
+ timedOut = true;
132
+ controller.abort();
133
+ }, timeoutMs);
134
+ const forwardAbort = linkAbort(controller, request.signal);
135
+ try {
136
+ const url = new URL(request.path, request.origin).toString();
137
+ const response = await deps.fetch(url, requestInit(request, controller.signal));
138
+ return { status: response.status, json: await readJsonBody(response) };
139
+ }
140
+ catch {
141
+ throw new CliError(timedOut ? TIMEOUT_FAILURE : NETWORK_FAILURE);
142
+ }
143
+ finally {
144
+ clearTimeout(timer);
145
+ request.signal?.removeEventListener('abort', forwardAbort);
146
+ }
147
+ };
148
+ }
149
+ export function createApiClient(deps) {
150
+ const send = createSend(deps, deps.timeoutMs ?? 30000);
151
+ return {
152
+ async createLoginRequest(base, body, signal) {
153
+ const { status, json } = await send({
154
+ origin: base.convexUrl,
155
+ path: '/cli/auth/requests',
156
+ body,
157
+ signal,
158
+ });
159
+ if (status === 201) {
160
+ if (!isLoginRequestResponse(json))
161
+ throw new CliError(INVALID_RESPONSE);
162
+ return json;
163
+ }
164
+ if (status === 429)
165
+ throw new CliError('Too many login attempts; wait a minute and retry.');
166
+ throw genericFailure('login', status, json);
167
+ },
168
+ async exchangeLoginRequest(base, body, signal) {
169
+ const { status, json } = await send({
170
+ origin: base.convexUrl,
171
+ path: '/cli/auth/token',
172
+ body,
173
+ signal,
174
+ });
175
+ return parseExchange(status, json);
176
+ },
177
+ async revoke(credential) {
178
+ const { status, json } = await send({
179
+ origin: credential.convexUrl,
180
+ path: '/cli/auth/revoke',
181
+ token: credential.token,
182
+ });
183
+ if (status === 200)
184
+ return 'revoked';
185
+ if (status === 401)
186
+ return 'already-invalid';
187
+ throw genericFailure('logout', status, json);
188
+ },
189
+ async call(credential, op, args) {
190
+ const { status, json } = await send({
191
+ origin: credential.convexUrl,
192
+ path: '/cli/v1/call',
193
+ token: credential.token,
194
+ body: { op, args },
195
+ });
196
+ return parseCall(status, op, json);
197
+ },
198
+ };
199
+ }
@@ -0,0 +1,18 @@
1
+ const DAY_MS = 24 * 60 * 60 * 1000;
2
+ /**
3
+ * ISO-8601 week-year and week number of the local calendar date of `ms`.
4
+ *
5
+ * The machine's local calendar date decides the answer (so a timestamp late on Sunday is
6
+ * that Sunday's week, whatever the UTC date is); the arithmetic afterwards runs in UTC so
7
+ * DST shifts cannot move the result by a day.
8
+ */
9
+ export function isoWeekOf(ms) {
10
+ const local = new Date(ms);
11
+ const date = new Date(Date.UTC(local.getFullYear(), local.getMonth(), local.getDate()));
12
+ const dayOfWeek = date.getUTCDay() || 7; // Monday = 1 … Sunday = 7
13
+ date.setUTCDate(date.getUTCDate() + 4 - dayOfWeek); // Thursday identifies the week's year
14
+ const year = date.getUTCFullYear();
15
+ const firstThursday = Date.UTC(year, 0, 1);
16
+ const week = Math.floor((date.getTime() - firstThursday) / DAY_MS / 7) + 1;
17
+ return { year, week };
18
+ }
@@ -0,0 +1,47 @@
1
+ import { spawn } from 'node:child_process';
2
+ /** Opens `command` detached from this process; resolves on close and rejects on spawn errors. */
3
+ function spawnDetached(command, args) {
4
+ return new Promise((resolve, reject) => {
5
+ const child = spawn(command, args, { stdio: 'ignore', shell: false });
6
+ child.once('error', reject);
7
+ child.once('close', () => resolve());
8
+ });
9
+ }
10
+ /** The OS command that hands `url` to the default browser. */
11
+ function launchCommand(platform, url) {
12
+ if (platform === 'darwin')
13
+ return { command: 'open', args: [url] };
14
+ if (platform === 'win32')
15
+ return { command: 'cmd', args: ['/c', 'start', '', url] };
16
+ return { command: 'xdg-open', args: [url] };
17
+ }
18
+ /** True only for absolute http(s) URLs; anything else must never be spawned. */
19
+ function isHttpUrl(value) {
20
+ try {
21
+ const { protocol } = new URL(value);
22
+ return protocol === 'http:' || protocol === 'https:';
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ /** Runs the OS opener; any failure (missing binary, headless box) is a quiet `false`. */
29
+ async function launchBrowser(launch, spawn) {
30
+ try {
31
+ await spawn(launch.command, launch.args);
32
+ return true;
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ /**
39
+ * Best-effort browser launch: returns `true` when the platform opener ran, `false` for a
40
+ * non-http(s) URL or any spawn failure. Never throws, so a headless machine still logs in.
41
+ */
42
+ export async function openBrowserBestEffort(url, options = {}) {
43
+ if (!isHttpUrl(url))
44
+ return false;
45
+ const platform = options.platform ?? process.platform;
46
+ return launchBrowser(launchCommand(platform, url), options.spawn ?? spawnDetached);
47
+ }
package/dist/output.js ADDED
@@ -0,0 +1,29 @@
1
+ /** `Key:` + padding to a common column (longest key + colon + two spaces); one row per line. */
2
+ export function formatKeyValues(rows) {
3
+ const width = rows.reduce((longest, [key]) => Math.max(longest, key.length), 0) + 3;
4
+ const lines = rows.map(([key, value]) => `${`${key}:`.padEnd(width)}${value}`);
5
+ return `${lines.join('\n')}\n`;
6
+ }
7
+ function columnWidths(headers, rows) {
8
+ return headers.map((header, column) => rows.reduce((longest, row) => Math.max(longest, row[column]?.length ?? 0), header.length));
9
+ }
10
+ function tableLine(cells, widths, marker) {
11
+ const padded = cells.map((cell, column) => cell.padEnd(widths[column] ?? 0));
12
+ return `${marker}${padded.join(' ')}`.trimEnd();
13
+ }
14
+ /**
15
+ * Left-aligned columns separated by two spaces, each line trimEnd()-ed. `markers[i]` is
16
+ * prepended to body row i; the header always gets two spaces so columns stay aligned.
17
+ */
18
+ export function formatTable(headers, rows, markers) {
19
+ const widths = columnWidths(headers, rows);
20
+ const lines = [
21
+ tableLine(headers, widths, ' '),
22
+ ...rows.map((row, index) => tableLine(row, widths, markers[index] ?? ' ')),
23
+ ];
24
+ return `${lines.join('\n')}\n`;
25
+ }
26
+ /** `JSON.stringify(value, null, 2)` plus one trailing newline. */
27
+ export function toJson(value) {
28
+ return `${JSON.stringify(value, null, 2)}\n`;
29
+ }
@@ -0,0 +1,26 @@
1
+ // GENERATED by packages/cli/scripts/vendor-shared.mjs from packages/shared — do not edit.
2
+ /**
3
+ * Wire contract shared by the `goals` CLI and the backend gateway.
4
+ *
5
+ * This module is intentionally type-only apart from `CLI_OP_NAMES`: the CLI
6
+ * compiles against it without pulling the Convex runtime, and the backend
7
+ * imports it with `import type` so nothing resolves in the Convex bundle.
8
+ * The only structural dependency is the quarterly markdown summary shape that
9
+ * `export.quarterSummary` returns.
10
+ */
11
+ // Compile-time exhaustive: adding an op to CliOpMap without listing it here is
12
+ // an error, and so is an extra key.
13
+ const OP_NAME_SET = {
14
+ 'auth.whoami': true,
15
+ 'goal.list': true,
16
+ 'goal.get': true,
17
+ 'goal.create': true,
18
+ 'goal.rename': true,
19
+ 'goal.setComplete': true,
20
+ 'goal.delete': true,
21
+ 'initiative.list': true,
22
+ 'initiative.get': true,
23
+ 'export.quarterSummary': true,
24
+ };
25
+ /** Sorted op names; the gateway registry must declare exactly these keys. */
26
+ export const CLI_OP_NAMES = Object.keys(OP_NAME_SET).sort();
@@ -0,0 +1,101 @@
1
+ // GENERATED by packages/cli/scripts/vendor-shared.mjs from packages/shared — do not edit.
2
+ /**
3
+ * Fixed English date formatting for quarterly markdown.
4
+ *
5
+ * Constraint: uses Intl.DateTimeFormat parts only (never toLocaleDateString /
6
+ * toLocaleTimeString, which can emit locale variants or U+202F), so the output
7
+ * is stable across environments. `timeZone` undefined means the system zone,
8
+ * matching the legacy behavior.
9
+ */
10
+ const MONTHS = [
11
+ 'Jan',
12
+ 'Feb',
13
+ 'Mar',
14
+ 'Apr',
15
+ 'May',
16
+ 'Jun',
17
+ 'Jul',
18
+ 'Aug',
19
+ 'Sep',
20
+ 'Oct',
21
+ 'Nov',
22
+ 'Dec',
23
+ ];
24
+ const formatterCache = new Map();
25
+ function formatterFor(timeZone) {
26
+ const key = timeZone ?? '';
27
+ const cached = formatterCache.get(key);
28
+ if (cached)
29
+ return cached;
30
+ const formatter = new Intl.DateTimeFormat('en-US', {
31
+ timeZone,
32
+ year: 'numeric',
33
+ month: 'numeric',
34
+ day: 'numeric',
35
+ hour: 'numeric',
36
+ minute: 'numeric',
37
+ hourCycle: 'h23',
38
+ });
39
+ formatterCache.set(key, formatter);
40
+ return formatter;
41
+ }
42
+ function partsOf(ms, timeZone) {
43
+ const values = {};
44
+ for (const part of formatterFor(timeZone).formatToParts(ms)) {
45
+ if (part.type !== 'literal')
46
+ values[part.type] = Number(part.value);
47
+ }
48
+ return {
49
+ year: values.year,
50
+ month: values.month,
51
+ day: values.day,
52
+ hour: values.hour % 24,
53
+ minute: values.minute,
54
+ };
55
+ }
56
+ const pad2 = (n) => String(n).padStart(2, '0');
57
+ /**
58
+ * Formats an instant as a `yyyy-MM-dd` grouping key in the given zone.
59
+ *
60
+ * @param ms - epoch milliseconds
61
+ * @param timeZone - IANA zone; defaults to the system zone
62
+ * @returns date key such as `2026-11-19`
63
+ */
64
+ export function formatDateKey(ms, timeZone) {
65
+ const p = partsOf(ms, timeZone);
66
+ return `${String(p.year).padStart(4, '0')}-${pad2(p.month)}-${pad2(p.day)}`;
67
+ }
68
+ /**
69
+ * Formats an instant as `LLL d, yyyy` in the given zone.
70
+ *
71
+ * @param ms - epoch milliseconds
72
+ * @param timeZone - IANA zone; defaults to the system zone
73
+ * @returns date such as `Nov 19, 2026`
74
+ */
75
+ export function formatDay(ms, timeZone) {
76
+ const p = partsOf(ms, timeZone);
77
+ return `${MONTHS[p.month - 1]} ${p.day}, ${p.year}`;
78
+ }
79
+ /**
80
+ * Formats a `yyyy-MM-dd` key as `LLL d, yyyy` without re-parsing in a zone.
81
+ *
82
+ * @param key - date key produced by `formatDateKey`
83
+ * @returns date such as `Nov 19, 2026`
84
+ */
85
+ export function formatDayFromKey(key) {
86
+ const [year, month, day] = key.split('-').map(Number);
87
+ return `${MONTHS[month - 1]} ${day}, ${year}`;
88
+ }
89
+ /**
90
+ * Formats an instant as the `Generated on` footer text.
91
+ *
92
+ * @param ms - epoch milliseconds
93
+ * @param timeZone - IANA zone; defaults to the system zone
94
+ * @returns footer timestamp such as `Nov 19, 2026 at 12:30 PM`
95
+ */
96
+ export function formatGeneratedAt(ms, timeZone) {
97
+ const p = partsOf(ms, timeZone);
98
+ const meridiem = p.hour < 12 ? 'AM' : 'PM';
99
+ const h12 = p.hour % 12 === 0 ? 12 : p.hour % 12;
100
+ return `${MONTHS[p.month - 1]} ${p.day}, ${p.year} at ${h12}:${pad2(p.minute)} ${meridiem}`;
101
+ }