@kamilio/wire 0.1.38 → 0.1.39

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,334 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { Cookie, RuntimeCapabilities } from "wire-core";
3
+
4
+ const origin = "https://app.ashbyhq.com";
5
+ const entries =
6
+ "id sourceFormDefinitionId fieldEntries { field fieldValue { ... on JSONBox { value } } isHidden isFixed }";
7
+ type Entry = {
8
+ field: {
9
+ path: string;
10
+ title: string;
11
+ type: string;
12
+ selectableValues?: { label: string; value: string }[];
13
+ };
14
+ fieldValue: { value: any } | null;
15
+ isHidden: boolean;
16
+ isFixed: boolean;
17
+ };
18
+ type Form = {
19
+ id: string;
20
+ sourceFormDefinitionId: string;
21
+ fieldEntries: Entry[];
22
+ };
23
+ type Rich = {
24
+ type: string;
25
+ text?: string;
26
+ content?: Rich[];
27
+ attrs?: { href?: string };
28
+ marks?: Rich[];
29
+ };
30
+
31
+ function plain(n: Rich): string {
32
+ const body = n.text ?? (n.content ?? []).map(plain).join("");
33
+ if (n.type === "text") {
34
+ const url = n.marks?.find((m) => m.type === "link")?.attrs?.href;
35
+ return url ? `[${body}](${url})` : body;
36
+ }
37
+ if (n.type === "listItem") return "- " + body.trimEnd() + "\n";
38
+ return (
39
+ body + (["paragraph", "heading", "hardBreak"].includes(n.type) ? "\n" : "")
40
+ );
41
+ }
42
+
43
+ export async function ashbySession(
44
+ runtime: RuntimeCapabilities,
45
+ cookies: readonly Cookie[],
46
+ ) {
47
+ const cookie = cookies
48
+ .filter((c) =>
49
+ ["ashbyhq.com", "app.ashbyhq.com"].includes(c.domain.replace(/^\./, "")),
50
+ )
51
+ .map((c) => c.name + "=" + c.value)
52
+ .join("; ");
53
+ const res = await runtime.http.request(origin + "/api/csrf/token", {
54
+ headers: { cookie },
55
+ redirect: "error",
56
+ });
57
+ if (!res.ok)
58
+ throw new Error("Ashby authentication failed. Run `wire ashby login`.");
59
+ const { token } = await res.json();
60
+ const csrfCookie = res.headers
61
+ .getSetCookie()
62
+ .map((c) => c.split(";")[0])
63
+ .join("; ");
64
+ return async (query: string, variables: Record<string, unknown> = {}) => {
65
+ const response = await runtime.http.request(origin + "/api/graphql", {
66
+ method: "POST",
67
+ redirect: "error",
68
+ headers: {
69
+ cookie: [cookie, csrfCookie].filter(Boolean).join("; "),
70
+ "x-csrf-token": token,
71
+ "x-ashby-app": "Recruiting",
72
+ "content-type": "application/json",
73
+ origin,
74
+ },
75
+ body: JSON.stringify({ query, variables }),
76
+ });
77
+ if (!response.ok)
78
+ throw new Error("Ashby request failed (HTTP " + response.status + ").");
79
+ const result = await response.json();
80
+ if (result.errors?.length || !result.data)
81
+ throw new Error(
82
+ "Ashby rejected the request. Check your login and access to the interview.",
83
+ );
84
+ return result.data;
85
+ };
86
+ }
87
+ type Query = Awaited<ReturnType<typeof ashbySession>>;
88
+
89
+ function eventId(url: string): string {
90
+ const m =
91
+ /^https:\/\/app\.ashbyhq\.com\/interview-briefings\/([\da-f-]{36})(?:\/feedback)?\/?$/.exec(
92
+ url,
93
+ );
94
+ if (!m) throw new Error("Expected an Ashby interview briefing URL.");
95
+ return m[1]!;
96
+ }
97
+ function answer(e: Entry): string {
98
+ const v = e.fieldValue?.value;
99
+ if (v == null) return "";
100
+ if (e.field.type === "RichText") return plain(v.content).trim();
101
+ const label = (s: string) =>
102
+ e.field.selectableValues?.find((o) => o.value === s)?.label ?? String(s);
103
+ return (Array.isArray(v) ? v.map(label).join("\n") : label(v)).trim();
104
+ }
105
+ const hash = (s: string) => createHash("sha256").update(s).digest("hex");
106
+ function template(url: string, name: string, form: Form, owner: string): string {
107
+ return (
108
+ [
109
+ `# ${name}\n\n${url}\n<!-- ashby-draft ${owner} -->`,
110
+ ...form.fieldEntries
111
+ .filter((e) => !e.isHidden && !e.isFixed)
112
+ .map((e) => {
113
+ const value = answer(e);
114
+ const options =
115
+ e.field.selectableValues?.map((o) => o.label) ??
116
+ (e.field.type === "Boolean" ? ["true", "false"] : []);
117
+ return (
118
+ `## ${e.field.title}\n<!-- ashby-field ${encodeURIComponent(e.field.path)} ${hash(value)} -->\n` +
119
+ (options.length ? "> Options: " + options.join(" | ") + "\n" : "") +
120
+ "\n" +
121
+ value
122
+ );
123
+ }),
124
+ ].join("\n\n") + "\n"
125
+ );
126
+ }
127
+ function payload(e: Entry, value: string) {
128
+ if (e.field.type === "RichText")
129
+ return {
130
+ version: "2",
131
+ attachments: [],
132
+ features: [],
133
+ content: {
134
+ type: "doc",
135
+ content: value
136
+ .split("\n")
137
+ .map((text) => ({
138
+ type: "paragraph",
139
+ content: text ? [{ type: "text", text }] : [],
140
+ })),
141
+ },
142
+ };
143
+ if (e.field.type === "Boolean" && ["true", "false"].includes(value))
144
+ return value === "true";
145
+ if (e.field.type === "String" || e.field.type === "LongText") return value;
146
+ if (["MultiValueSelect", "ValueSelect"].includes(e.field.type)) {
147
+ const selected = value.split("\n").map((s) => {
148
+ const options = e.field.selectableValues?.filter((o) => o.label === s);
149
+ if (options?.length !== 1)
150
+ throw new Error("Invalid option for " + e.field.title);
151
+ return options[0]!.value;
152
+ });
153
+ if (e.field.type === "MultiValueSelect") return selected;
154
+ if (selected.length === 1) return selected[0];
155
+ }
156
+ throw new Error("Unsupported answer for " + e.field.title);
157
+ }
158
+
159
+ const header =
160
+ "candidate { name } jobTitle interviewEvent { id startTime endTime interview { title } }";
161
+ async function draft(q: Query, url: string) {
162
+ const b = (
163
+ await q(
164
+ `query($id:String!) { interviewBriefing(interviewEventId:$id) { ${header} interviewerEvent { id scorecardSubmission { ... on Scorecard { id } } } } }`,
165
+ { id: eventId(url) },
166
+ )
167
+ ).interviewBriefing;
168
+ if (!b.interviewerEvent || b.interviewerEvent.scorecardSubmission !== null)
169
+ throw new Error("No editable personal scorecard for this interview.");
170
+ const form: Form = (
171
+ await q(
172
+ `mutation($id:String!){ startScorecardForm(interviewerEventId:$id){ ${entries} } }`,
173
+ { id: b.interviewerEvent.id },
174
+ )
175
+ ).startScorecardForm;
176
+ return { form, owner: b.interviewerEvent.id as string, name: b.candidate.name as string };
177
+ }
178
+
179
+ export async function ashby(
180
+ runtime: RuntimeCapabilities,
181
+ action: string,
182
+ arg?: string,
183
+ ): Promise<string> {
184
+ const q = await ashbySession(runtime, await runtime.cookies.load("ashby"));
185
+ if (action === "interviews" || action === "pending") {
186
+ const fields =
187
+ "id startTime endTime interview{title} application{candidate{name} job{title}} interviewerEvents{interviewer{id}}";
188
+ const { interviewEvents, sessionUser } =
189
+ action === "pending"
190
+ ? await q(
191
+ `query {sessionUser{id} interviewEvents:interviewEventsWithOverdueScorecards{${fields}}}`,
192
+ )
193
+ : await q(
194
+ `query($now:DateTime!){ sessionUser{id} interviewEvents(onOrAfterTime:$now,ascending:true){${fields}} }`,
195
+ { now: runtime.clock.now().toISOString() },
196
+ );
197
+ return (
198
+ interviewEvents
199
+ .filter((e: any) =>
200
+ e.interviewerEvents.some(
201
+ (i: any) => i.interviewer.id === sessionUser.id,
202
+ ),
203
+ )
204
+ .map(
205
+ (e: any) =>
206
+ `- ${e.startTime} – ${e.endTime} · ${e.application.candidate.name} · ${e.interview.title} · ${e.application.job.title}\n ${origin}/interview-briefings/${e.id}`,
207
+ )
208
+ .join("\n") || "No matching interviews."
209
+ );
210
+ }
211
+ if (action === "latest") {
212
+ let cursor = null,
213
+ latest: { id: string; at: string } | undefined;
214
+ do {
215
+ const d = await q(
216
+ `query($cursor:String){sessionUser{id} paginatedInterviewEvents(cursor:$cursor){ results{id interviewerEvents{interviewer{id} scorecardSubmission{... on Scorecard{submittedAt submittedByUser{id}}}}} moreDataAvailable nextCursor}}`,
217
+ { cursor },
218
+ );
219
+ for (const event of d.paginatedInterviewEvents.results)
220
+ for (const i of event.interviewerEvents) {
221
+ const s = i.scorecardSubmission;
222
+ if (
223
+ s?.submittedAt &&
224
+ i.interviewer.id === d.sessionUser.id &&
225
+ s.submittedByUser?.id === d.sessionUser.id &&
226
+ (!latest || s.submittedAt > latest.at)
227
+ )
228
+ latest = { id: event.id, at: s.submittedAt };
229
+ }
230
+ cursor = d.paginatedInterviewEvents.moreDataAvailable
231
+ ? d.paginatedInterviewEvents.nextCursor
232
+ : null;
233
+ } while (cursor);
234
+ if (!latest) return "No submitted feedback.";
235
+ const b = (
236
+ await q(
237
+ `query($id:String!){interviewBriefing(interviewEventId:$id){${header} interviewerEvent{scorecardSubmission{... on Scorecard{submittedAt submittedFormRender{${entries}}}}}}}`,
238
+ { id: latest.id },
239
+ )
240
+ ).interviewBriefing;
241
+ const s = b.interviewerEvent.scorecardSubmission;
242
+ return [
243
+ `# ${b.candidate.name} · ${b.interviewEvent.interview.title}\n\nSubmitted: ${s.submittedAt}\n${origin}/interview-briefings/${latest.id}/feedback`,
244
+ ...s.submittedFormRender.fieldEntries
245
+ .filter((e: Entry) => !e.isHidden && answer(e))
246
+ .map((e: Entry) => "## " + e.field.title + "\n\n" + answer(e)),
247
+ ].join("\n\n");
248
+ }
249
+ if (action === "prep") {
250
+ const b = (
251
+ await q(
252
+ `query($id:String!) { interviewBriefing(interviewEventId:$id){${header} instructions applicationResume{employmentHistory{position employer{name}} educationHistory{school{name}}}}}`,
253
+ { id: eventId(arg!) },
254
+ )
255
+ ).interviewBriefing;
256
+ const r = b.applicationResume;
257
+ return [
258
+ `# ${b.candidate.name} · ${b.interviewEvent.interview.title}`,
259
+ b.jobTitle,
260
+ b.interviewEvent.startTime + " – " + b.interviewEvent.endTime,
261
+ arg,
262
+ "## Candidate background",
263
+ ...(r?.employmentHistory ?? []).map((x: any) =>
264
+ [x.position, x.employer?.name].filter(Boolean).join(", "),
265
+ ),
266
+ ...(r?.educationHistory ?? []).map((x: any) => x.school?.name),
267
+ "## Interview briefing",
268
+ b.instructions && plain(b.instructions.content),
269
+ ]
270
+ .filter(Boolean)
271
+ .join("\n\n");
272
+ }
273
+ if (action === "template") {
274
+ const { name, form, owner } = await draft(q, arg!);
275
+ return template(arg!, name, form, owner);
276
+ }
277
+ if (action !== "sync") throw new Error("Unknown Ashby command.");
278
+ const file = arg!,
279
+ md = await runtime.filesystem.readText(file);
280
+ const url = md.split("\n")[2]!;
281
+ const { name, form, owner } = await draft(q, url);
282
+ if (md.split("\n")[3] !== `<!-- ashby-draft ${owner} -->`)
283
+ throw new Error("The file does not belong to this draft.");
284
+ const sections = md.trimEnd().split(/^## /m).slice(1);
285
+ const seen = new Set<string>(),
286
+ changes = [];
287
+ for (const section of sections) {
288
+ const m =
289
+ /^[^\n]+\n<!-- ashby-field (\S+) ([a-f0-9]{64}) -->\n?(?:> Options:[^\n]*\n?)?([\s\S]*)$/.exec(
290
+ section,
291
+ );
292
+ if (!m)
293
+ throw new Error(
294
+ "Invalid Ashby section; keep the generated field markers.",
295
+ );
296
+ const path = decodeURIComponent(m[1]!),
297
+ value = m[3]!.trim();
298
+ const e = form.fieldEntries.find(
299
+ (e) => e.field.path === path && !e.isHidden && !e.isFixed,
300
+ );
301
+ if (!e || seen.has(path))
302
+ throw new Error("Unknown or repeated scorecard field.");
303
+ seen.add(path);
304
+ if (!value || hash(value) === m[2] || value === answer(e)) continue;
305
+ if (hash(answer(e)) !== m[2])
306
+ throw new Error("Remote draft changed: " + e.field.title);
307
+ changes.push({ path, value: payload(e, value), text: value });
308
+ }
309
+ if (!sections.length) throw new Error("No scorecard sections found.");
310
+ for (const change of changes) {
311
+ const updated = (
312
+ await q(
313
+ `mutation($id:String!,$path:String!,$v:JSON,$definition:String){setFormValue(formRenderIdentifier:$id,path:$path,value:$v,formDefinitionIdentifier:$definition){${entries}}}`,
314
+ {
315
+ id: form.id,
316
+ path: change.path,
317
+ v: change.value,
318
+ definition: form.sourceFormDefinitionId,
319
+ },
320
+ )
321
+ ).setFormValue as Form;
322
+ if (
323
+ answer(
324
+ updated.fieldEntries.find((e) => e.field.path === change.path)!,
325
+ ) !== change.text
326
+ )
327
+ throw new Error("Ashby did not save the requested value.");
328
+ }
329
+ const fresh = await draft(q, url);
330
+ if (md !== (await runtime.filesystem.readText(file)))
331
+ throw new Error("The local file changed during sync.");
332
+ await runtime.filesystem.writeText(file, template(url, name, fresh.form, owner));
333
+ return `Saved ${changes.length} draft section(s). Review and submit: ${url}`;
334
+ }
@@ -10,9 +10,9 @@ import { formatAgenda, type readAgenda } from "./calendar.js";
10
10
 
11
11
  export type WireRoot = Group;
12
12
  export type TextInputReader = () => Promise<string>;
13
- export type WireRootOptions = Readonly<{ allowPaste: boolean; previewDrive?: (url: string) => Promise<string>; scrapeDrive?: (url?: string) => Promise<string>; calendarAgenda?: (date?: string, calendarId?: string) => ReturnType<typeof readAgenda>; latticeSync?: (url: string | undefined, file?: string) => Promise<string>; latticeRequests?: (url: string) => Promise<string>; latticeTemplate?: (url: string) => Promise<string>; latticeFill?: (url: string, file: string) => Promise<string>; scrapeZoom?: () => ReturnType<typeof zoomProvider.scrape> }>;
13
+ export type WireRootOptions = Readonly<{ allowPaste: boolean; ashby?: (action: string, arg?: string) => Promise<string>; previewDrive?: (url: string) => Promise<string>; scrapeDrive?: (url?: string) => Promise<string>; calendarAgenda?: (date?: string, calendarId?: string) => ReturnType<typeof readAgenda>; latticeSync?: (url: string | undefined, file?: string) => Promise<string>; latticeRequests?: (url: string) => Promise<string>; latticeTemplate?: (url: string) => Promise<string>; latticeFill?: (url: string, file: string) => Promise<string>; scrapeZoom?: () => ReturnType<typeof zoomProvider.scrape> }>;
14
14
 
15
- const authServices = ["asana", "chatgpt", "gmail", "google-docs", "notion", "slack", "zoom"] as const;
15
+ const authServices = ["ashby", "asana", "chatgpt", "gmail", "google-docs", "notion", "slack", "zoom"] as const;
16
16
  const removedCliCommandNames = Object.freeze({
17
17
  create: "Use `wire attach <url>` or `wire <url>`.",
18
18
  fetch: "Use `wire download <url>`.",
@@ -207,7 +207,7 @@ function wireUserErrorMessage(message: string): boolean {
207
207
  || /^Resource (path |identifier |URL )?not found: /.test(message)
208
208
  || /^Ambiguous resource path /.test(message)
209
209
  || /^Login not saved$/.test(message)
210
- || /authentication (is missing|is missing or expired|failed|expired).*Run `wire (asana|chatgpt|gmail|google-docs|notion|slack|zoom) login`/i.test(message)
210
+ || /authentication (is missing|is missing or expired|failed|expired).*Run `wire (ashby|asana|chatgpt|gmail|google-docs|notion|slack|zoom) login`/i.test(message)
211
211
  || /^Asana API /.test(message)
212
212
  || /^(GET|POST|PUT|DELETE) \/.* failed: \d+ /.test(message)
213
213
  || /^(Invalid Asana project heading|Asana section appears|Asana milestone appears|Asana task appears|Asana subtask appears|Unsupported Asana Markdown|Duplicate Asana identity|Missing Asana project heading|Asana project identity changed|Unknown Asana identity|Conflicting Asana edits)/.test(message)
@@ -246,7 +246,7 @@ function wireUserErrorDisplayMessage(message: string): string {
246
246
  if (unsupportedSource !== null) return `unsupported source\nurl: ${lineText(unsupportedSource[1]!)}\nsupported: Asana, ChatGPT, Gmail, Google Docs/Sheets/Slides/Forms, Notion, Slack, Zoom`;
247
247
  const existingWorkspace = /^Wire workspace already initialized with (sqlite|files) registry at ([\s\S]+)\. Existing registries are not overwritten\.$/.exec(message);
248
248
  if (existingWorkspace !== null) return `workspace already initialized\nbackend: ${existingWorkspace[1]!}\nregistry: ${lineText(existingWorkspace[2]!)}\nkept: existing registry`;
249
- const authentication = /authentication (is missing or expired|is missing|failed|expired).*Run `wire (asana|chatgpt|gmail|google-docs|notion|slack|zoom) login`/i.exec(message);
249
+ const authentication = /authentication (is missing or expired|is missing|failed|expired).*Run `wire (ashby|asana|chatgpt|gmail|google-docs|notion|slack|zoom) login`/i.exec(message);
250
250
  if (authentication !== null) return `login required\nservice: ${serviceTitle(authentication[2] as AuthService)}\nrun: wire ${authentication[2]} login`;
251
251
  const asanaApi = /^Asana API ([^\s]+) failed: HTTP (\d+)(?: ([\s\S]+))?$/.exec(message);
252
252
  if (asanaApi !== null) return `api failed\nservice: Asana\nrequest: ${lineText(asanaApi[1]!)}\nstatus: HTTP ${asanaApi[2]!}${asanaApi[3] === undefined ? "" : `\ndetail: ${lineText(asanaApi[3]!)}`}`;
@@ -345,6 +345,7 @@ function userFacing<T>(operation: () => Promise<T>): Promise<T> {
345
345
 
346
346
  function serviceTitle(service: AuthService): string {
347
347
  return {
348
+ ashby: "Ashby",
348
349
  asana: "Asana",
349
350
  chatgpt: "ChatGPT",
350
351
  gmail: "Gmail",
@@ -410,7 +411,7 @@ export const wirePresentation: WirePresentation = Object.freeze({
410
411
  function authGroup(service: AuthService, description: string, loginDescription: string, auth: Auth, readInput: TextInputReader | undefined, options: WireRootOptions): Group {
411
412
  const login = async (paste: boolean | undefined) => {
412
413
  if (paste === true && !options.allowPaste) throw new UserError("Cookie paste is CLI-only.");
413
- return paste === true ? auth.pasteCookies(service, await readInput!()) : service === "asana" ? auth.extractAsana() : service === "chatgpt" ? auth.extractChatgpt() : service === "gmail" ? auth.extractGmail() : service === "google-docs" ? auth.extractGoogleDocs() : service === "notion" ? auth.extractNotion() : service === "slack" ? auth.extractSlack() : auth.extractZoom();
414
+ return paste === true ? auth.pasteCookies(service, await readInput!()) : service === "ashby" ? auth.extractAshby() : service === "asana" ? auth.extractAsana() : service === "chatgpt" ? auth.extractChatgpt() : service === "gmail" ? auth.extractGmail() : service === "google-docs" ? auth.extractGoogleDocs() : service === "notion" ? auth.extractNotion() : service === "slack" ? auth.extractSlack() : auth.extractZoom();
414
415
  };
415
416
  const title = serviceTitle(service);
416
417
  return defineGroup({ name: service, description, children: [
@@ -561,6 +562,18 @@ export function createRoot(wire: Wire, currentDirectory: string, auth?: Auth, re
561
562
  render: render<JsonObject>((comment) => `Updated comment ${comment["gid"]}`),
562
563
  })] })] : []),
563
564
  ] });
565
+ if (service === "ashby" && options.ashby) {
566
+ const run = options.ashby;
567
+ return defineGroup({ ...group, description: "Read your interviews and sync feedback drafts.", children: [...group.children,
568
+ ...([["interviews","List your upcoming interviews."],["pending","List interviews awaiting your feedback."],["latest","Read your most recently submitted feedback."]] as const).map(([name,description])=>defineCommand({
569
+ name,description,params:S.Object({}),handler:()=>userFacing(()=>run(name)),render:render<string>(v=>v),
570
+ })),
571
+ ...([["prep","Read the interview briefing and candidate background."],["template","Print your editable Markdown feedback draft."]] as const).map(([name,description])=>defineCommand({
572
+ name,description,positional:["url"],params:S.Object({url:S.String({description:"Interview briefing URL."})}),handler:({params})=>userFacing(()=>run(name,params.url)),render:render<string>(v=>v),
573
+ })),
574
+ defineCommand({name:"sync",description:"Save edited Markdown sections as drafts. Blank answers are skipped. Final submission is manual.",positional:["file"],params:S.Object({file:S.String({description:"Markdown file created with ashby template."})}),handler:({params})=>userFacing(()=>run("sync",params.file)),render:render<string>(v=>v)}),
575
+ ]});
576
+ }
564
577
  if (service === "zoom" && options.scrapeZoom) return defineGroup({ ...group, children: [...group.children, defineCommand({
565
578
  name: "scrape", scope: ["cli"], description: "Sync available Zoom Hub transcripts into ./zoom without deleting existing files.", params: S.Object({}),
566
579
  handler: () => userFacing(options.scrapeZoom!),
package/src/auth.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { parsePastedCookieMetadata, parsePastedCookies, type ChromeCookieExtraction, type ChromeCookieResult, type Cookie, type NodeEnvironment, type RuntimeCapabilities } from "wire-core";
2
2
 
3
- export type AuthService = "asana" | "chatgpt" | "gmail" | "google-docs" | "notion" | "slack" | "zoom";
3
+ import { ashbySession } from "./adapters/ashby.js";
4
+
5
+ export type AuthService = "ashby" | "asana" | "chatgpt" | "gmail" | "google-docs" | "notion" | "slack" | "zoom";
4
6
  export type CookieAuthService = AuthService;
5
7
 
6
8
  export interface AuthResult {
@@ -227,6 +229,7 @@ export interface Auth {
227
229
  readonly status: (service: AuthService) => Promise<AuthResult>;
228
230
  readonly pasteCookies: (service: AuthService, contents: string) => Promise<AuthResult>;
229
231
  readonly logout: (service: AuthService) => Promise<{ readonly service: AuthService; readonly deleted: true }>;
232
+ readonly extractAshby: () => Promise<AuthResult>;
230
233
  readonly extractAsana: () => Promise<AuthResult>;
231
234
  readonly extractChatgpt: () => Promise<AuthResult>;
232
235
  readonly extractGmail: () => Promise<AuthResult>;
@@ -239,8 +242,8 @@ export interface Auth {
239
242
  export type CookieExtractor = (environment: NodeEnvironment, extraction: ChromeCookieExtraction) => Promise<ChromeCookieResult>;
240
243
 
241
244
  export function composeAuth(runtime: RuntimeCapabilities, environment: NodeEnvironment, extractCookies: CookieExtractor): Auth {
242
- const cookieDomains: Readonly<Record<AuthService, string>> = Object.freeze({ asana: ".asana.com", chatgpt: ".chatgpt.com", gmail: ".google.com", "google-docs": ".google.com", notion: ".notion.so", slack: ".slack.com", zoom: ".zoom.us" });
243
- const verifyCookies = (service: AuthService, cookies: readonly Cookie[], metadata: Readonly<Record<string, string>>) => service === "asana" ? verifyAsana(runtime, cookies) : service === "chatgpt" ? verifyChatgpt(runtime, cookies) : service === "gmail" ? verifyGmailCookies(runtime, cookies) : service === "google-docs" ? verifyGoogleDocsCookies(runtime, cookies) : service === "notion" ? verifyNotion(runtime, cookies) : service === "slack" ? verifySlack(runtime, cookies, metadata) : verifyZoom(runtime, cookies);
245
+ const cookieDomains: Readonly<Record<AuthService, string>> = Object.freeze({ ashby: ".ashbyhq.com", asana: ".asana.com", chatgpt: ".chatgpt.com", gmail: ".google.com", "google-docs": ".google.com", notion: ".notion.so", slack: ".slack.com", zoom: ".zoom.us" });
246
+ const verifyCookies = (service: AuthService, cookies: readonly Cookie[], metadata: Readonly<Record<string, string>>) => service === "ashby" ? ashbySession(runtime,cookies).then(q=>q("query { sessionUser { id } }")).then(d=>d.sessionUser ? {service,identity:{user_id:d.sessionUser.id}} : null).catch(()=>null) : service === "asana" ? verifyAsana(runtime, cookies) : service === "chatgpt" ? verifyChatgpt(runtime, cookies) : service === "gmail" ? verifyGmailCookies(runtime, cookies) : service === "google-docs" ? verifyGoogleDocsCookies(runtime, cookies) : service === "notion" ? verifyNotion(runtime, cookies) : service === "slack" ? verifySlack(runtime, cookies, metadata) : verifyZoom(runtime, cookies);
244
247
  const verifyCookieState = async (service: AuthService, cookies: readonly Cookie[], metadata: Readonly<Record<string, string>>) => {
245
248
  if (service === "zoom") return verifyZoomCookieState(runtime, cookies, metadata);
246
249
  return Object.freeze({ result: await verifyCookies(service, cookies, metadata), cookies, metadata, changed: false });
@@ -286,6 +289,7 @@ export function composeAuth(runtime: RuntimeCapabilities, environment: NodeEnvir
286
289
  await runtime.cookies.delete(service);
287
290
  return Object.freeze({ service, deleted: true });
288
291
  },
292
+ extractAshby: () => extract("ashby", "https://app.ashbyhq.com/", ["ashbyhq.com"], values => values.length > 0),
289
293
  extractAsana: () => extract("asana", "https://app.asana.com/", ["asana.com"], (values) => values.some((cookie) => cookie.domain === ".asana.com" || cookie.domain.endsWith(".asana.com"))),
290
294
  extractChatgpt: () => extract("chatgpt", "https://chatgpt.com/", ["chatgpt.com", "openai.com"], (values) => values.some((cookie) => cookie.name === "oai-did") && values.some((cookie) => cookie.name === "__Secure-next-auth.session-token" || cookie.name === "__Secure-next-auth.session-token.0"), undefined, true),
291
295
  extractGmail: () => extract("gmail", "https://mail.google.com/mail/u/0/", ["google.com"], googleReady),
package/src/cli.ts CHANGED
@@ -120,7 +120,7 @@ const fixedCommandPositionals = Object.freeze({
120
120
  "sync-all": Object.freeze({ expected: 0, name: "" }),
121
121
  watch: Object.freeze({ expected: 1, name: "file" }),
122
122
  });
123
- const authServices = new Set(["asana", "chatgpt", "gmail", "google-docs", "notion", "slack", "zoom"]);
123
+ const authServices = new Set(["ashby", "asana", "chatgpt", "gmail", "google-docs", "notion", "slack", "zoom"]);
124
124
  const slackResourceCommands = new Set(["preview", "attach", "sync"]);
125
125
  const authCommands = new Set(["login", "logout", "status"]);
126
126
  const removedCommandNames = Object.freeze({
@@ -299,7 +299,7 @@ function renderRemovedCommand(argv: readonly string[]): boolean {
299
299
  function renderUnknownAuthCommand(argv: readonly string[]): boolean {
300
300
  if (hasRootSeparator(argv)) return false;
301
301
  const words = positionalWords(argv);
302
- if (words === null || words.length < 2 || !authServices.has(words[0]!) || authCommands.has(words[1]!) || (words[0] === "zoom" && words[1] === "scrape") || words[0] === "asana" && (words[1] === "projects" || words[1] === "tasks" || words[1] === "comments") || (words[0] === "slack" || words[0] === "notion" || words[0] === "asana") && words[1] === "users" || words[0] === "slack" && (words[1] === "send" || words[1] === "edit" || slackResourceCommands.has(words[1]!))) return false;
302
+ if (words === null || words.length < 2 || !authServices.has(words[0]!) || authCommands.has(words[1]!) || (words[0] === "ashby" && ["interviews","pending","latest","prep","template","sync"].includes(words[1]!)) || (words[0] === "zoom" && words[1] === "scrape") || words[0] === "asana" && (words[1] === "projects" || words[1] === "tasks" || words[1] === "comments") || (words[0] === "slack" || words[0] === "notion" || words[0] === "asana") && words[1] === "users" || words[0] === "slack" && (words[1] === "send" || words[1] === "edit" || slackResourceCommands.has(words[1]!))) return false;
303
303
  renderCliError(argv, `Unknown command: ${words[1]}`, `wire ${words[0]} --help`, `Unknown command: ${cliValue(words[1]!)}`);
304
304
  return true;
305
305
  }
package/src/executable.ts CHANGED
@@ -10,6 +10,7 @@ import { zoomProvider } from "provider-zoom";
10
10
  import { lookupNotionUsers } from "provider-notion";
11
11
 
12
12
  import { previewDrive, scrapeDrive } from "./adapters/gdrive.js";
13
+ import { ashby } from "./adapters/ashby.js";
13
14
  import { readAgenda } from "./adapters/calendar.js";
14
15
  import { createRoot } from "./adapters/root.js";
15
16
  import { composeAuth } from "./auth.js";
@@ -140,7 +141,7 @@ export function createExecutableRoot(environment: NodeEnvironment, currentDirect
140
141
  switchBackend: baseWire.switchBackend,
141
142
  });
142
143
  const wire = withWireHooks(configuredWire, { currentDirectory, home, environment: configuredEnvironment() });
143
- return createRoot(wire, currentDirectory, auth, readStandardInput, { ...options, previewDrive: url => previewDrive(runtime,url), scrapeDrive: url => scrapeDrive(runtime, currentDirectory, url), calendarAgenda: (date, id) => readAgenda(processCapability, configuration.get("WIRE_REPOSITORY_ROOT"), date, id), latticeSync: (url,file) => syncLatticeDrafts(runtime,url,currentDirectory,file), latticeRequests: url => listLatticeReviewRequests(runtime,url), latticeTemplate: url => latticeReviewDraft(runtime,url), latticeFill: async (url,file) => latticeReviewDraft(runtime,url,await runtime.filesystem.readText(resolve(currentDirectory,file))), scrapeZoom: () => zoomProvider.scrape(runtime, currentDirectory) }, (destination, markdown) => sendSlackMessage(runtime, destination, markdown), (query) => lookupSlackUsers(runtime, query), (url, markdown) => editSlackMessage(runtime, url, markdown), (query) => lookupNotionUsers(runtime, query), {
144
+ return createRoot(wire, currentDirectory, auth, readStandardInput, { ...options, ashby: (action,arg) => ashby(runtime,action,action === "sync" ? resolve(currentDirectory,arg!) : arg), previewDrive: url => previewDrive(runtime,url), scrapeDrive: url => scrapeDrive(runtime, currentDirectory, url), calendarAgenda: (date, id) => readAgenda(processCapability, configuration.get("WIRE_REPOSITORY_ROOT"), date, id), latticeSync: (url,file) => syncLatticeDrafts(runtime,url,currentDirectory,file), latticeRequests: url => listLatticeReviewRequests(runtime,url), latticeTemplate: url => latticeReviewDraft(runtime,url), latticeFill: async (url,file) => latticeReviewDraft(runtime,url,await runtime.filesystem.readText(resolve(currentDirectory,file))), scrapeZoom: () => zoomProvider.scrape(runtime, currentDirectory) }, (destination, markdown) => sendSlackMessage(runtime, destination, markdown), (query) => lookupSlackUsers(runtime, query), (url, markdown) => editSlackMessage(runtime, url, markdown), (query) => lookupNotionUsers(runtime, query), {
144
145
  lookup: (query) => lookupAsanaUsers(runtime, query), projects: () => listAsanaProjects(runtime), project: (project) => showAsanaProject(runtime, project), tasks: (project) => listAsanaTasks(runtime, project), show: (task) => showAsanaTask(runtime, task),
145
146
  writes: { move: (task, project, section) => moveAsanaTask(runtime, task, project, section), create: (project, title, section, body, assignee) => createAsanaTask(runtime, project, title, section, body, assignee), edit: (task, fields) => editAsanaTask(runtime, task, fields), comment: (task, body) => addAsanaComment(runtime, task, body), editComment: (comment, body) => editAsanaComment(runtime, comment, body) },
146
147
  }, async () => {