@tasqmate/sdk 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,894 @@
1
+ // src/prefixes.ts
2
+ var AGENT_KEY_PREFIX = "tq_ag_";
3
+ var USER_TOKEN_PREFIX = "tq_us_";
4
+
5
+ // src/files.ts
6
+ var TYPES = new Map(Object.entries({
7
+ avif: "image/avif",
8
+ csv: "text/csv",
9
+ doc: "application/msword",
10
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
11
+ gif: "image/gif",
12
+ gz: "application/gzip",
13
+ heic: "image/heic",
14
+ htm: "text/html",
15
+ html: "text/html",
16
+ jpeg: "image/jpeg",
17
+ jpg: "image/jpeg",
18
+ json: "application/json",
19
+ key: "application/vnd.apple.keynote",
20
+ log: "text/plain",
21
+ md: "text/markdown",
22
+ mov: "video/quicktime",
23
+ mp3: "audio/mpeg",
24
+ mp4: "video/mp4",
25
+ pdf: "application/pdf",
26
+ png: "image/png",
27
+ ppt: "application/vnd.ms-powerpoint",
28
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
29
+ svg: "image/svg+xml",
30
+ tar: "application/x-tar",
31
+ tsv: "text/tab-separated-values",
32
+ txt: "text/plain",
33
+ wav: "audio/wav",
34
+ webm: "video/webm",
35
+ webp: "image/webp",
36
+ xls: "application/vnd.ms-excel",
37
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
38
+ yaml: "application/yaml",
39
+ yml: "application/yaml",
40
+ zip: "application/zip"
41
+ }));
42
+ function contentTypeFor(fileName) {
43
+ const dot = fileName.lastIndexOf(".");
44
+ const extension = dot === -1 ? "" : fileName.slice(dot + 1).toLowerCase();
45
+ return TYPES.get(extension) ?? "application/octet-stream";
46
+ }
47
+ function formatFileSize(bytes) {
48
+ if (bytes < 1024) return `${bytes} B`;
49
+ const units = ["KB", "MB", "GB"];
50
+ let value = bytes / 1024;
51
+ let unit = 0;
52
+ while (value >= 1024 && unit < units.length - 1) {
53
+ value /= 1024;
54
+ unit += 1;
55
+ }
56
+ const rounded = value >= 10 ? Math.round(value) : Math.round(value * 10) / 10;
57
+ return `${rounded} ${units[unit]}`;
58
+ }
59
+ var PREVIEWABLE_IMAGE_TYPES = /* @__PURE__ */ new Set([
60
+ "image/png",
61
+ "image/jpeg",
62
+ "image/gif",
63
+ "image/webp",
64
+ "image/avif"
65
+ ]);
66
+ function isPreviewableImage(contentType) {
67
+ return PREVIEWABLE_IMAGE_TYPES.has(contentType.toLowerCase());
68
+ }
69
+ function escapeLinkText(text) {
70
+ return text.replace(/[\\[\]]/g, (char) => `\\${char}`);
71
+ }
72
+ function fileMarkdown(file, layout = {}) {
73
+ const href = `tasq:file/${file.id}`;
74
+ if (!isPreviewableImage(file.contentType)) {
75
+ return `[${escapeLinkText(file.fileName)}](${href})`;
76
+ }
77
+ const size = layout.size ?? "full";
78
+ const align = layout.align ?? "center";
79
+ const title = size === "full" && align === "center" ? "" : ` "${size} ${align}"`;
80
+ return `![${escapeLinkText(layout.caption ?? "")}](${href}${title})`;
81
+ }
82
+
83
+ // src/errors.ts
84
+ var TasqmateApiError = class extends Error {
85
+ code;
86
+ status;
87
+ details;
88
+ constructor(status, body) {
89
+ super(body.message);
90
+ this.name = "TasqmateApiError";
91
+ this.code = body.code;
92
+ this.status = status;
93
+ this.details = body.details;
94
+ }
95
+ };
96
+ var TasqmateRateLimitError = class extends TasqmateApiError {
97
+ retryAfterSeconds;
98
+ resetAt;
99
+ limit;
100
+ remaining;
101
+ constructor(status, body, retryAfterHeader) {
102
+ super(status, body);
103
+ this.name = "TasqmateRateLimitError";
104
+ const details = body.details ?? {};
105
+ this.limit = details.limit;
106
+ this.remaining = details.remaining;
107
+ this.resetAt = details.resetAt === void 0 ? void 0 : new Date(details.resetAt);
108
+ const fromHeader = Number(retryAfterHeader);
109
+ if (retryAfterHeader !== null && Number.isFinite(fromHeader)) {
110
+ this.retryAfterSeconds = Math.max(0, fromHeader);
111
+ } else if (this.resetAt !== void 0) {
112
+ const ms = this.resetAt.getTime() - Date.now();
113
+ this.retryAfterSeconds = Math.max(0, Math.ceil(ms / 1e3));
114
+ } else {
115
+ this.retryAfterSeconds = 0;
116
+ }
117
+ }
118
+ };
119
+ var TasqmateValidationError = class extends TasqmateApiError {
120
+ issues;
121
+ constructor(status, body) {
122
+ super(status, body);
123
+ this.name = "TasqmateValidationError";
124
+ this.issues = Array.isArray(body.details) ? body.details : [];
125
+ }
126
+ };
127
+ var TasqmatePolicyDeniedError = class extends TasqmateApiError {
128
+ /** The rejected action name, when the API reported one. */
129
+ action;
130
+ /** The policy version quoted in the message, when the API quoted one. */
131
+ policyVersion;
132
+ constructor(status, body) {
133
+ super(status, body);
134
+ this.name = "TasqmatePolicyDeniedError";
135
+ this.action = actionFromDetails(body.details);
136
+ this.policyVersion = policyVersionFromMessage(body.message);
137
+ }
138
+ };
139
+ function actionFromDetails(details) {
140
+ if (!Array.isArray(details)) return void 0;
141
+ const issues = details;
142
+ for (const issue of issues) {
143
+ if (issue.path[0] === "action") return issue.message;
144
+ }
145
+ return void 0;
146
+ }
147
+ function policyVersionFromMessage(message) {
148
+ const match = /policy v(?:ersion )?(\d+)/i.exec(message);
149
+ if (!match?.[1]) return void 0;
150
+ return Number(match[1]);
151
+ }
152
+ function noCredentialError() {
153
+ return new TasqmateApiError(0, {
154
+ code: "NO_CREDENTIAL",
155
+ message: "No credential configured. Run `tasqmate auth login`, or set TASQMATE_API_KEY."
156
+ });
157
+ }
158
+ function toTasqmateError(status, body, retryAfterHeader) {
159
+ if (status === 429 || body.code === "RATE_LIMITED") {
160
+ return new TasqmateRateLimitError(status, body, retryAfterHeader);
161
+ }
162
+ if (body.code === "VALIDATION_ERROR") {
163
+ return new TasqmateValidationError(status, body);
164
+ }
165
+ if (body.code === "AGENT_ACTION_DENIED") {
166
+ return new TasqmatePolicyDeniedError(status, body);
167
+ }
168
+ return new TasqmateApiError(status, body);
169
+ }
170
+
171
+ // src/client.ts
172
+ var PROJECT_UPDATES_PAGE_MAX = 100;
173
+ function assertPrefix(token, prefix, label) {
174
+ if (!token.startsWith(prefix)) {
175
+ throw new Error(
176
+ `Invalid ${label}: expected a token starting with "${prefix}".`
177
+ );
178
+ }
179
+ }
180
+ function credential(auth) {
181
+ if (auth === void 0) return void 0;
182
+ if ("agentKey" in auth) {
183
+ assertPrefix(auth.agentKey, AGENT_KEY_PREFIX, "agent key");
184
+ return auth.agentKey;
185
+ }
186
+ assertPrefix(auth.userToken, USER_TOKEN_PREFIX, "user token");
187
+ return auth.userToken;
188
+ }
189
+ function normaliseBaseUrl(baseUrl) {
190
+ return `${baseUrl.replace(/\/+$/, "")}/api`;
191
+ }
192
+ function queryString(params) {
193
+ if (!params) return "";
194
+ const search = new URLSearchParams();
195
+ for (const [key, value] of Object.entries(params)) {
196
+ if (value === void 0) continue;
197
+ search.set(key, String(value));
198
+ }
199
+ const encoded = search.toString();
200
+ return encoded === "" ? "" : `?${encoded}`;
201
+ }
202
+ var TasqmateClient = class _TasqmateClient {
203
+ #baseUrl;
204
+ #token;
205
+ #fetch;
206
+ /** A client with no credential, for the two anonymous auth calls. */
207
+ static anonymous(baseUrl, fetchImpl) {
208
+ return new _TasqmateClient({ baseUrl, fetch: fetchImpl });
209
+ }
210
+ constructor(options) {
211
+ this.#baseUrl = normaliseBaseUrl(options.baseUrl);
212
+ this.#token = credential(options.auth);
213
+ this.#fetch = options.fetch ?? globalThis.fetch;
214
+ }
215
+ async #request(path, init = {}) {
216
+ const { anonymous = false, timeoutMs, ...requestInit } = init;
217
+ const headers = new Headers(requestInit.headers);
218
+ if (!anonymous) {
219
+ if (this.#token === void 0) throw noCredentialError();
220
+ headers.set("authorization", `Bearer ${this.#token}`);
221
+ }
222
+ if (requestInit.body !== void 0 && !headers.has("content-type")) {
223
+ headers.set("content-type", "application/json");
224
+ }
225
+ headers.set("accept", "application/json");
226
+ const timeout = timeoutMs === void 0 ? void 0 : AbortSignal.timeout(timeoutMs);
227
+ const signals = [requestInit.signal, timeout].filter(
228
+ (candidate) => candidate != null
229
+ );
230
+ const signal = signals.length === 0 ? void 0 : signals.length === 1 ? signals[0] : AbortSignal.any(signals);
231
+ const response = await this.#fetch(`${this.#baseUrl}${path}`, {
232
+ ...requestInit,
233
+ headers,
234
+ signal
235
+ });
236
+ if (!response.ok) {
237
+ throw await this.#toError(response);
238
+ }
239
+ return await response.json();
240
+ }
241
+ /**
242
+ * A read whose body is Markdown rather than JSON.
243
+ *
244
+ * The export and the `format=markdown` context are documents, not
245
+ * envelopes, so they are read as text. Errors still arrive as the JSON
246
+ * envelope every other route uses, so the failure path is `#toError`'s,
247
+ * unchanged.
248
+ */
249
+ async #text(path, params, options) {
250
+ const headers = new Headers({ accept: "text/markdown" });
251
+ if (this.#token === void 0) throw noCredentialError();
252
+ headers.set("authorization", `Bearer ${this.#token}`);
253
+ const timeout = options?.timeoutMs === void 0 ? void 0 : AbortSignal.timeout(options.timeoutMs);
254
+ const signals = [options?.signal, timeout].filter(
255
+ (candidate) => candidate != null
256
+ );
257
+ const signal = signals.length === 0 ? void 0 : signals.length === 1 ? signals[0] : AbortSignal.any(signals);
258
+ const response = await this.#fetch(
259
+ `${this.#baseUrl}${path}${queryString(params)}`,
260
+ { headers, signal }
261
+ );
262
+ if (!response.ok) throw await this.#toError(response);
263
+ return await response.text();
264
+ }
265
+ async #toError(response) {
266
+ const retryAfter = response.headers.get("retry-after");
267
+ const fallback = {
268
+ code: `HTTP_${response.status}`,
269
+ message: `Request failed with status ${response.status}`
270
+ };
271
+ const envelope = await response.json().catch(() => null);
272
+ const error = envelope?.error;
273
+ const body = error?.code === void 0 ? fallback : {
274
+ code: error.code,
275
+ message: error.message ?? fallback.message,
276
+ details: error.details
277
+ };
278
+ return toTasqmateError(response.status, body, retryAfter);
279
+ }
280
+ #get(path, params, options) {
281
+ return this.#request(`${path}${queryString(params)}`, options);
282
+ }
283
+ workspaces = {
284
+ list: async () => (await this.#get("/workspaces")).workspaces,
285
+ get: async (slug) => (await this.#get(
286
+ `/workspaces/${encodeURIComponent(slug)}`
287
+ )).workspace
288
+ };
289
+ tasks = {
290
+ list: async (slug, filters) => (await this.#get(
291
+ `/workspaces/${encodeURIComponent(slug)}/tasks`,
292
+ filters
293
+ )).tasks,
294
+ get: async (slug, taskId) => (await this.#get(
295
+ `/workspaces/${encodeURIComponent(slug)}/tasks/${encodeURIComponent(taskId)}`
296
+ )).task,
297
+ /**
298
+ * Ask a person to sign off on a task (6.3). Asking again while a
299
+ * request stands replaces the approver. The approver cannot be an agent.
300
+ */
301
+ requestApproval: (slug, taskId, approverId) => this.dispatch("task.requestApproval", slug, { taskId, approverId }),
302
+ /**
303
+ * The approver's answer (6.3). `approve` also moves the task to the next
304
+ * status in its team's category order. Person credentials only: no
305
+ * agent policy can include it.
306
+ */
307
+ decide: (slug, taskId, decision) => this.dispatch("task.decide", slug, { taskId, decision })
308
+ };
309
+ /**
310
+ * Time tracking: whole minutes on a task for a day, no running timer.
311
+ * Everything here is member-level; a guest credential is refused. Turn a
312
+ * typed duration into minutes with `parseDuration`.
313
+ */
314
+ time = {
315
+ /** A task's entries, newest day first, and its total with direct subtasks. */
316
+ forTask: (slug, taskId) => this.#get(
317
+ `/workspaces/${encodeURIComponent(slug)}/tasks/${encodeURIComponent(taskId)}/time`
318
+ ),
319
+ /**
320
+ * Time on a project's tasks between two inclusive `YYYY-MM-DD` days, by
321
+ * person and day. The API reads at most 92 days at a time.
322
+ */
323
+ forProject: (slug, projectId, range) => this.#get(
324
+ `/workspaces/${encodeURIComponent(slug)}/projects/${encodeURIComponent(projectId)}/time`,
325
+ { from: range.from, to: range.to }
326
+ ),
327
+ /**
328
+ * Log minutes on a task for a day. `memberId` defaults to the caller;
329
+ * logging for someone else is an admin's job.
330
+ */
331
+ log: (slug, input) => this.dispatch("time.log", slug, input),
332
+ /** Change an entry; omitted fields are left alone, `note: null` clears it. */
333
+ update: (slug, input) => this.dispatch("time.update", slug, input),
334
+ delete: (slug, input) => this.dispatch("time.delete", slug, input)
335
+ };
336
+ /**
337
+ * Clients (initiatives) and their hours. Member-only; refused unless a team
338
+ * with a project for the client has Client hours on.
339
+ */
340
+ clients = {
341
+ /**
342
+ * One month of a client's hours by billable flag, project and person.
343
+ * `month` is `YYYY-MM`; `billableOnly` counts billable entries only.
344
+ */
345
+ hours: (slug, clientId, month, options = {}) => this.#get(
346
+ `/workspaces/${encodeURIComponent(slug)}/clients/${encodeURIComponent(clientId)}/hours`,
347
+ { month, billable: options.billableOnly ? "billable" : "all" }
348
+ ),
349
+ /** A client's billing months, newest first, with each one's hours and state. */
350
+ billing: (slug, clientId) => this.#get(
351
+ `/workspaces/${encodeURIComponent(slug)}/clients/${encodeURIComponent(clientId)}/billing`
352
+ )
353
+ };
354
+ /** The caller's own time (TM-2, My week). */
355
+ me = {
356
+ /**
357
+ * The caller's Monday-to-Sunday week around `day` (`YYYY-MM-DD`), that
358
+ * day's entries, and tasks they worked on that day with no time logged.
359
+ * `tz` is the IANA zone that decides which edits fall on the day.
360
+ */
361
+ week: (slug, day, options = {}) => this.#get(
362
+ `/workspaces/${encodeURIComponent(slug)}/me/week`,
363
+ options.tz ? { day, tz: options.tz } : { day }
364
+ )
365
+ };
366
+ /**
367
+ * Agent timesheet drafts (TM-2). The drafting agent reads a draft and the
368
+ * member's day and saves lines; the member requests, logs, dismisses or
369
+ * replies. Agent keys are refused the member's side by policy.
370
+ */
371
+ timeDrafts = {
372
+ get: async (slug, draftId) => (await this.#get(
373
+ `/workspaces/${encodeURIComponent(slug)}/time-drafts/${encodeURIComponent(draftId)}`
374
+ )).draft,
375
+ /** The member's week around `day`, read by the agent that drafts it. */
376
+ memberWeek: (slug, memberId, day) => this.#get(
377
+ `/workspaces/${encodeURIComponent(slug)}/members/${encodeURIComponent(memberId)}/week`,
378
+ { day }
379
+ ),
380
+ request: (slug, input) => this.dispatch("timeDraft.request", slug, input),
381
+ save: (slug, input) => this.dispatch("timeDraft.save", slug, input),
382
+ confirm: (slug, input) => this.dispatch("timeDraft.confirm", slug, input),
383
+ dismiss: (slug, input) => this.dispatch("timeDraft.dismiss", slug, input),
384
+ reply: (slug, input) => this.dispatch("timeDraft.reply", slug, input)
385
+ };
386
+ /** Close, invoice and reopen a client's month (admins only). */
387
+ billingPeriods = {
388
+ close: (slug, input) => this.dispatch("billingPeriod.close", slug, input),
389
+ markInvoiced: (slug, input) => this.dispatch("billingPeriod.markInvoiced", slug, input),
390
+ reopen: (slug, input) => this.dispatch("billingPeriod.reopen", slug, input)
391
+ };
392
+ projects = {
393
+ list: async (slug) => (await this.#get(
394
+ `/workspaces/${encodeURIComponent(slug)}/projects`
395
+ )).projects,
396
+ get: async (slug, projectId) => (await this.#get(
397
+ `/workspaces/${encodeURIComponent(slug)}/projects/${encodeURIComponent(projectId)}`
398
+ )).project,
399
+ /**
400
+ * Pin a project to the caller's own sidebar. People only: an agent
401
+ * key is refused by policy whatever its preset.
402
+ */
403
+ star: (slug, input) => this.dispatch("project.star", slug, input),
404
+ unstar: (slug, input) => this.dispatch("project.unstar", slug, input),
405
+ /**
406
+ * Share a project with a guest already in the workspace (6.2). Admins
407
+ * and the project lead only; an agent key is always refused.
408
+ */
409
+ grantGuest: (slug, input) => this.dispatch("project.grantGuest", slug, input),
410
+ setGuestAccess: (slug, input) => this.dispatch("project.setGuestAccess", slug, input),
411
+ revokeGuest: (slug, input) => this.dispatch("project.revokeGuest", slug, input)
412
+ };
413
+ /**
414
+ * Docs: plans, specs and notes linked to projects, teams and tasks. Read a
415
+ * body as `bodyMarkdown` and save it back as `bodyMarkdown`: mentions are
416
+ * `[ENG-12](tasq:task/<id>)` and `[Title](tasq:doc/<id>)` links, and a bare
417
+ * `@ENG-12` becomes a mention when it names a task the caller can see.
418
+ * Writes are member-level; an agent needs `doc.*` in its policy.
419
+ */
420
+ /**
421
+ * Files on tasks, docs and comments (ATT-1). The bytes never pass through
422
+ * the API: `upload` asks for a storage link, PUTs the bytes to it, then
423
+ * confirms. A task's files are on `tasks.get(...).attachments`, a
424
+ * comment's on its `attachments`.
425
+ */
426
+ attachments = {
427
+ /**
428
+ * Upload a file in one call: `attachment.begin`, the PUT, then
429
+ * `attachment.finish`. With `forComment`, the file is staged for the
430
+ * next `comment.add` that names it in `attachmentIds`. With `inline`,
431
+ * it is for the task's description or the doc's body (ATT-2): put
432
+ * `fileMarkdown(result.attachment)` in the body to show it there.
433
+ */
434
+ upload: async (slug, target, file, options) => {
435
+ const body = file.data instanceof Blob ? file.data : new Blob([file.data]);
436
+ const contentType = file.contentType ?? (file.data instanceof Blob && file.data.type !== "" ? file.data.type : contentTypeFor(file.fileName));
437
+ const begun = await this.dispatch("attachment.begin", slug, {
438
+ ...target,
439
+ fileName: file.fileName,
440
+ contentType,
441
+ sizeBytes: body.size,
442
+ forComment: file.forComment,
443
+ inline: file.inline
444
+ });
445
+ const { upload, attachment } = begun.result;
446
+ const put = await this.#fetch(upload.url, {
447
+ method: upload.method,
448
+ headers: upload.headers,
449
+ body,
450
+ signal: options?.signal
451
+ });
452
+ if (!put.ok) {
453
+ throw toTasqmateError(
454
+ put.status,
455
+ {
456
+ code: "UPLOAD_FAILED",
457
+ message: `Storage refused the upload (status ${put.status})`
458
+ },
459
+ null
460
+ );
461
+ }
462
+ return this.dispatch("attachment.finish", slug, {
463
+ attachmentId: attachment.id
464
+ });
465
+ },
466
+ /** A five-minute link to the bytes, with the name, type and size. */
467
+ link: (slug, attachmentId, options) => this.#get(
468
+ `/workspaces/${encodeURIComponent(slug)}/attachments/${encodeURIComponent(attachmentId)}/download`,
469
+ { link: 1, inline: options?.inline ? 1 : void 0 },
470
+ options
471
+ ),
472
+ /** The file's bytes, read through a fresh link. */
473
+ download: async (slug, attachmentId, options) => {
474
+ const link = await this.attachments.link(slug, attachmentId, options);
475
+ const response = await this.#fetch(link.url, { signal: options?.signal });
476
+ if (!response.ok) {
477
+ throw toTasqmateError(
478
+ response.status,
479
+ {
480
+ code: "DOWNLOAD_FAILED",
481
+ message: `Storage refused the download (status ${response.status})`
482
+ },
483
+ null
484
+ );
485
+ }
486
+ return { link, data: await response.arrayBuffer() };
487
+ },
488
+ /** Remove a file: its uploader, or an admin or owner. */
489
+ remove: (slug, attachmentId) => this.dispatch("attachment.remove", slug, { attachmentId })
490
+ };
491
+ docs = {
492
+ /**
493
+ * The library, most recently edited first. With `project` (an id), the
494
+ * project's docs; `mentioning` then lists the docs that only mention
495
+ * one of its tasks.
496
+ */
497
+ list: (slug, options = {}) => this.#get(
498
+ `/workspaces/${encodeURIComponent(slug)}/docs`,
499
+ { filter: options.filter ?? "all", project: options.project }
500
+ ),
501
+ get: (slug, documentId) => this.#get(
502
+ `/workspaces/${encodeURIComponent(slug)}/docs/${encodeURIComponent(documentId)}`
503
+ ),
504
+ /** The docs linked to a task, mentioning it, or mentioned on it. */
505
+ forTask: async (slug, taskId) => (await this.#get(
506
+ `/workspaces/${encodeURIComponent(slug)}/tasks/${encodeURIComponent(taskId)}/docs`
507
+ )).documents,
508
+ create: (slug, input) => this.dispatch("doc.create", slug, input),
509
+ /**
510
+ * Save a title and body. `baseVersion` is the version the edit started
511
+ * from; a save on an older one is a 409 `CONFLICT`.
512
+ */
513
+ update: (slug, input) => this.dispatch("doc.update", slug, input),
514
+ link: (slug, input) => this.dispatch("doc.link", slug, input),
515
+ unlink: (slug, input) => this.dispatch("doc.unlink", slug, input),
516
+ archive: (slug, documentId) => this.dispatch("doc.archive", slug, { documentId }),
517
+ unarchive: (slug, documentId) => this.dispatch("doc.unarchive", slug, { documentId })
518
+ };
519
+ /**
520
+ * Initiatives group projects across teams. Any member reads them; every
521
+ * write is admin-level, so an agent key (always a member) cannot make one.
522
+ */
523
+ initiatives = {
524
+ list: async (slug) => (await this.#get(
525
+ `/workspaces/${encodeURIComponent(slug)}/initiatives`
526
+ )).initiatives,
527
+ create: (slug, input) => this.dispatch("initiative.create", slug, input),
528
+ update: (slug, input) => this.dispatch("initiative.update", slug, input),
529
+ delete: (slug, input) => this.dispatch("initiative.delete", slug, input),
530
+ linkProject: (slug, input) => this.dispatch("initiative.linkProject", slug, input),
531
+ unlinkProject: (slug, input) => this.dispatch("initiative.unlinkProject", slug, input)
532
+ };
533
+ /**
534
+ * Project updates: a health call and a body for the project's client (7.5).
535
+ *
536
+ * `draft` is what an agent calls; an agent's update is always a draft
537
+ * whatever it passes. `send` is people only: no agent policy can grant it,
538
+ * because nothing an agent drafts goes to a client without a person
539
+ * approving it.
540
+ */
541
+ projectUpdates = {
542
+ /**
543
+ * Every update on the project, drafts included, newest first. Follows
544
+ * `nextCursor` until the last page; use `listPage` for one page.
545
+ */
546
+ list: async (slug, projectId) => {
547
+ const updates = [];
548
+ let before;
549
+ do {
550
+ const page = await this.projectUpdates.listPage(slug, projectId, {
551
+ limit: PROJECT_UPDATES_PAGE_MAX,
552
+ before
553
+ });
554
+ updates.push(...page.updates);
555
+ before = page.nextCursor ?? void 0;
556
+ } while (before !== void 0);
557
+ return updates;
558
+ },
559
+ /**
560
+ * One page of the project's updates, drafts included, newest first; pass
561
+ * `nextCursor` as `before` for the next. The API returns 20 by default,
562
+ * at most 100.
563
+ */
564
+ listPage: (slug, projectId, query = {}) => this.#get(
565
+ `/workspaces/${encodeURIComponent(slug)}/projects/${encodeURIComponent(projectId)}/updates`,
566
+ { limit: query.limit, before: query.before }
567
+ ),
568
+ draft: (slug, input) => this.dispatch("projectUpdate.create", slug, input),
569
+ create: (slug, input) => this.dispatch("projectUpdate.create", slug, input),
570
+ update: (slug, input) => this.dispatch("projectUpdate.update", slug, input),
571
+ send: (slug, input) => this.dispatch("projectUpdate.send", slug, input),
572
+ delete: (slug, input) => this.dispatch("projectUpdate.delete", slug, input)
573
+ };
574
+ threads = {
575
+ /**
576
+ * The context bundle for one thread: the entity it hangs off, the
577
+ * transcript, recent activity, and the participants (D-6).
578
+ *
579
+ * Authorized by the entity's own read rule, so a read-only agent may
580
+ * pull it. Lists are capped per D-8 with `truncated` flags.
581
+ */
582
+ context: (slug, threadId, options) => this.#get(
583
+ `/workspaces/${encodeURIComponent(slug)}/threads/${encodeURIComponent(threadId)}/context`,
584
+ void 0,
585
+ options
586
+ )
587
+ };
588
+ cycles = {
589
+ list: async (slug, filters) => (await this.#get(
590
+ `/workspaces/${encodeURIComponent(slug)}/cycles`,
591
+ filters
592
+ )).cycles
593
+ };
594
+ teams = {
595
+ list: async (slug) => (await this.#get(
596
+ `/workspaces/${encodeURIComponent(slug)}/teams`
597
+ )).teams,
598
+ /** The only read that carries a team's statuses. */
599
+ get: async (slug, identifier) => (await this.#get(
600
+ `/workspaces/${encodeURIComponent(slug)}/teams/${encodeURIComponent(identifier)}`
601
+ )).team,
602
+ /**
603
+ * Whether agents on this team may wake each other, plus the loop and
604
+ * fan-out limits that stand behind the open setting (B-04c D-1).
605
+ *
606
+ * Read-only here on purpose: saving the setting is admin-only and web-only
607
+ * (D-8), so no agent key can reach it.
608
+ */
609
+ agentSettings: (slug, identifier) => this.#get(
610
+ `/workspaces/${encodeURIComponent(slug)}/teams/${encodeURIComponent(identifier)}/agent-settings`
611
+ )
612
+ };
613
+ labels = {
614
+ list: async (slug) => (await this.#get(
615
+ `/workspaces/${encodeURIComponent(slug)}/labels`
616
+ )).labels
617
+ };
618
+ /**
619
+ * Custom fields (6.4): the workspace library, archived fields included.
620
+ * Values are set with `task.setField` and `project.setField`, by field key.
621
+ */
622
+ fields = {
623
+ list: async (slug) => (await this.#get(
624
+ `/workspaces/${encodeURIComponent(slug)}/fields`
625
+ )).fields,
626
+ /** Set a task's value; null, `[]` or `false` clears it. */
627
+ setTaskValue: (slug, taskId, fieldKey, value) => this.dispatch("task.setField", slug, { taskId, fieldKey, value }),
628
+ /**
629
+ * Set one value on up to 100 tasks, all or nothing: a task whose team
630
+ * has the field off refuses the whole set.
631
+ */
632
+ bulkSetTaskValue: (slug, taskIds, fieldKey, value) => this.dispatch("task.bulkSetField", slug, { taskIds, fieldKey, value }),
633
+ /** Set a project field's value; null clears it. */
634
+ setProjectValue: (slug, projectId, fieldKey, value) => this.dispatch("project.setField", slug, { projectId, fieldKey, value })
635
+ };
636
+ agents = {
637
+ policy: (slug, agentId) => this.#get(
638
+ `/workspaces/${encodeURIComponent(slug)}/agents/${encodeURIComponent(agentId)}/policy`
639
+ ),
640
+ /**
641
+ * Long-poll for mentions addressed to the agent behind this key.
642
+ *
643
+ * The same call acks: ids passed as `ack` are marked before the select
644
+ * runs, so a runner's next poll is also its acknowledgement of the last
645
+ * batch (D-5). Agent keys only.
646
+ */
647
+ events: (slug, query = {}, options) => this.#get(
648
+ `/workspaces/${encodeURIComponent(slug)}/agents/me/events`,
649
+ {
650
+ wait: query.wait,
651
+ limit: query.limit,
652
+ ack: query.ack === void 0 || query.ack.length === 0 ? void 0 : query.ack.join(",")
653
+ },
654
+ options
655
+ ),
656
+ /** The paired bridge behind this agent key, or `bridge: null` (BR-1). */
657
+ bridge: (slug) => this.#get(
658
+ `/workspaces/${encodeURIComponent(slug)}/agents/me/bridge`
659
+ ),
660
+ /**
661
+ * Report what the bridge is doing: `running` while it works a wake,
662
+ * then `idle`. Every report is also a sign of life for the presence dot.
663
+ */
664
+ reportBridgeState: (slug, report) => this.#request(
665
+ `/workspaces/${encodeURIComponent(slug)}/agents/me/bridge/state`,
666
+ { method: "POST", body: JSON.stringify(report) }
667
+ ),
668
+ /** The bridge unpairs itself: its record and this key are revoked. */
669
+ unpairBridge: (slug) => this.#request(
670
+ `/workspaces/${encodeURIComponent(slug)}/agents/me/bridge`,
671
+ { method: "DELETE" }
672
+ )
673
+ };
674
+ /**
675
+ * Pairing a Tasqmate Bridge (BR-1). Both calls are anonymous: the bridge
676
+ * has no credential until a person approves it, and the device code is
677
+ * the secret it collects its key with.
678
+ */
679
+ bridge = {
680
+ startPairing: (report) => this.#request("/bridge/pairings", {
681
+ method: "POST",
682
+ body: JSON.stringify(report),
683
+ anonymous: true
684
+ }),
685
+ /** Ask once whether the pairing was approved; the key comes back exactly once. */
686
+ pollPairing: (deviceCode) => this.#request("/bridge/pairings/token", {
687
+ method: "POST",
688
+ body: JSON.stringify({ deviceCode }),
689
+ anonymous: true
690
+ })
691
+ };
692
+ /**
693
+ * Agent routines (AR-1): schedules that wake an agent with a prompt. A
694
+ * routine only emits a `routine` event at its time; the runner pulls it
695
+ * with `agents.events` and acts. Managing routines takes an owner or admin
696
+ * session or user key; agent keys can list them but never change them.
697
+ */
698
+ routines = {
699
+ list: async (slug, query = {}) => (await this.#get(
700
+ `/workspaces/${encodeURIComponent(slug)}/agent-console/routines`,
701
+ { agent: query.agent }
702
+ )).routines,
703
+ create: (slug, input) => this.dispatch("routine.create", slug, input),
704
+ update: (slug, input) => this.dispatch("routine.update", slug, input),
705
+ pause: (slug, routineId) => this.dispatch("routine.pause", slug, { routineId }),
706
+ resume: (slug, routineId) => this.dispatch("routine.resume", slug, { routineId }),
707
+ delete: (slug, routineId) => this.dispatch("routine.delete", slug, { routineId }),
708
+ /** Wake the agent now; the schedule stays where it was. */
709
+ runNow: (slug, routineId) => this.dispatch("routine.runNow", slug, { routineId })
710
+ };
711
+ /**
712
+ * Releases: the structural record of a cycle close, and the narrative an
713
+ * agent or a person attaches to it (B-04d).
714
+ *
715
+ * Reads are authorized by the workspace role guard rather than a policy
716
+ * action, so a read-only agent may pull the context it needs; the write
717
+ * goes through `release.saveNarrative` like every other action.
718
+ */
719
+ releases = {
720
+ list: async (slug, teamIdentifier) => (await this.#get(
721
+ `/workspaces/${encodeURIComponent(slug)}/releases`,
722
+ { team: teamIdentifier }
723
+ )).releases,
724
+ get: async (slug, releaseId) => (await this.#get(
725
+ `/workspaces/${encodeURIComponent(slug)}/releases/${encodeURIComponent(releaseId)}`
726
+ )).release,
727
+ /**
728
+ * The context bundle a narrator writes from.
729
+ *
730
+ * `format: "markdown"` returns the server-rendered prompt as a string,
731
+ * which is what a harness pastes into a model; the default returns the
732
+ * bundle, for a runner that branches on the fields itself.
733
+ */
734
+ context: ((slug, releaseId, options = {}) => {
735
+ const path = `/workspaces/${encodeURIComponent(slug)}/releases/${encodeURIComponent(releaseId)}/context`;
736
+ return options.format === "markdown" ? this.#text(path, { format: "markdown" }, options) : this.#get(path, void 0, options);
737
+ }),
738
+ diff: async (slug, releaseId) => (await this.#get(
739
+ `/workspaces/${encodeURIComponent(slug)}/releases/${encodeURIComponent(releaseId)}/diff`
740
+ )).diff,
741
+ /** The release as a Markdown document, the same body the web export serves. */
742
+ export: (slug, releaseId) => this.#text(
743
+ `/workspaces/${encodeURIComponent(slug)}/releases/${encodeURIComponent(releaseId)}/export`
744
+ ),
745
+ /** Last write wins; the author and timestamp move with the body (D-3). */
746
+ saveNarrative: (slug, input) => this.dispatch("release.saveNarrative", slug, input)
747
+ };
748
+ members = {
749
+ list: async (slug) => (await this.#get(
750
+ `/workspaces/${encodeURIComponent(slug)}/members`
751
+ )).members
752
+ };
753
+ notifications = {
754
+ list: (slug, query = {}) => this.#get(
755
+ `/workspaces/${encodeURIComponent(slug)}/notifications`,
756
+ { unread: query.unread === true ? 1 : void 0 }
757
+ )
758
+ };
759
+ activity = {
760
+ /** The workspace activity feed, newest first; page with `nextCursor`. */
761
+ list: (slug, query = {}) => this.#get(
762
+ `/workspaces/${encodeURIComponent(slug)}/activity`,
763
+ { limit: query.limit, before: query.before }
764
+ )
765
+ };
766
+ waiting = {
767
+ /** Approvals and agent drafts waiting on the caller. People only. */
768
+ get: (slug) => this.#get(
769
+ `/workspaces/${encodeURIComponent(slug)}/waiting`
770
+ )
771
+ };
772
+ auth = {
773
+ /** The principal behind the current credential. */
774
+ me: async () => (await this.#get("/auth/me")).user,
775
+ /** Step one of CLI login: mail a sign-in code. Needs no credential. */
776
+ requestMagicLink: async (input) => {
777
+ await this.#request("/auth/magic-link", {
778
+ method: "POST",
779
+ body: JSON.stringify({ email: input.email }),
780
+ anonymous: true
781
+ });
782
+ },
783
+ /** Step two: exchange the code for a `tq_us_…` token. Needs no credential. */
784
+ verifyCliCode: (input) => this.#request("/auth/cli/verify-code", {
785
+ method: "POST",
786
+ body: JSON.stringify(input),
787
+ anonymous: true
788
+ }),
789
+ /** Revoke the user token this client authenticates with. */
790
+ revokeUserToken: async () => {
791
+ await this.#request("/auth/cli/token", { method: "DELETE" });
792
+ }
793
+ };
794
+ /** Run a write action. The API validates `input`; the SDK does not. */
795
+ dispatch(action, slug, input) {
796
+ return this.#request(
797
+ `/workspaces/${encodeURIComponent(slug)}/actions`,
798
+ { method: "POST", body: JSON.stringify({ action, input }) }
799
+ );
800
+ }
801
+ };
802
+
803
+ // src/time.ts
804
+ var DURATION_FORMS = "1h 30m, 1h30m, 90m, 1.5h, 1:30 or a bare number of hours";
805
+ function parseDuration(raw) {
806
+ const value = raw.trim().toLowerCase().replace(/\s+/g, "");
807
+ if (!value) return null;
808
+ let match = value.match(/^(\d{1,2}):([0-5]\d)$/);
809
+ if (match) return Number(match[1]) * 60 + Number(match[2]);
810
+ match = value.match(/^(\d+(?:\.\d+)?)h$/);
811
+ if (match) return Math.round(Number(match[1]) * 60);
812
+ match = value.match(/^(\d+)m(?:in|ins)?$/);
813
+ if (match) return Number(match[1]);
814
+ match = value.match(/^(\d+)h(\d+)m?(?:in|ins)?$/);
815
+ if (match) return Number(match[1]) * 60 + Number(match[2]);
816
+ match = value.match(/^(\d+(?:\.\d+)?)$/);
817
+ if (match) return Math.round(Number(match[1]) * 60);
818
+ return null;
819
+ }
820
+ function formatMinutes(minutes) {
821
+ const hours = Math.floor(minutes / 60);
822
+ const rest = minutes % 60;
823
+ if (hours === 0) return `${rest}m`;
824
+ return rest === 0 ? `${hours}h` : `${hours}h ${rest}m`;
825
+ }
826
+
827
+ // src/types.ts
828
+ var PROJECT_HEALTH_VALUES = [
829
+ "on_track",
830
+ "at_risk",
831
+ "off_track"
832
+ ];
833
+ var THREAD_CONTEXT_MESSAGE_LIMIT = 50;
834
+ var THREAD_CONTEXT_ACTIVITY_LIMIT = 20;
835
+ var THREAD_CONTEXT_DESCRIPTION_MAX = 8e3;
836
+ var AGENT_ISOLATION_VALUES = ["isolated", "open"];
837
+ var SUPPRESSED_REASONS = [
838
+ "isolation",
839
+ "fanout_cap",
840
+ "loop_cap",
841
+ "guest_actor",
842
+ "policy_kind",
843
+ "policy_sender",
844
+ "policy_scope"
845
+ ];
846
+ var MAX_AGENT_WAKES_PER_MESSAGE = 10;
847
+ var MAX_CONSECUTIVE_AGENT_MESSAGES = 5;
848
+ var RELEASE_DISPOSITIONS = [
849
+ "shipped",
850
+ "carried_over",
851
+ "dropped"
852
+ ];
853
+ var RELEASE_NARRATIVE_MAX = 5e4;
854
+ var RELEASE_NARRATIVE_EXCERPT_MAX = 500;
855
+ var RELEASE_CONTEXT_TASK_LIMIT = 100;
856
+ var DOCUMENT_FILTERS = [
857
+ "all",
858
+ "workspace",
859
+ "projects",
860
+ "teams",
861
+ "mine",
862
+ "templates",
863
+ "archived"
864
+ ];
865
+ export {
866
+ AGENT_ISOLATION_VALUES,
867
+ AGENT_KEY_PREFIX,
868
+ DOCUMENT_FILTERS,
869
+ DURATION_FORMS,
870
+ MAX_AGENT_WAKES_PER_MESSAGE,
871
+ MAX_CONSECUTIVE_AGENT_MESSAGES,
872
+ PROJECT_HEALTH_VALUES,
873
+ RELEASE_CONTEXT_TASK_LIMIT,
874
+ RELEASE_DISPOSITIONS,
875
+ RELEASE_NARRATIVE_EXCERPT_MAX,
876
+ RELEASE_NARRATIVE_MAX,
877
+ SUPPRESSED_REASONS,
878
+ THREAD_CONTEXT_ACTIVITY_LIMIT,
879
+ THREAD_CONTEXT_DESCRIPTION_MAX,
880
+ THREAD_CONTEXT_MESSAGE_LIMIT,
881
+ TasqmateApiError,
882
+ TasqmateClient,
883
+ TasqmatePolicyDeniedError,
884
+ TasqmateRateLimitError,
885
+ TasqmateValidationError,
886
+ USER_TOKEN_PREFIX,
887
+ contentTypeFor,
888
+ fileMarkdown,
889
+ formatFileSize,
890
+ formatMinutes,
891
+ isPreviewableImage,
892
+ parseDuration
893
+ };
894
+ //# sourceMappingURL=index.js.map