soltask 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,2 @@
1
+ import type { CommandSpec } from "../context.js";
2
+ export declare const watchCommands: readonly CommandSpec[];
@@ -0,0 +1,397 @@
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+ import { REASONS } from "../domain.js";
3
+ import { CliError, EXIT_AUTH, EXIT_OK, EXIT_VALIDATION, EXIT_WATCH_STOPPED } from "../errors.js";
4
+ import { displayText, emitJsonLine, errOut, formatTimestamp, out } from "../output.js";
5
+ import { splitCsvList, utcNowIso } from "../util.js";
6
+ import { parseColumnFilter, resolveTaskAcrossCommunities } from "./read.js";
7
+ const ALL_COLUMNS = ["backlog", "queued", "working", "needs", "shipping", "done", "canceled"];
8
+ const COLUMN_SET = new Set(ALL_COLUMNS);
9
+ const REASON_SET = new Set(Object.keys(REASONS));
10
+ const INITIAL_BACKOFF_MS = 200;
11
+ const MAX_BACKOFF_MS = 2_000;
12
+ function parseUntilConditions(rawItems) {
13
+ const tokens = splitCsvList(rawItems);
14
+ const matchers = [];
15
+ let allowsCanceled = false;
16
+ for (const raw of tokens) {
17
+ const colon = raw.indexOf(":");
18
+ if (colon !== -1) {
19
+ const prefix = raw.slice(0, colon).trim().toLowerCase();
20
+ const value = raw.slice(colon + 1).trim();
21
+ if (prefix === "col") {
22
+ const lower = value.toLowerCase();
23
+ if (!COLUMN_SET.has(lower)) {
24
+ throw new CliError(`Invalid --until column '${value}'. Valid columns: ${ALL_COLUMNS.join(", ")}.`, {
25
+ exitCode: EXIT_VALIDATION,
26
+ });
27
+ }
28
+ const col = lower;
29
+ if (col === "canceled") {
30
+ allowsCanceled = true;
31
+ }
32
+ matchers.push({ kind: "col", col });
33
+ continue;
34
+ }
35
+ if (prefix === "reason") {
36
+ const lower = value.toLowerCase();
37
+ if (!REASON_SET.has(lower)) {
38
+ throw new CliError(`Invalid --until reason '${value}'. Valid reasons: ${Object.keys(REASONS).join(", ")}.`, { exitCode: EXIT_VALIDATION });
39
+ }
40
+ matchers.push({ kind: "reason", reason: lower });
41
+ continue;
42
+ }
43
+ if (prefix === "stage") {
44
+ if (value === "") {
45
+ throw new CliError("--until stage:<id> requires a non-empty stage ID.", { exitCode: EXIT_VALIDATION });
46
+ }
47
+ matchers.push({ kind: "stage", stage: value });
48
+ continue;
49
+ }
50
+ throw new CliError(`Invalid --until condition '${raw}'. Use col:<name>, reason:<type>, stage:<id>, for-me, or a column/reason name.`, { exitCode: EXIT_VALIDATION });
51
+ }
52
+ const lower = raw.toLowerCase();
53
+ if (lower === "for-me") {
54
+ matchers.push({ kind: "for-me" });
55
+ }
56
+ else if (COLUMN_SET.has(lower)) {
57
+ const col = lower;
58
+ if (col === "canceled") {
59
+ allowsCanceled = true;
60
+ }
61
+ matchers.push({ kind: "col", col });
62
+ }
63
+ else if (REASON_SET.has(lower)) {
64
+ matchers.push({ kind: "reason", reason: lower });
65
+ }
66
+ else {
67
+ throw new CliError(`Invalid --until condition '${raw}'. Valid tokens: ${[...ALL_COLUMNS, ...Object.keys(REASONS), "for-me", "stage:<id>"].join(", ")}.`, { exitCode: EXIT_VALIDATION });
68
+ }
69
+ }
70
+ return { matchers, allowsCanceled };
71
+ }
72
+ function parseTimeoutSeconds(raw) {
73
+ if (raw === undefined) {
74
+ return null;
75
+ }
76
+ const trimmed = raw.trim();
77
+ const seconds = Number(trimmed);
78
+ if (trimmed === "" || !Number.isFinite(seconds) || seconds <= 0) {
79
+ throw new CliError("--timeout must be a positive number of seconds.", { exitCode: EXIT_VALIDATION });
80
+ }
81
+ return { seconds, ms: Math.max(1, Math.round(seconds * 1000)) };
82
+ }
83
+ function matchesUntil(task, matchers) {
84
+ return matchers.some((matcher) => {
85
+ switch (matcher.kind) {
86
+ case "col":
87
+ return task.col === matcher.col;
88
+ case "reason":
89
+ return task.reason?.type === matcher.reason;
90
+ case "for-me":
91
+ return task.forMe;
92
+ case "stage":
93
+ return task.stage === matcher.stage;
94
+ }
95
+ });
96
+ }
97
+ function emitTaskUpdate(task, jsonl) {
98
+ if (jsonl) {
99
+ emitJsonLine({
100
+ event: "task",
101
+ community: task.community,
102
+ root: task.root,
103
+ key: task.key,
104
+ col: task.col,
105
+ stage: task.stage,
106
+ stageLabel: task.stageLabel,
107
+ reason: task.reason ?? null,
108
+ forMe: task.forMe,
109
+ title: task.title,
110
+ version: task.version,
111
+ });
112
+ return;
113
+ }
114
+ const stagePart = task.stage !== null ? `/${displayText(task.stage)}` : "";
115
+ const reasonPart = task.reason !== undefined ? ` (${task.reason.type}: ${displayText(task.reason.label)})` : "";
116
+ out(`[${formatTimestamp(task.last)}] ${displayText(task.key)} [${task.col}${stagePart}] ${displayText(task.title)}${reasonPart}`);
117
+ }
118
+ function emitCanceledStop(task, jsonl) {
119
+ if (jsonl) {
120
+ emitJsonLine({
121
+ ok: false,
122
+ event: "stopped",
123
+ error: "task_canceled",
124
+ key: task.key,
125
+ community: task.community,
126
+ root: task.root,
127
+ col: task.col,
128
+ });
129
+ }
130
+ else {
131
+ errOut(`Watch stopped: ${displayText(task.key)} was canceled.`);
132
+ }
133
+ }
134
+ function isRetryableWatchError(err) {
135
+ if (err instanceof CliError) {
136
+ if (err.exitCode === EXIT_AUTH || err.payload["error"] === "redirect_refused") {
137
+ return false;
138
+ }
139
+ return err.retryable;
140
+ }
141
+ return false;
142
+ }
143
+ function defaultSleep(ms, signal) {
144
+ return sleep(ms, undefined, { signal });
145
+ }
146
+ /** `watch [TASK_REF] [--until CONDITIONS] [--col COLS] [--timeout SEC] [--jsonl]` */
147
+ async function cmdWatch(ctx) {
148
+ const { matchers: untilMatchers, allowsCanceled } = parseUntilConditions(ctx.optList("until"));
149
+ const { cols: colFilter } = parseColumnFilter(ctx.optList("col"));
150
+ const timeout = parseTimeoutSeconds(ctx.opt("timeout"));
151
+ const jsonl = ctx.flag("jsonl") || ctx.global.json;
152
+ const includeTyping = ctx.flag("include-typing");
153
+ const sleepFn = ctx.io.sleepFn ?? defaultSleep;
154
+ const client = ctx.client();
155
+ const configuredCommunity = ctx.community();
156
+ const taskRef = ctx.positionals[0];
157
+ let target = null;
158
+ if (taskRef !== undefined) {
159
+ const resolved = await resolveTaskAcrossCommunities(ctx, taskRef);
160
+ target = { community: resolved.task.community, root: resolved.task.root, key: resolved.task.key };
161
+ const detail = await client.request("GET", `/api/tasks/${encodeURIComponent(target.community)}/${encodeURIComponent(target.root)}`);
162
+ const current = detail.body.task;
163
+ if (untilMatchers.length > 0) {
164
+ if (matchesUntil(current, untilMatchers)) {
165
+ emitTaskUpdate(current, jsonl);
166
+ return EXIT_OK;
167
+ }
168
+ if (!allowsCanceled && current.col === "canceled") {
169
+ emitTaskUpdate(current, jsonl);
170
+ emitCanceledStop(current, jsonl);
171
+ return EXIT_WATCH_STOPPED;
172
+ }
173
+ }
174
+ }
175
+ else if (ctx.global.waitLive) {
176
+ await client.waitUntilLive(configuredCommunity !== undefined ? [configuredCommunity] : undefined);
177
+ }
178
+ const communityFilter = target?.community ?? configuredCommunity;
179
+ const controller = new AbortController();
180
+ const stop = {
181
+ reason: null,
182
+ signal: null,
183
+ };
184
+ const onSignal = (sig) => {
185
+ if (stop.reason === null) {
186
+ stop.reason = "signal";
187
+ stop.signal = sig;
188
+ controller.abort(new Error(sig));
189
+ }
190
+ };
191
+ process.on("SIGINT", onSignal);
192
+ process.on("SIGTERM", onSignal);
193
+ let timer;
194
+ if (timeout !== null) {
195
+ timer = setTimeout(() => {
196
+ if (stop.reason === null) {
197
+ stop.reason = "timeout";
198
+ controller.abort(new Error("timeout"));
199
+ }
200
+ }, timeout.ms);
201
+ }
202
+ const isAborted = () => controller.signal.aborted;
203
+ let backoffMs = INITIAL_BACKOFF_MS;
204
+ try {
205
+ while (!isAborted()) {
206
+ let nextDelayMs = backoffMs;
207
+ try {
208
+ for await (const ev of client.streamEvents({ signal: controller.signal })) {
209
+ if (isAborted()) {
210
+ break;
211
+ }
212
+ backoffMs = INITIAL_BACKOFF_MS;
213
+ switch (ev.event) {
214
+ case "status": {
215
+ if (communityFilter !== undefined && ev.data.community !== communityFilter) {
216
+ break;
217
+ }
218
+ const now = new Date();
219
+ if (jsonl) {
220
+ emitJsonLine({
221
+ event: "status",
222
+ community: ev.data.community,
223
+ state: ev.data.state,
224
+ degradedSince: ev.data.degradedSince,
225
+ at: utcNowIso(now),
226
+ });
227
+ }
228
+ else {
229
+ out(`[${formatTimestamp(Math.floor(now.getTime() / 1000))}] status ${displayText(ev.data.community)}: ${ev.data.state}`);
230
+ }
231
+ break;
232
+ }
233
+ case "typing": {
234
+ if (!includeTyping) {
235
+ break;
236
+ }
237
+ if (communityFilter !== undefined && ev.data.community !== communityFilter) {
238
+ break;
239
+ }
240
+ if (target !== null && ev.data.root !== target.root) {
241
+ break;
242
+ }
243
+ const now = new Date();
244
+ if (jsonl) {
245
+ emitJsonLine({
246
+ event: "typing",
247
+ community: ev.data.community,
248
+ channel: ev.data.channel,
249
+ root: ev.data.root,
250
+ pubkey: ev.data.pubkey,
251
+ at: utcNowIso(now),
252
+ });
253
+ }
254
+ else {
255
+ out(`[${formatTimestamp(Math.floor(now.getTime() / 1000))}] typing ${displayText(ev.data.community)} ${displayText(ev.data.pubkey.slice(0, 8))} in ${displayText(ev.data.channel)}`);
256
+ }
257
+ break;
258
+ }
259
+ case "task": {
260
+ if (target !== null) {
261
+ if (ev.data.community !== target.community || ev.data.root !== target.root) {
262
+ break;
263
+ }
264
+ }
265
+ else if (communityFilter !== undefined && ev.data.community !== communityFilter) {
266
+ break;
267
+ }
268
+ const detail = await client.request("GET", `/api/tasks/${encodeURIComponent(ev.data.community)}/${encodeURIComponent(ev.data.root)}`, { signal: controller.signal });
269
+ const task = detail.body.task;
270
+ const shouldDisplay = colFilter === null || colFilter.has(task.col);
271
+ if (shouldDisplay) {
272
+ emitTaskUpdate(task, jsonl);
273
+ }
274
+ if (untilMatchers.length > 0) {
275
+ if (matchesUntil(task, untilMatchers)) {
276
+ if (!shouldDisplay) {
277
+ emitTaskUpdate(task, jsonl);
278
+ }
279
+ return EXIT_OK;
280
+ }
281
+ if (target !== null && task.col === "canceled" && !allowsCanceled) {
282
+ if (!shouldDisplay) {
283
+ emitTaskUpdate(task, jsonl);
284
+ }
285
+ emitCanceledStop(task, jsonl);
286
+ return EXIT_WATCH_STOPPED;
287
+ }
288
+ }
289
+ break;
290
+ }
291
+ }
292
+ }
293
+ }
294
+ catch (err) {
295
+ if (isAborted()) {
296
+ break;
297
+ }
298
+ if (!isRetryableWatchError(err)) {
299
+ throw err;
300
+ }
301
+ if (err instanceof CliError && err.retryAfter !== null && err.retryAfter > 0) {
302
+ nextDelayMs = Math.min(MAX_BACKOFF_MS, err.retryAfter * 1000);
303
+ }
304
+ }
305
+ if (isAborted()) {
306
+ break;
307
+ }
308
+ try {
309
+ await sleepFn(nextDelayMs, controller.signal);
310
+ }
311
+ catch {
312
+ if (isAborted()) {
313
+ break;
314
+ }
315
+ }
316
+ backoffMs = Math.min(MAX_BACKOFF_MS, backoffMs * 2);
317
+ }
318
+ }
319
+ finally {
320
+ if (timer !== undefined) {
321
+ clearTimeout(timer);
322
+ }
323
+ process.off("SIGINT", onSignal);
324
+ process.off("SIGTERM", onSignal);
325
+ }
326
+ if (stop.reason === "timeout") {
327
+ if (untilMatchers.length > 0) {
328
+ const secs = timeout?.seconds ?? 0;
329
+ const msg = `Watch timed out after ${secs}s before condition matched.`;
330
+ if (jsonl) {
331
+ emitJsonLine({
332
+ ok: false,
333
+ event: "timeout",
334
+ error: "watch_timeout",
335
+ message: msg,
336
+ ...(target !== null ? { key: target.key, community: target.community, root: target.root } : {}),
337
+ });
338
+ }
339
+ else {
340
+ errOut(msg);
341
+ }
342
+ return EXIT_WATCH_STOPPED;
343
+ }
344
+ return EXIT_OK;
345
+ }
346
+ if (stop.reason === "signal") {
347
+ if (jsonl) {
348
+ emitJsonLine({
349
+ ok: false,
350
+ event: "stopped",
351
+ error: "interrupted",
352
+ signal: stop.signal,
353
+ });
354
+ }
355
+ else {
356
+ errOut(`Watch stopped (${stop.signal ?? "interrupted"}).`);
357
+ }
358
+ return EXIT_WATCH_STOPPED;
359
+ }
360
+ return EXIT_OK;
361
+ }
362
+ export const watchCommands = [
363
+ {
364
+ name: "watch",
365
+ summary: "Stream realtime SSE task board updates and optionally wait for a condition",
366
+ usage: "watch [TASK_REF] [--until CONDITIONS] [--col COLS] [--timeout SEC] [--jsonl]",
367
+ options: {
368
+ until: {
369
+ type: "string",
370
+ multiple: true,
371
+ placeholder: "CONDITIONS",
372
+ description: "Exit 0 when a matching column, reason, for-me, or stage:<id> is reached",
373
+ },
374
+ col: {
375
+ type: "string",
376
+ multiple: true,
377
+ placeholder: "COLS",
378
+ description: "Filter displayed task updates by column (backlog..canceled, open)",
379
+ },
380
+ timeout: {
381
+ type: "string",
382
+ placeholder: "SEC",
383
+ description: "Stop watching after SEC seconds",
384
+ },
385
+ jsonl: {
386
+ type: "boolean",
387
+ description: "Emit newline-delimited JSON events",
388
+ },
389
+ "include-typing": {
390
+ type: "boolean",
391
+ description: "Include noisy typing indicator events in output",
392
+ },
393
+ },
394
+ positionals: { min: 0, max: 1 },
395
+ handler: cmdWatch,
396
+ },
397
+ ];
@@ -0,0 +1,86 @@
1
+ import { type JsonObject } from "./util.js";
2
+ export declare const ENV_SERVER = "SOLTASK_SERVER";
3
+ export declare const ENV_CONFIG = "SOLTASK_CONFIG";
4
+ export declare const ENV_COOKIE = "SOLTASK_COOKIE";
5
+ export declare const ENV_UNLOCK_KEY = "SOLTASK_UNLOCK_KEY";
6
+ export declare const ENV_TOKEN = "SOLTASK_TOKEN";
7
+ export declare const ENV_NSEC = "SOLTASK_NSEC";
8
+ export declare const ENV_COMMUNITY = "SOLTASK_COMMUNITY";
9
+ export declare const LOOPBACK_HOSTS: ReadonlySet<string>;
10
+ /** Config keys that belong to one login session; dropped together on logout. */
11
+ export declare const SESSION_CONFIG_KEYS: readonly ["cookie_name", "cookie_value", "unlock", "token", "pubkey", "profile", "communities", "saved_at"];
12
+ export type ServerOrigin = readonly [scheme: string, host: string, port: number];
13
+ export interface CookieSessionAuth {
14
+ mode: "cookie";
15
+ source: "env" | "config";
16
+ cookieName: string;
17
+ cookieValue: string;
18
+ unlock: string;
19
+ }
20
+ export interface BearerSessionAuth {
21
+ mode: "bearer";
22
+ source: "env" | "config";
23
+ token: string;
24
+ }
25
+ export type SessionAuth = CookieSessionAuth | BearerSessionAuth;
26
+ /**
27
+ * Validates and normalizes a server base URL: http(s) only, no credentials, query, or fragment.
28
+ * A deliberate base path survives (`https://board.example.com/sub/` becomes `https://board.example.com/sub`);
29
+ * the trailing slash does not.
30
+ */
31
+ export declare function normalizeServerUrl(raw: string | null | undefined): string;
32
+ /** `[scheme, hostname, port]` with the default port filled in, for exact origin comparison; null when not an http(s) URL. */
33
+ export declare function serverOrigin(url: string): ServerOrigin | null;
34
+ export declare function sameServerOrigin(a: string, b: string): boolean;
35
+ /** True for plain `http:` to anything but loopback: credentials would cross the network in cleartext. */
36
+ export declare function isNonLoopbackHttp(url: string): boolean;
37
+ export interface PathContext {
38
+ env?: NodeJS.ProcessEnv;
39
+ platform?: NodeJS.Platform;
40
+ home?: string;
41
+ }
42
+ /** `--config`, then `SOLTASK_CONFIG`, then `$XDG_CONFIG_HOME/soltask/config.json` (`%APPDATA%\soltask\config.json` on Windows). */
43
+ export declare function resolveConfigPath(cliConfig?: string | null, context?: PathContext): string;
44
+ /** Reads the config file; a missing file is an empty config, a symbolic link or a non-object is refused. */
45
+ export declare function loadConfig(path: string): JsonObject;
46
+ /** Writes the config atomically with mode 0600 in a 0700 directory. Secret keys (`nsec`, `password`) are never persisted. */
47
+ export declare function saveConfig(path: string, data: Readonly<JsonObject>): void;
48
+ /** The config minus the keys of a login session. */
49
+ export declare function withoutSessionFields(cfg: Readonly<JsonObject>): {
50
+ config: JsonObject;
51
+ removed: boolean;
52
+ };
53
+ export interface ConfigFileCheck {
54
+ exists: boolean;
55
+ ok: boolean;
56
+ detail: string;
57
+ /** Why it is not ok: `permissions` can be fixed with chmod, `unsafe` (a link, a directory, an unreadable path) cannot. */
58
+ problem?: "permissions" | "unsafe";
59
+ }
60
+ /** Looks at the config file's type and permissions without reading it. */
61
+ export declare function inspectConfigFile(path: string, platform?: NodeJS.Platform): ConfigFileCheck;
62
+ /** A sentence to show when the config file deserves attention, or null when there is nothing to say. */
63
+ export declare function configPermWarning(path: string, platform?: NodeJS.Platform): string | null;
64
+ /** `--server`, then `SOLTASK_SERVER`, then the saved server, normalized. */
65
+ export declare function resolveServer(flagServer: string | undefined, cfg: Readonly<JsonObject>, env?: NodeJS.ProcessEnv): string;
66
+ /** `--community`, then `SOLTASK_COMMUNITY`, then saved default `community` in config. */
67
+ export declare function resolveCommunity(flagCommunity: string | undefined, cfg: Readonly<JsonObject>, env?: NodeJS.ProcessEnv): string | undefined;
68
+ /** Parses a `name=value` cookie string (stripping any trailing attributes after `;`), or returns null when invalid. */
69
+ export declare function parseCookiePair(raw: string): {
70
+ name: string;
71
+ value: string;
72
+ } | null;
73
+ /** True when any session credential env var (`SOLTASK_COOKIE`, `SOLTASK_UNLOCK_KEY`, `SOLTASK_TOKEN`) is set. */
74
+ export declare function hasEnvCredentials(env?: NodeJS.ProcessEnv): boolean;
75
+ /** True when the saved config holds session credentials (cookie+unlock or token). */
76
+ export declare function hasSavedCredentials(cfg: Readonly<JsonObject>): boolean;
77
+ /**
78
+ * Resolves authentication credentials for `serverUrl`.
79
+ *
80
+ * Precedence:
81
+ * 1. `SOLTASK_COOKIE` (`name=value`) + `SOLTASK_UNLOCK_KEY` from the environment (not origin-bound).
82
+ * 2. `SOLTASK_TOKEN` from the environment (optional Bearer mode, not origin-bound).
83
+ * 3. Saved session in `cfg` (`cookie_name` + `cookie_value` + `unlock`, or saved `token`),
84
+ * strictly origin-bound so saved credentials are NEVER sent to a different `--server` origin.
85
+ */
86
+ export declare function resolveSession(cfg: Readonly<JsonObject>, serverUrl: string, env?: NodeJS.ProcessEnv): SessionAuth | null;