@springbrand/hr-cli 0.4.0 → 0.5.0-alpha.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/hr.js CHANGED
@@ -91,6 +91,22 @@ var Hr = class {
91
91
  patch(pathname, body) {
92
92
  return this.request(`${this.apiUrl}/api/v1${pathname}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
93
93
  }
94
+ put(pathname, body) {
95
+ return this.request(`${this.apiUrl}/api/v1${pathname}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
96
+ }
97
+ delete(pathname) {
98
+ return this.request(`${this.apiUrl}/api/v1${pathname}`, { method: "DELETE" });
99
+ }
100
+ /** multipart/form-data (resume uploads); the browser-style boundary is set by fetch. */
101
+ upload(pathname, form) {
102
+ return this.request(`${this.apiUrl}/api/v1${pathname}`, { method: "POST", body: form });
103
+ }
104
+ /** Fetches a signed file link HR handed out (it needs no credential) and returns its bytes. */
105
+ async download(url) {
106
+ const response = await this.send(url, {}, "the file link");
107
+ if (!response.ok) throw new CliError(`HTTP_${response.status}`, `The file link answered HTTP ${response.status}`);
108
+ return Buffer.from(await response.arrayBuffer());
109
+ }
94
110
  async request(url, init) {
95
111
  const token = await this.token();
96
112
  return unwrap(await this.send(url, { ...init, headers: { ...init.headers, Authorization: `Bearer ${token}` } }, "HR"), "HR");
@@ -116,110 +132,15 @@ var Hr = class {
116
132
  }
117
133
  };
118
134
 
119
- // src/login.ts
120
- import { createHash, randomBytes } from "node:crypto";
121
- import { createServer } from "node:http";
122
- var TimeoutMs = 5 * 60 * 1e3;
123
- var page = (text) => `<!doctype html><meta charset="utf-8"><title>SpringBrand HR</title><p style="font:16px system-ui;margin:4rem;text-align:center">${text}</p>`;
124
- async function login(hr, deps, openBrowser2 = true) {
125
- const state = randomBytes(24).toString("base64url");
126
- const verifier = randomBytes(32).toString("base64url");
127
- const challenge = createHash("sha256").update(verifier).digest("base64url");
128
- const { appOrigin } = await hr.config();
129
- let settle = () => void 0;
130
- const received = new Promise((resolve) => settle = resolve);
131
- const server = createServer((request, response) => {
132
- const url = new URL(request.url ?? "/", "http://127.0.0.1");
133
- if (url.pathname !== "/callback") return response.writeHead(404).end();
134
- const code = url.searchParams.get("code");
135
- const valid = Boolean(code) && url.searchParams.get("state") === state;
136
- response.writeHead(valid ? 200 : 400, { "Content-Type": "text/html; charset=utf-8", Connection: "close" }).end(page(valid ? "\u767B\u5F55\u6210\u529F\uFF0C\u53EF\u4EE5\u5173\u95ED\u8FD9\u4E2A\u9875\u9762\u3002Signed in. You can close this page." : "\u767B\u5F55\u5931\u8D25\u3002Sign-in failed."));
137
- settle(valid ? code : new CliError("LOGIN_FAILED", "The browser sent back an invalid sign-in"));
138
- });
139
- await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
140
- const timer = setTimeout(() => settle(new CliError("LOGIN_TIMEOUT", "Nobody approved the sign-in within 5 minutes")), TimeoutMs);
141
- try {
142
- const target = new URL(`${appOrigin}/cli-login`);
143
- target.searchParams.set("port", String(server.address().port));
144
- target.searchParams.set("state", state);
145
- target.searchParams.set("challenge", challenge);
146
- deps.stderr(`Approve the sign-in in your browser: ${target}`);
147
- if (openBrowser2) deps.openBrowser(target.toString());
148
- const result = await received;
149
- if (result instanceof Error) throw result;
150
- return await hr.redeem(result, verifier);
151
- } finally {
152
- clearTimeout(timer);
153
- server.closeAllConnections();
154
- server.close();
155
- }
156
- }
157
-
158
- // src/resolve.ts
159
- var Uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
160
- var isId = (value) => Uuid.test(value);
161
- function pickOne(items, query, names, describe, what) {
162
- const wanted = query.trim().toLowerCase();
163
- const values = (item) => names(item).filter(Boolean).map((name) => name.toLowerCase());
164
- const exact = items.filter((item) => values(item).includes(wanted));
165
- const matches = exact.length ? exact : items.filter((item) => values(item).some((name) => name.includes(wanted)));
166
- if (matches.length === 1) return matches[0];
167
- if (!matches.length) throw new CliError("NOT_FOUND", `No ${what} matches "${query}"`, { candidates: items.slice(0, 20).map(describe) });
168
- throw new CliError("AMBIGUOUS", `${matches.length} ${what}s match "${query}"; use an id or narrow it down`, { candidates: matches.slice(0, 20).map(describe) });
169
- }
170
-
171
- // src/run.ts
172
- var Commands = [
173
- { usage: "hr login [--no-browser] | logout", does: "Sign a person in or out. Agents use HR_AGENT_KEY instead.", returns: "login: data: { name, expiresAt }. logout: data: { signedOut }." },
174
- { usage: "hr whoami", does: "Who the caller is.", returns: "data: { principalId, name, kind, permissions[] }. permissions are HR action codes such as recruit:talent:view." },
175
- { usage: "hr jobs list [--status open|paused|draft|closed]", does: "Jobs, open ones first.", returns: "data: [{ id, title, slug, status, counts: { active, hired, rejected, withdrawn } }]. counts are applications per job." },
176
- {
177
- usage: "hr talents search [text] [--job <job>] [--page n] [--page-size n]",
178
- does: "Talents in the pool, optionally matching text (name, headline, contact) or applying to a job. Page size defaults to 50, at most 200.",
179
- returns: "data: { total, items: [{ id, displayName, headline, status, tags, skills, applicationCount, jobTitles, bestScore, url }] }. total counts every match, not just this page.",
180
- example: "hr talents search --page-size 1 # data.total is the size of the pool"
181
- },
182
- { usage: "hr talents show <name|id>", does: "One talent with contacts (when the caller may see them), documents, skills and applications.", returns: "data: { id, displayName, \u2026, url, applications: [{ id, jobTitle, stageName, status, url }] }" },
183
- { usage: "hr screening list [--job <job>]", does: "Applications waiting for screening.", returns: "data: { total, items: [{ id, talentName, jobTitle, stageName, url }] }. total is how many are waiting." },
184
- { usage: "hr screening pass <name|id> [--job <job>]", does: "Pass a candidate waiting for screening to the next stage.", returns: "data: the updated application, or data.pendingApproval (see below)." },
185
- { usage: "hr screening reject <name|id> --reason <reason> [--job <job>]", does: "Reject a candidate waiting for screening. <reason> comes from `hr reasons list`.", returns: "data: the updated application, or data.pendingApproval (see below)." },
186
- { usage: "hr interviews to-schedule [--job <job>] [--page n] [--page-size n]", does: "Candidates in an interview stage with no interview booked.", returns: "data: { total, items: [{ id, talentName, jobTitle, stageName, url }] }" },
187
- {
188
- usage: "hr interviews schedule <name|id> --start <time> [--end <time> | --minutes n] [--location text] [--with <people>] [--job <job>]",
189
- does: "Book an interview for a candidate waiting in `hr interviews to-schedule` (or an application id). <time> is ISO 8601 with its UTC offset, such as 2026-11-12T15:00+08:00. Length defaults to 60 minutes. <people> are interviewers, comma-separated names, emails or ids from `hr people search`; a person calling may leave it out to interview alone, an Agent must pass it. HR only records the interview: it puts nothing on any calendar.",
190
- returns: "data: { id, applicationId, round, status, startsAt, endsAt, locationOrLink, participants: [{ principalId, submitted }], talentName, jobTitle, url }. Times are UTC.",
191
- example: 'hr interviews schedule "Li Wei" --start 2026-11-12T15:00+08:00 --with "Rita Tan" --location "Room 3"'
192
- },
193
- { usage: "hr interviews list <application id>", does: "Every interview of one application, latest first.", returns: "data: [{ id, applicationId, round, status, startsAt, endsAt, locationOrLink, participants: [{ principalId, submitted }], url }]. Times are UTC." },
194
- { usage: "hr interviews reschedule <interview id> [--start <time>] [--end <time> | --minutes n] [--location text]", does: "Move or relocate an interview. A new --start keeps the length unless --end or --minutes is given.", returns: "data: { id, applicationId, round, status, startsAt, endsAt, locationOrLink, participants: [{ principalId, submitted }], talentName, jobTitle, url }. Times are UTC." },
195
- { usage: "hr interviews cancel <interview id>", does: "Cancel an interview.", returns: "data: { id, applicationId, round, status, startsAt, endsAt, locationOrLink, participants: [{ principalId, submitted }], talentName, jobTitle, url }. Times are UTC." },
196
- { usage: "hr people search <name>", does: "People (not Agents) in the organization, to name interviewers.", returns: "data: [{ id, name, email, jobTitle }]" },
197
- { usage: "hr reasons list", does: "Reject reasons.", returns: "data: [{ id, name, category }]. Rejecting uses those with category we_rejected." },
198
- { usage: "hr approvals status <id> [--wait] [--timeout seconds]", does: "Where an approval stands; --wait polls until it is decided or the timeout (default 300) passes.", returns: "data: { status: pending | executed | rejected | failed, error? }" }
199
- ];
200
- var Overall = `hr: SpringBrand HR from the command line. Output is JSON on stdout.
201
-
202
- Setup
203
- HR_API_URL this deployment's HR address (or --api-url)
204
- HR_AGENT_KEY an Agent key from IAM; without it, run \`hr login\`
205
- IAM_URL optional; by default HR says where IAM is
206
-
207
- Commands (\`hr <command> --help\` shows what one returns)
208
- ${Commands.map((command) => ` ${command.usage}`).join("\n")}
209
-
210
- Every command prints { ok: true, data } or { ok: false, error: { code, message } }.
211
- <job> is a title, slug or id. Talents and applications carry url, their page in the HR console.
212
- A command without the permission answers with data.pendingApproval: the action waits for a person to decide in IAM.`;
213
- function helpFor(args) {
214
- const words = args.filter((arg) => !arg.startsWith("-")).slice(0, 2).join(" ");
215
- const command = words && Commands.find((entry) => entry.usage.startsWith(`hr ${words}`));
216
- if (!command) return Overall;
217
- return [`${command.usage}`, "", command.does, "", `Returns ${command.returns}`, ...command.example ? ["", `Example: ${command.example}`] : []].join("\n");
218
- }
219
- var options = {
135
+ // src/command.ts
136
+ import { readFile as readFile2 } from "node:fs/promises";
137
+ var Options = {
220
138
  "api-url": { type: "string" },
139
+ help: { type: "boolean", short: "h" },
140
+ json: { type: "string" },
221
141
  job: { type: "string" },
222
142
  status: { type: "string" },
143
+ stage: { type: "string" },
223
144
  reason: { type: "string" },
224
145
  page: { type: "string" },
225
146
  "page-size": { type: "string" },
@@ -229,10 +150,96 @@ var options = {
229
150
  start: { type: "string" },
230
151
  end: { type: "string" },
231
152
  minutes: { type: "string" },
232
- location: { type: "string" },
153
+ online: { type: "string" },
154
+ code: { type: "string" },
155
+ offline: { type: "string" },
233
156
  with: { type: "string" },
234
- help: { type: "boolean", short: "h" }
157
+ subject: { type: "string" },
158
+ body: { type: "string" },
159
+ application: { type: "string" },
160
+ verdict: { type: "string" },
161
+ summary: { type: "string" },
162
+ intent: { type: "string" },
163
+ force: { type: "boolean" },
164
+ mail: { type: "boolean" },
165
+ source: { type: "string" },
166
+ note: { type: "string" },
167
+ referrer: { type: "string" },
168
+ file: { type: "string", multiple: true },
169
+ out: { type: "string" },
170
+ name: { type: "string" },
171
+ color: { type: "string" },
172
+ description: { type: "string" },
173
+ rating: { type: "string" },
174
+ kind: { type: "string" },
175
+ value: { type: "string" },
176
+ tag: { type: "string" },
177
+ pool: { type: "string" },
178
+ skill: { type: "string" },
179
+ q: { type: "string" },
180
+ from: { type: "string" },
181
+ to: { type: "string" },
182
+ mailbox: { type: "string" },
183
+ classification: { type: "string" },
184
+ talent: { type: "string" },
185
+ batch: { type: "string" },
186
+ confirm: { type: "boolean" },
187
+ url: { type: "string" },
188
+ backfill: { type: "string" },
189
+ "backfill-from": { type: "string" },
190
+ interviewing: { type: "boolean" },
191
+ stale: { type: "boolean" },
192
+ historical: { type: "boolean" },
193
+ queue: { type: "string" },
194
+ location: { type: "string" },
195
+ recruiter: { type: "string" },
196
+ keywords: { type: "string" },
197
+ template: { type: "string" },
198
+ password: { type: "string" },
199
+ address: { type: "string" },
200
+ preset: { type: "string" }
235
201
  };
202
+ function needed(name, value) {
203
+ if (!value) throw new CliError("USAGE", `Missing ${name}. Run \`hr --help\``);
204
+ return value;
205
+ }
206
+ var joined = (ctx, name) => needed(name, ctx.args.join(" ").trim() || void 0);
207
+ async function jsonInput(ctx) {
208
+ const raw = ctx.values.json;
209
+ if (!raw) return {};
210
+ const text = raw.startsWith("@") ? await readFile2(raw.slice(1), "utf8").catch(() => Promise.reject(new CliError("USAGE", `Cannot read ${raw.slice(1)}`))) : raw;
211
+ try {
212
+ const value = JSON.parse(text);
213
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("not an object");
214
+ return value;
215
+ } catch {
216
+ throw new CliError("USAGE", "--json takes a JSON object, or @path to a file holding one");
217
+ }
218
+ }
219
+ async function bodyOf(ctx, flags = {}) {
220
+ return { ...await jsonInput(ctx), ...Object.fromEntries(Object.entries(flags).filter(([, value]) => value !== void 0)) };
221
+ }
222
+ function oneOf(flag, value, allowed) {
223
+ if (value !== void 0 && !allowed.includes(value)) throw new CliError("USAGE", `${flag} is one of ${allowed.join(", ")}`);
224
+ return value;
225
+ }
226
+ var list = (value) => value?.split(",").map((item) => item.trim()).filter(Boolean);
227
+ var takesJson = (fields) => ` Other fields go in --json (an object, or @file): ${fields}.`;
228
+
229
+ // src/resolve.ts
230
+ var Uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
231
+ var isId = (value) => Uuid.test(value);
232
+ function pickOne(items, query, names, describe2, what) {
233
+ const wanted = query.trim().toLowerCase();
234
+ const values = (item) => names(item).filter(Boolean).map((name) => name.toLowerCase());
235
+ const exact = items.filter((item) => values(item).includes(wanted));
236
+ const matches = exact.length ? exact : items.filter((item) => values(item).some((name) => name.includes(wanted)));
237
+ if (matches.length === 1) return matches[0];
238
+ if (!matches.length) throw new CliError("NOT_FOUND", `No ${what} matches "${query}"`, { candidates: items.slice(0, 20).map(describe2) });
239
+ throw new CliError("AMBIGUOUS", `${matches.length} ${what}s match "${query}"; use an id or narrow it down`, { candidates: matches.slice(0, 20).map(describe2) });
240
+ }
241
+
242
+ // src/lookup.ts
236
243
  async function linked(hr, records, page2) {
237
244
  const origin = await hr.appOrigin();
238
245
  return records.map((record) => ({ ...record, url: `${origin}/${page2}/${record.id}` }));
@@ -240,27 +247,58 @@ async function linked(hr, records, page2) {
240
247
  async function linkedPage(hr, result, page2) {
241
248
  return { ...result, items: await linked(hr, result.items, page2) };
242
249
  }
243
- async function linkedTalent(hr, id) {
244
- const talent = await hr.get(`/talents/${id}`);
245
- const [withUrl] = await linked(hr, [talent], "talents");
246
- return { ...withUrl, ...talent.applications ? { applications: await linked(hr, talent.applications, "applications") } : {} };
250
+ async function linkedOne(hr, record, page2) {
251
+ return (await linked(hr, [record], page2))[0];
247
252
  }
248
253
  async function jobId(hr, job) {
249
254
  if (!job || isId(job)) return job;
250
255
  const jobs = await hr.get("/jobs");
251
256
  return pickOne(jobs, job, (entry) => [entry.slug, entry.title], (entry) => ({ id: entry.id, title: entry.title, status: entry.status }), "job").id;
252
257
  }
253
- var screeningQueue = async (hr, job) => hr.get("/applications", { queue: "screening", jobId: await jobId(hr, job), pageSize: 200 });
254
- async function screeningApplication(hr, who, job) {
258
+ async function requiredJob(hr, job) {
259
+ const id = await jobId(hr, job);
260
+ if (!id) throw new CliError("USAGE", "Pass the job (title, slug or id)");
261
+ return id;
262
+ }
263
+ async function talentId(hr, who) {
264
+ if (isId(who)) return who;
265
+ const found = await hr.get("/talents", { q: who, pageSize: 50 });
266
+ return pickOne(found.items, who, (item) => [item.displayName], (item) => ({ id: item.id, name: item.displayName, headline: item.headline }), "talent").id;
267
+ }
268
+ async function applicationId(hr, who, filters = {}) {
255
269
  if (isId(who)) return who;
256
- const queue = await screeningQueue(hr, job);
257
- return pickOne(queue.items, who, (item) => [item.talentName], (item) => ({ id: item.id, talent: item.talentName, job: item.jobTitle }), "candidate waiting for screening").id;
270
+ const result = await hr.get("/applications", { ...filters.queue ? { queue: filters.queue } : { status: "active" }, jobId: await jobId(hr, filters.job), pageSize: 200 });
271
+ const what = filters.queue === "screening" ? "candidate waiting for screening" : filters.queue === "to_schedule" ? "candidate waiting for an interview" : "active application";
272
+ return pickOne(result.items, who, (item) => [item.talentName], (item) => ({ id: item.id, talent: item.talentName, job: item.jobTitle, stage: item.stageName }), what).id;
258
273
  }
259
- async function rejectReason(hr, reason) {
274
+ async function stageId(hr, application, stage) {
275
+ if (isId(stage)) return stage;
276
+ const detail = await hr.get(`/applications/${application}`);
277
+ return pickOne(detail.job.stages, stage, (entry) => [entry.name, entry.category], (entry) => ({ id: entry.id, name: entry.name, category: entry.category }), "stage").id;
278
+ }
279
+ async function rejectReason(hr, reason, category = "we_rejected") {
260
280
  if (!reason) throw new CliError("USAGE", "Pass --reason; `hr reasons list` shows them");
261
281
  if (isId(reason)) return reason;
262
- const reasons = (await hr.get("/reject-reasons")).filter((entry) => entry.category === "we_rejected");
263
- return pickOne(reasons, reason, (entry) => [entry.name], (entry) => ({ id: entry.id, name: entry.name }), "reject reason").id;
282
+ const reasons = (await hr.get("/reject-reasons")).filter((entry) => !category || entry.category === category);
283
+ return pickOne(reasons, reason, (entry) => [entry.name], (entry) => ({ id: entry.id, name: entry.name, category: entry.category }), "reject reason").id;
284
+ }
285
+ async function namedId(hr, path3, value, what) {
286
+ if (isId(value)) return value;
287
+ const rows = await hr.get(path3);
288
+ return pickOne(rows, value, (row) => [row.name], (row) => ({ id: row.id, name: row.name }), what).id;
289
+ }
290
+ var people = async (hr) => (await hr.get("/people")).filter((person) => person.type === "human");
291
+ var describePerson = (person) => ({ id: person.id, name: person.displayName, email: person.email, jobTitle: person.jobTitle });
292
+ async function personId(hr, name) {
293
+ if (isId(name)) return name;
294
+ return pickOne(await people(hr), name, (person) => [person.displayName, person.email], describePerson, "person").id;
295
+ }
296
+ async function personIds(hr, names) {
297
+ if (!names) return void 0;
298
+ const list2 = names.split(",").map((name) => name.trim()).filter(Boolean);
299
+ if (list2.every(isId)) return list2;
300
+ const everyone = await people(hr);
301
+ return list2.map((name) => isId(name) ? name : pickOne(everyone, name, (person) => [person.displayName, person.email], describePerson, "person").id);
264
302
  }
265
303
  function time(value, flag) {
266
304
  const date = new Date(value);
@@ -282,26 +320,144 @@ function slot(values, current) {
282
320
  const endsAt = values.end ? time(values.end, "--end") : new Date(startsAt.getTime() + length * 6e4);
283
321
  return { startsAt: startsAt.toISOString(), endsAt: endsAt.toISOString() };
284
322
  }
285
- var people = async (hr) => (await hr.get("/people")).filter((person) => person.type === "human");
286
- var describePerson = (person) => ({ id: person.id, name: person.displayName, email: person.email, jobTitle: person.jobTitle });
287
- async function interviewers(hr, names) {
288
- if (!names) {
289
- const me = await hr.get("/me");
290
- if (me.kind !== "human") throw new CliError("USAGE", "Say who interviews: pass --with with names from `hr people search`");
291
- return [me.principalId];
292
- }
293
- const everyone = await people(hr);
294
- return names.split(",").map((name) => name.trim()).filter(Boolean).map((name) => isId(name) ? name : pickOne(everyone, name, (person) => [person.displayName, person.email], describePerson, "person").id);
295
- }
296
- async function toScheduleApplication(hr, who, job) {
297
- if (isId(who)) return who;
298
- const queue = await hr.get("/applications", { queue: "to_schedule", jobId: await jobId(hr, job), pageSize: 200 });
299
- return pickOne(queue.items, who, (item) => [item.talentName], (item) => ({ id: item.id, talent: item.talentName, job: item.jobTitle }), "candidate waiting for an interview").id;
323
+ function place(values) {
324
+ if (values.online && values.offline) throw new CliError("USAGE", "Pass --online or --offline, not both");
325
+ if (values.code && !values.online) throw new CliError("USAGE", "--code goes with --online");
326
+ if (values.online) return { mode: "online", meetingUrl: values.online, ...values.code ? { meetingCode: values.code } : {} };
327
+ if (values.offline) return { mode: "offline", address: values.offline };
328
+ return void 0;
300
329
  }
301
- async function described(hr, interview) {
302
- const detail = await hr.get(`/applications/${interview.applicationId}`);
303
- return { ...interview, talentName: detail.talent.displayName, jobTitle: detail.job.title, url: `${await hr.appOrigin()}/applications/${interview.applicationId}` };
330
+
331
+ // src/commands/applications.ts
332
+ var ApplicationReturns = "data: the updated application { id, talentId, jobId, stageId, status, \u2026 }, or data.pendingApproval (see below).";
333
+ var Statuses = ["active", "hired", "rejected", "withdrawn"];
334
+ var applicationCommands = [
335
+ {
336
+ name: "applications list",
337
+ usage: "hr applications list [--job <job>] [--status active|hired|rejected|withdrawn] [--queue screening|to_schedule] [--talent <name|id>] [--interviewing] [--stale] [--historical] [--page n] [--page-size n]",
338
+ does: "Applications, best final score first. --interviewing: only those the caller interviews. --stale: past their stage's time limit. --historical: backfilled from old mail.",
339
+ returns: "data: { total, items: [{ id, talentName, talentHeadline, rating, jobTitle, stageName, stageCategory, status, aiScore, humanScore, finalScore, pendingReplies, isStale, url }] }",
340
+ run: async ({ hr, values, page: page2 }) => {
341
+ const query = {
342
+ jobId: await jobId(hr, values.job),
343
+ status: oneOf("--status", values.status, Statuses),
344
+ queue: oneOf("--queue", values.queue, ["screening", "to_schedule"]),
345
+ talentId: values.talent ? await talentId(hr, values.talent) : void 0,
346
+ interviewing: values.interviewing ? "true" : void 0,
347
+ stale: values.stale ? "true" : void 0,
348
+ historical: values.historical ? "true" : void 0,
349
+ ...page2
350
+ };
351
+ return linkedPage(hr, await hr.get("/applications", query), "applications");
352
+ }
353
+ },
354
+ {
355
+ name: "applications show",
356
+ usage: "hr applications show <name|id> [--job <job>]",
357
+ does: "One application: the talent, the job and its stages, the stage history, interviews, evaluations the caller may see, missing evaluations and unanswered replies.",
358
+ returns: "data: { access, application, job: { stages }, currentStage, talent, history, interviews, evaluations, missingEvaluations, pendingReplies, url }",
359
+ run: async (ctx) => {
360
+ const id = await applicationId(ctx.hr, joined(ctx, "a candidate or application id"), { job: ctx.values.job });
361
+ return { ...await ctx.hr.get(`/applications/${id}`), url: (await linkedOne(ctx.hr, { id }, "applications")).url };
362
+ }
363
+ },
364
+ {
365
+ name: "applications add",
366
+ usage: "hr applications add <talent name|id> --job <job>",
367
+ does: "Put a talent from the pool forward for a job (a new application in its first stage), and run AI screening.",
368
+ returns: "data: the new application, with url.",
369
+ run: async (ctx) => {
370
+ const talent = await talentId(ctx.hr, joined(ctx, "a talent"));
371
+ const application = await ctx.hr.post(`/talents/${talent}/applications`, { jobId: await requiredJob(ctx.hr, ctx.values.job), screen: true });
372
+ return linkedOne(ctx.hr, application, "applications");
373
+ }
374
+ },
375
+ {
376
+ name: "applications move",
377
+ usage: "hr applications move <name|id> --stage <stage> [--reason <text>] [--force] [--job <job>]",
378
+ does: "Move an application to another stage of its pipeline (by name or id, from `hr applications show`), forward or back. The stage's own actions run (its mail, interview settings\u2026). Leaving a stage that needs evaluations waits for them; --force (job managers) moves anyway and is recorded. Rejecting and withdrawing have their own commands.",
379
+ returns: ApplicationReturns,
380
+ run: async (ctx) => {
381
+ const id = await applicationId(ctx.hr, joined(ctx, "a candidate or application id"), { job: ctx.values.job });
382
+ const stage = await stageId(ctx.hr, id, needed("--stage", ctx.values.stage));
383
+ return ctx.hr.post(`/applications/${id}/move`, { stageId: stage, reason: ctx.values.reason ?? null, ...ctx.values.force ? { force: true } : {} });
384
+ }
385
+ },
386
+ {
387
+ name: "applications reject",
388
+ usage: "hr applications reject <name|id> --reason <reason> [--subject <text> --body <text>] [--job <job>]",
389
+ does: "Reject an application at any stage, with a reason from `hr reasons list` (a \"candidate declined\" reason withdraws it instead). --subject and --body mail the candidate that rejection letter (edit the reason's template; `hr mail draft` can help); without them the rejected stage's own mail, if any, goes out.",
390
+ returns: `${ApplicationReturns} mailError / archiveError say what failed after the rejection.`,
391
+ run: async (ctx) => {
392
+ const id = await applicationId(ctx.hr, joined(ctx, "a candidate or application id"), { job: ctx.values.job });
393
+ if (Boolean(ctx.values.subject) !== Boolean(ctx.values.body)) throw new CliError("USAGE", "A rejection mail needs both --subject and --body");
394
+ const mail = ctx.values.subject && ctx.values.body ? { subject: ctx.values.subject, body: ctx.values.body } : null;
395
+ return ctx.hr.post(`/applications/${id}/reject`, { reasonId: await rejectReason(ctx.hr, ctx.values.reason, null), mail });
396
+ }
397
+ },
398
+ {
399
+ name: "applications withdraw",
400
+ usage: "hr applications withdraw <name|id> [--job <job>]",
401
+ does: "The candidate is no longer coming: close the application as withdrawn.",
402
+ returns: ApplicationReturns,
403
+ run: async (ctx) => ctx.hr.post(`/applications/${await applicationId(ctx.hr, joined(ctx, "a candidate or application id"), { job: ctx.values.job })}/withdraw`, {})
404
+ },
405
+ {
406
+ name: "applications reopen",
407
+ usage: "hr applications reopen <application id>",
408
+ does: "Reconsider a closed (rejected, withdrawn) application: back to the first stage.",
409
+ returns: ApplicationReturns,
410
+ run: ({ hr, args }) => hr.post(`/applications/${needed("an application id", args[0])}/reopen`, {})
411
+ },
412
+ {
413
+ name: "applications screen",
414
+ usage: "hr applications screen <name|id> [--job <job>]",
415
+ does: "Run AI screening again on the job's scorecard (the resume or the scorecard changed). Earlier screenings are kept. Takes up to a few minutes.",
416
+ returns: "data: the new ai_screen evaluation { overallScore, recommendation, summary, questions, items }, or null when the job has no scorecard.",
417
+ run: async (ctx) => ctx.hr.post(`/applications/${await applicationId(ctx.hr, joined(ctx, "a candidate or application id"), { job: ctx.values.job })}/screen`, {})
418
+ }
419
+ ];
420
+
421
+ // src/login.ts
422
+ import { createHash, randomBytes } from "node:crypto";
423
+ import { createServer } from "node:http";
424
+ var TimeoutMs = 5 * 60 * 1e3;
425
+ var page = (text) => `<!doctype html><meta charset="utf-8"><title>SpringBrand HR</title><p style="font:16px system-ui;margin:4rem;text-align:center">${text}</p>`;
426
+ async function login(hr, deps, openBrowser2 = true) {
427
+ const state = randomBytes(24).toString("base64url");
428
+ const verifier = randomBytes(32).toString("base64url");
429
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
430
+ const { appOrigin } = await hr.config();
431
+ let settle = () => void 0;
432
+ const received = new Promise((resolve) => settle = resolve);
433
+ const server = createServer((request, response) => {
434
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
435
+ if (url.pathname !== "/callback") return response.writeHead(404).end();
436
+ const code = url.searchParams.get("code");
437
+ const valid = Boolean(code) && url.searchParams.get("state") === state;
438
+ response.writeHead(valid ? 200 : 400, { "Content-Type": "text/html; charset=utf-8", Connection: "close" }).end(page(valid ? "\u767B\u5F55\u6210\u529F\uFF0C\u53EF\u4EE5\u5173\u95ED\u8FD9\u4E2A\u9875\u9762\u3002Signed in. You can close this page." : "\u767B\u5F55\u5931\u8D25\u3002Sign-in failed."));
439
+ settle(valid ? code : new CliError("LOGIN_FAILED", "The browser sent back an invalid sign-in"));
440
+ });
441
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
442
+ const timer = setTimeout(() => settle(new CliError("LOGIN_TIMEOUT", "Nobody approved the sign-in within 5 minutes")), TimeoutMs);
443
+ try {
444
+ const target = new URL(`${appOrigin}/cli-login`);
445
+ target.searchParams.set("port", String(server.address().port));
446
+ target.searchParams.set("state", state);
447
+ target.searchParams.set("challenge", challenge);
448
+ deps.stderr(`Approve the sign-in in your browser: ${target}`);
449
+ if (openBrowser2) deps.openBrowser(target.toString());
450
+ const result = await received;
451
+ if (result instanceof Error) throw result;
452
+ return await hr.redeem(result, verifier);
453
+ } finally {
454
+ clearTimeout(timer);
455
+ server.closeAllConnections();
456
+ server.close();
457
+ }
304
458
  }
459
+
460
+ // src/commands/core.ts
305
461
  async function approvalStatus(hr, deps, id, wait, timeoutSeconds) {
306
462
  const deadline = Date.now() + timeoutSeconds * 1e3;
307
463
  for (; ; ) {
@@ -310,73 +466,965 @@ async function approvalStatus(hr, deps, id, wait, timeoutSeconds) {
310
466
  await deps.sleep(5e3);
311
467
  }
312
468
  }
313
- async function dispatch(args, deps) {
314
- const { values, positionals } = parseArgs({ args, options, allowPositionals: true });
315
- const [group, action, ...rest] = positionals;
316
- const hr = new Hr(deps, values["api-url"]);
317
- const page2 = { page: values.page, pageSize: values["page-size"] };
318
- const needed = (name, value) => {
319
- if (!value) throw new CliError("USAGE", `Missing ${name}. Run \`hr --help\``);
320
- return value;
469
+ var coreCommands = [
470
+ {
471
+ name: "login",
472
+ usage: "hr login [--no-browser]",
473
+ does: "Sign a person in through the browser. Agents use HR_AGENT_KEY instead.",
474
+ returns: "data: { name, expiresAt }",
475
+ run: ({ hr, deps, values }) => login(hr, deps, !values["no-browser"])
476
+ },
477
+ { name: "logout", usage: "hr logout", does: "Forget this machine's sign-in.", returns: "data: { signedOut }", run: ({ hr }) => hr.logout() },
478
+ {
479
+ name: "whoami",
480
+ usage: "hr whoami",
481
+ does: "Who the caller is.",
482
+ returns: "data: { principalId, name, kind, permissions[] }. permissions are HR action codes such as recruit:talent:view.",
483
+ run: ({ hr }) => hr.get("/me")
484
+ },
485
+ {
486
+ name: "people search",
487
+ usage: "hr people search [name]",
488
+ does: "People (not Agents) in the organization, to name interviewers, owners and referrers.",
489
+ returns: "data: [{ id, name, email, jobTitle }]",
490
+ run: async ({ hr, args }) => {
491
+ const wanted = args.join(" ").trim().toLowerCase();
492
+ return (await people(hr)).filter((person) => !wanted || [person.displayName, person.email].some((value) => value?.toLowerCase().includes(wanted))).map(describePerson);
493
+ }
494
+ },
495
+ {
496
+ name: "people show",
497
+ usage: "hr people show <id>",
498
+ does: "One person or Agent from IAM.",
499
+ returns: "data: { id, type, displayName, email, jobTitle, departments, \u2026 }",
500
+ run: ({ hr, args }) => hr.get(`/people/${needed("a person id", args[0])}`)
501
+ },
502
+ {
503
+ name: "approvals status",
504
+ usage: "hr approvals status <id> [--wait] [--timeout seconds]",
505
+ does: "Where an approval stands; --wait polls until it is decided or the timeout (default 300) passes.",
506
+ returns: "data: { status: pending | executed | rejected | failed, error? }",
507
+ run: ({ hr, deps, args, values }) => approvalStatus(hr, deps, needed("an approval id", args[0]), Boolean(values.wait), Number(values.timeout ?? 300))
508
+ }
509
+ ];
510
+
511
+ // src/commands/jobs.ts
512
+ var JobStatuses = ["draft", "open", "paused", "closed"];
513
+ var EmploymentTypes = ["full_time", "part_time", "contract", "intern"];
514
+ var JobFields = "slug, departmentId, hiringManagerPrincipalId, recruiterPrincipalId, headcount, location, descriptionMd, pipelineId, scorecardId, keywords [], requiredDegree, skills [{ name, level 1-10 }], members [{ principalId, role interviewer|viewer }]";
515
+ var JobReturns = "data: the job { id, title, slug, status, employmentType, pipelineId, scorecardId, stages, members, skills, \u2026 } with url.";
516
+ async function jobFlags(ctx) {
517
+ const { hr, values } = ctx;
518
+ const interviewers = await personIds(hr, values.with);
519
+ return {
520
+ title: values.name,
521
+ status: oneOf("--status", values.status, JobStatuses),
522
+ employmentType: oneOf("--kind", values.kind, EmploymentTypes),
523
+ location: values.location,
524
+ descriptionMd: values.description,
525
+ recruiterPrincipalId: values.recruiter ? await personId(hr, values.recruiter) : void 0,
526
+ keywords: list(values.keywords),
527
+ ...interviewers ? { members: interviewers.map((principalId) => ({ principalId, role: "interviewer" })) } : {}
321
528
  };
322
- switch (`${group} ${action ?? ""}`.trim()) {
323
- case "login":
324
- return login(hr, deps, !values["no-browser"]);
325
- case "logout":
326
- return hr.logout();
327
- case "whoami":
328
- return hr.get("/me");
329
- case "jobs list":
330
- return hr.get("/jobs", { status: values.status });
331
- case "talents search":
332
- return linkedPage(hr, await hr.get("/talents", { q: rest.join(" ") || void 0, jobId: await jobId(hr, values.job), ...page2 }), "talents");
333
- case "talents show": {
334
- const who = needed("a name or id", rest.join(" "));
335
- if (isId(who)) return linkedTalent(hr, who);
336
- const found = await hr.get("/talents", { q: who, pageSize: 50 });
337
- return linkedTalent(hr, pickOne(found.items, who, (item) => [item.displayName], (item) => ({ id: item.id, name: item.displayName, headline: item.headline }), "talent").id);
338
- }
339
- case "screening list":
340
- return linkedPage(hr, await screeningQueue(hr, values.job), "applications");
341
- case "screening pass":
342
- return hr.post(`/applications/${await screeningApplication(hr, needed("a candidate", rest.join(" ")), values.job)}/screening`, { decision: "pass" });
343
- case "screening reject": {
344
- const id = await screeningApplication(hr, needed("a candidate", rest.join(" ")), values.job);
345
- return hr.post(`/applications/${id}/screening`, { decision: "reject", reasonId: await rejectReason(hr, values.reason) });
346
- }
347
- case "interviews to-schedule":
348
- return linkedPage(hr, await hr.get("/applications", { queue: "to_schedule", jobId: await jobId(hr, values.job), ...page2 }), "applications");
349
- case "interviews schedule": {
350
- const applicationId = await toScheduleApplication(hr, needed("a candidate", rest.join(" ")), values.job);
351
- const body = { ...slot(values), participants: await interviewers(hr, values.with), ...values.location !== void 0 ? { locationOrLink: values.location } : {} };
352
- return described(hr, await hr.post(`/applications/${applicationId}/interviews`, body));
353
- }
354
- case "interviews list": {
355
- const applicationId = needed("an application id", rest[0]);
356
- const url = `${await hr.appOrigin()}/applications/${applicationId}`;
357
- return (await hr.get("/interviews", { applicationId })).map((interview) => ({ ...interview, url }));
358
- }
359
- case "interviews reschedule": {
360
- const id = needed("an interview id", rest[0]);
361
- if (!values.start && !values.end && !values.minutes && values.location === void 0) throw new CliError("USAGE", "Pass --start, --end, --minutes or --location");
529
+ }
530
+ var jobCommands = [
531
+ {
532
+ name: "jobs list",
533
+ usage: "hr jobs list [--status open|paused|draft|closed]",
534
+ does: "Jobs, open ones first.",
535
+ returns: "data: [{ id, title, slug, status, counts: { active, hired, rejected, withdrawn } }]. counts are applications per job.",
536
+ run: ({ hr, values }) => hr.get("/jobs", { status: oneOf("--status", values.status, JobStatuses) })
537
+ },
538
+ {
539
+ name: "jobs show",
540
+ usage: "hr jobs show <job>",
541
+ does: "One job with its pipeline stages (and what each does on entry), interviewers and required skills.",
542
+ returns: JobReturns,
543
+ run: async (ctx) => linkedOne(ctx.hr, await ctx.hr.get(`/jobs/${await requiredJob(ctx.hr, joined(ctx, "a job"))}`), "jobs")
544
+ },
545
+ {
546
+ name: "jobs create",
547
+ usage: "hr jobs create --name <title> [--status draft|open|paused|closed] [--kind full_time|part_time|contract|intern] [--location <text>] [--description <markdown>] [--with <interviewers>] [--recruiter <person>] [--keywords <a,b>] [--json '{\u2026}']",
548
+ does: `Open a job. --with sets its interviewers, --recruiter its recruiter, --keywords the words that route mail to it. Mail to jobs+<slug>@ the recruiting domain lands on it.${takesJson(JobFields)}`,
549
+ returns: JobReturns,
550
+ run: async (ctx) => {
551
+ const body = await bodyOf(ctx, await jobFlags(ctx));
552
+ if (!body.title) throw new CliError("USAGE", "Pass --name with the job title");
553
+ return linkedOne(ctx.hr, await ctx.hr.post("/jobs", body), "jobs");
554
+ }
555
+ },
556
+ {
557
+ name: "jobs update",
558
+ usage: "hr jobs update <job> [--name <title>] [--status \u2026] [--kind \u2026] [--location <text>] [--description <markdown>] [--with <interviewers>] [--recruiter <person>] [--keywords <a,b>] [--json '{\u2026}']",
559
+ does: `Change a job; fields left out keep their value. --with replaces the interviewers. Switching pipelineId moves its applications to the stage of the same category.${takesJson(JobFields)}`,
560
+ returns: JobReturns,
561
+ run: async (ctx) => linkedOne(ctx.hr, await ctx.hr.patch(`/jobs/${await requiredJob(ctx.hr, joined(ctx, "a job"))}`, await bodyOf(ctx, await jobFlags(ctx))), "jobs")
562
+ },
563
+ {
564
+ name: "jobs matches",
565
+ usage: "hr jobs matches <job>",
566
+ does: "The talent pool ranked for a job by its gates and required skills (no model call): who in the pool could fit.",
567
+ returns: "data: [{ id, displayName, headline, gate: pass|fail|unknown|null, gates: [{ name, result }], skillMatch 0-200 }]",
568
+ run: async (ctx) => ctx.hr.get(`/jobs/${await requiredJob(ctx.hr, joined(ctx, "a job"))}/matches`)
569
+ },
570
+ {
571
+ name: "jobs screen-matches",
572
+ usage: "hr jobs screen-matches <job> --talent <name|id>[,\u2026]",
573
+ does: "Run AI screening of up to 20 talents against a job's scorecard without putting them forward. Takes minutes.",
574
+ returns: "data: [the ai_screen evaluation, or { talentId, error }]",
575
+ run: async (ctx) => {
576
+ const job = await requiredJob(ctx.hr, joined(ctx, "a job"));
577
+ const talentIds = await Promise.all((list(needed("--talent", ctx.values.talent)) ?? []).map((who) => talentId(ctx.hr, who)));
578
+ return ctx.hr.post(`/jobs/${job}/matches/screen`, { talentIds });
579
+ }
580
+ },
581
+ {
582
+ name: "reasons list",
583
+ usage: "hr reasons list",
584
+ does: "Reject reasons.",
585
+ returns: "data: [{ id, name, category, templateId }]. category we_rejected rejects; candidate_declined withdraws.",
586
+ run: ({ hr }) => hr.get("/reject-reasons")
587
+ },
588
+ {
589
+ name: "reasons save",
590
+ usage: "hr reasons save [<reason name|id>] --name <name> --kind we_rejected|candidate_declined [--template <template name|id>]",
591
+ does: "Create a reject reason, or change one when named. --template picks the rejection mail template offered with it.",
592
+ returns: "data: { id, name, category, templateId }",
593
+ run: async (ctx) => {
594
+ const existing = ctx.args.length ? await namedId(ctx.hr, "/reject-reasons", ctx.args.join(" "), "reject reason") : null;
595
+ const body = {
596
+ name: needed("--name", ctx.values.name),
597
+ category: oneOf("--kind", needed("--kind", ctx.values.kind), ["we_rejected", "candidate_declined"]),
598
+ templateId: ctx.values.template ? await namedId(ctx.hr, "/mail-templates", ctx.values.template, "template") : null
599
+ };
600
+ return existing ? ctx.hr.put(`/reject-reasons/${existing}`, body) : ctx.hr.post("/reject-reasons", body);
601
+ }
602
+ }
603
+ ];
604
+
605
+ // src/commands/mail.ts
606
+ var IntakeStatuses = ["pending", "processing", "linked", "created", "needs_review", "ignored", "failed"];
607
+ var Classifications = ["application", "reply", "job_board", "referral", "other"];
608
+ var Presets = ["feishu", "gmail", "custom"];
609
+ var MailboxFields = "imapHost, imapPort, imapSecure, smtpHost, smtpPort, smtpSecure, username, folders [], sentFolder, archiveFolder, kind shared|personal, ownerPrincipalId, backfillFrom (a date)";
610
+ var MailboxReturns = "data: the mailbox { id, address, preset, imapHost, smtpHost, folders, status, lastSyncedAt, lastError, backfillStatus, backfillStats, defaultJobId, hasPassword } (never the password).";
611
+ async function mailboxId(ctx, value) {
612
+ if (isId(value)) return value;
613
+ const boxes = await ctx.hr.get("/mailboxes");
614
+ return pickOne(boxes, value, (box) => [box.address], (box) => ({ id: box.id, address: box.address }), "mailbox").id;
615
+ }
616
+ async function mailboxBody(ctx) {
617
+ return bodyOf(ctx, {
618
+ address: ctx.values.address,
619
+ preset: oneOf("--preset", ctx.values.preset, Presets),
620
+ password: ctx.values.password,
621
+ defaultJobId: ctx.values.job ? await jobId(ctx.hr, ctx.values.job) : void 0
622
+ });
623
+ }
624
+ var mailCommands = [
625
+ {
626
+ name: "mail send",
627
+ usage: "hr mail send <name|id> --subject <text> --body <text> [--application <application id>]",
628
+ does: "Mail a candidate from the recruiting mailbox, as a reply in their latest thread (about that application when given). It counts as answering their unanswered replies.",
629
+ returns: "data: the sent mail { id, subject, sentAt, \u2026 }, or data.pendingApproval (see below).",
630
+ run: async (ctx) => {
631
+ const id = await talentId(ctx.hr, joined(ctx, "a candidate"));
632
+ return ctx.hr.post(`/talents/${id}/mail`, { subject: needed("--subject", ctx.values.subject), body: needed("--body", ctx.values.body), ...ctx.values.application ? { applicationId: ctx.values.application } : {} });
633
+ }
634
+ },
635
+ {
636
+ name: "mail draft",
637
+ usage: "hr mail draft <name|id> --intent <what the mail should say> [--application <application id>]",
638
+ does: "Have the model draft a mail to a candidate (in the language they wrote in), from what it should say and their last mail. Nothing is sent: show it to the user, then `hr mail send`.",
639
+ returns: "data: { subject, body, llmRunId }",
640
+ run: async (ctx) => ctx.hr.post(`/talents/${await talentId(ctx.hr, joined(ctx, "a candidate"))}/mail/draft`, { intent: needed("--intent", ctx.values.intent), applicationId: ctx.values.application ?? null })
641
+ },
642
+ {
643
+ name: "mail list",
644
+ usage: "hr mail list [text] [--mailbox <address|id>] [--status <intake status>] [--classification application|reply|job_board|referral|other] [--talent <name|id>] [--page n] [--page-size n]",
645
+ does: "Mail HR synced, newest first, with how intake handled each: pending, processing, linked (to a known talent), created (a new talent), needs_review, ignored or failed. Text matches subject and sender.",
646
+ returns: "data: { total, items: [{ id, direction, fromAddress, fromName, subject, sentAt, textBody (first 300 characters), talentId, applicationId, intakeStatus, classification, replyIntent, error }] }",
647
+ run: async (ctx) => ctx.hr.get("/mail", {
648
+ q: ctx.args.join(" ") || void 0,
649
+ mailboxId: ctx.values.mailbox ? await mailboxId(ctx, ctx.values.mailbox) : void 0,
650
+ status: oneOf("--status", ctx.values.status, IntakeStatuses),
651
+ classification: oneOf("--classification", ctx.values.classification, Classifications),
652
+ talentId: ctx.values.talent ? await talentId(ctx.hr, ctx.values.talent) : void 0,
653
+ ...ctx.page
654
+ })
655
+ },
656
+ {
657
+ name: "mail show",
658
+ usage: "hr mail show <mail id>",
659
+ does: "One mail in full, with its attachments and what intake extracted from it.",
660
+ returns: "data: { id, \u2026, textBody, extraction, attachments: [{ id, fileName, mime, size, documentId }] }",
661
+ run: ({ hr, args }) => hr.get(`/mail/${needed("a mail id", args[0])}`)
662
+ },
663
+ {
664
+ name: "mail stats",
665
+ usage: "hr mail stats",
666
+ does: "How much mail sits in each intake status, live and backfilled.",
667
+ returns: "data: [{ status, backfill, total }]",
668
+ run: ({ hr }) => hr.get("/mail/stats")
669
+ },
670
+ {
671
+ name: "mail replay",
672
+ usage: "hr mail replay <mail id>",
673
+ does: "Put a mail through intake again (after it failed, or after fixing a job board rule).",
674
+ returns: "data: { id }",
675
+ run: ({ hr, args }) => hr.post(`/mail/${needed("a mail id", args[0])}/replay`, {})
676
+ },
677
+ {
678
+ name: "mail correct",
679
+ usage: `hr mail correct <mail id> --json '{"name":\u2026,"contacts":[\u2026]}'`,
680
+ does: `Correct the candidate HR read from a mail (typically a job board notice); the talent is updated and the mail kept as a sample.${takesJson("name, contacts [{ kind, value }], headline, currentCompany, currentTitle, city, yearsOfExperience, highestDegree, profile, skills")}`,
681
+ returns: "data: the mail, as `hr mail show` returns it.",
682
+ run: async (ctx) => ctx.hr.post(`/mail/${needed("a mail id", ctx.args[0])}/correction`, await bodyOf(ctx))
683
+ },
684
+ // ---------- Mailboxes ----------
685
+ { name: "mailboxes list", usage: "hr mailboxes list", does: "The recruiting mailboxes HR syncs, with their sync and backfill state.", returns: `data: [${MailboxReturns.slice(6, -1)}]`, run: ({ hr }) => hr.get("/mailboxes") },
686
+ {
687
+ name: "mailboxes test",
688
+ usage: "hr mailboxes test --address <email> --preset feishu|gmail|custom --password <app password> [--json '{\u2026}']",
689
+ does: `Try signing in to IMAP and SMTP without saving anything.${takesJson(MailboxFields)}`,
690
+ returns: "data: { ok: true }, or the server's reason it refused.",
691
+ run: async (ctx) => ctx.hr.post("/mailboxes/test", await mailboxBody(ctx))
692
+ },
693
+ {
694
+ name: "mailboxes create",
695
+ usage: "hr mailboxes create --address <email> --preset feishu|gmail|custom --password <app password> [--job <default job>] [--json '{\u2026}']",
696
+ does: `Connect a recruiting mailbox (the sign-in is tested first; the password is sealed and never shown again). --job is where mail that names no job goes. Prefer passing the password from the user's own environment, never typing it into chat.${takesJson(MailboxFields)}`,
697
+ returns: MailboxReturns,
698
+ run: async (ctx) => {
699
+ const body = await mailboxBody(ctx);
700
+ if (!body.address || !body.preset) throw new CliError("USAGE", "Pass --address and --preset");
701
+ return ctx.hr.post("/mailboxes", body);
702
+ }
703
+ },
704
+ {
705
+ name: "mailboxes update",
706
+ usage: "hr mailboxes update <address|id> [--address \u2026] [--preset \u2026] [--password \u2026] [--job <default job>] [--json '{\u2026}']",
707
+ does: `Change a mailbox; leaving out --password keeps the stored one.${takesJson(MailboxFields)}`,
708
+ returns: MailboxReturns,
709
+ run: async (ctx) => {
710
+ const id = await mailboxId(ctx, joined(ctx, "a mailbox"));
711
+ const current = await ctx.hr.get("/mailboxes").then((boxes) => boxes.find((box) => box.id === id));
712
+ return ctx.hr.patch(`/mailboxes/${id}`, { address: current.address, preset: current.preset, ...await mailboxBody(ctx) });
713
+ }
714
+ },
715
+ {
716
+ name: "mailboxes delete",
717
+ usage: "hr mailboxes delete <address|id>",
718
+ does: "Disconnect a mailbox. Mail already synced stays.",
719
+ returns: "data: { id }",
720
+ run: async (ctx) => ctx.hr.delete(`/mailboxes/${await mailboxId(ctx, joined(ctx, "a mailbox"))}`)
721
+ },
722
+ {
723
+ name: "mailboxes state",
724
+ usage: "hr mailboxes state <address|id> [--status active|paused] [--backfill start|pause|resume] [--backfill-from <date>]",
725
+ does: "Pause or resume syncing, or run a backfill: read old mail from --backfill-from (2025-01-01) as history (no auto-replies, no screening, no notifications).",
726
+ returns: MailboxReturns,
727
+ run: async (ctx) => ctx.hr.post(`/mailboxes/${await mailboxId(ctx, joined(ctx, "a mailbox"))}/state`, {
728
+ ...ctx.values.status ? { status: oneOf("--status", ctx.values.status, ["active", "paused"]) } : {},
729
+ ...ctx.values.backfill ? { backfill: oneOf("--backfill", ctx.values.backfill, ["start", "pause", "resume"]) } : {},
730
+ ...ctx.values["backfill-from"] ? { backfillFrom: ctx.values["backfill-from"] } : {}
731
+ })
732
+ },
733
+ {
734
+ name: "mailboxes sync",
735
+ usage: "hr mailboxes sync <address|id>",
736
+ does: "Fetch new mail now instead of waiting for the next round.",
737
+ returns: "data: { stored, more }. more means another round has mail left.",
738
+ run: async (ctx) => ctx.hr.post(`/mailboxes/${await mailboxId(ctx, joined(ctx, "a mailbox"))}/sync`, {})
739
+ }
740
+ ];
741
+
742
+ // src/commands/recruiting.ts
743
+ var InterviewReturns = "data: { id, applicationId, round, status, candidateStatus, startsAt, endsAt, mode, meetingUrl, meetingCode, address, platform, invitedAt, participants: [{ principalId, evaluationId, submitted }], talentName, jobTitle, url }. Times are UTC. candidateStatus is the candidate's answer: pending | confirmed | declined | reschedule_requested | no_response, or null when the stage asks for none.";
744
+ var InviteReturns = "plus invite: { status: sent | none | failed, error? } or { pendingApproval } (the invitation waits for approval; the interview is booked).";
745
+ var Verdicts = ["strong_yes", "yes", "hold", "no", "strong_no"];
746
+ var AnswerStatuses = ["confirmed", "declined", "reschedule_requested", "pending"];
747
+ async function described(hr, interview) {
748
+ const detail = await hr.get(`/applications/${interview.applicationId}`);
749
+ return { ...interview, talentName: detail.talent.displayName, jobTitle: detail.job.title, url: `${await hr.appOrigin()}/applications/${interview.applicationId}` };
750
+ }
751
+ var recruitingCommands = [
752
+ // ---------- Screening ----------
753
+ {
754
+ name: "screening list",
755
+ usage: "hr screening list [--job <job>]",
756
+ does: "Applications waiting for screening, first come first.",
757
+ returns: "data: { total, items: [{ id, talentName, jobTitle, stageName, url }] }. total is how many are waiting.",
758
+ run: async ({ hr, values }) => linkedPage(hr, await hr.get("/applications", { queue: "screening", jobId: await jobId(hr, values.job), pageSize: 200 }), "applications")
759
+ },
760
+ {
761
+ name: "screening pass",
762
+ usage: "hr screening pass <name|id> [--job <job>]",
763
+ does: "Pass a candidate waiting for screening to the job's first interview stage.",
764
+ returns: "data: the updated application, or data.pendingApproval (see below).",
765
+ run: async (ctx) => ctx.hr.post(`/applications/${await applicationId(ctx.hr, joined(ctx, "a candidate"), { job: ctx.values.job, queue: "screening" })}/screening`, { decision: "pass" })
766
+ },
767
+ {
768
+ name: "screening reject",
769
+ usage: "hr screening reject <name|id> --reason <reason> [--job <job>]",
770
+ does: "Reject a candidate waiting for screening. <reason> comes from `hr reasons list`.",
771
+ returns: "data: the updated application, or data.pendingApproval (see below).",
772
+ run: async (ctx) => {
773
+ const id = await applicationId(ctx.hr, joined(ctx, "a candidate"), { job: ctx.values.job, queue: "screening" });
774
+ return ctx.hr.post(`/applications/${id}/screening`, { decision: "reject", reasonId: await rejectReason(ctx.hr, ctx.values.reason) });
775
+ }
776
+ },
777
+ // ---------- Interviews ----------
778
+ {
779
+ name: "interviews to-schedule",
780
+ usage: "hr interviews to-schedule [--job <job>] [--page n] [--page-size n]",
781
+ does: "Candidates in an interview stage with no interview booked.",
782
+ returns: "data: { total, items: [{ id, talentName, jobTitle, stageName, url }] }",
783
+ run: async ({ hr, values, page: page2 }) => linkedPage(hr, await hr.get("/applications", { queue: "to_schedule", jobId: await jobId(hr, values.job), ...page2 }), "applications")
784
+ },
785
+ {
786
+ name: "interviews schedule",
787
+ usage: "hr interviews schedule <name|id> --start <time> [--end <time> | --minutes n] (--online <link> [--code <meeting id>] | --offline <address>) [--with <people>] [--job <job>]",
788
+ does: "Book an interview for a candidate waiting in `hr interviews to-schedule` (or an application id). <time> is ISO 8601 with its UTC offset, such as 2026-11-12T15:00+08:00. Length defaults to 60 minutes. Where: --online with the meeting link from any platform (Feishu, Tencent Meeting, Zoom\u2026; create the meeting first with your calendar tool) and optionally its meeting ID, or --offline with the address. <people> are interviewers, comma-separated names, emails or ids from `hr people search`; leave it out to use the stage's default interviewers, or else the job's interviewers. When the stage is set to, HR mails the candidate the invitation (time, place, link) in their thread and waits for their answer; it puts nothing on any calendar.",
789
+ returns: `${InterviewReturns.slice(0, -1)}, ${InviteReturns}`,
790
+ example: 'hr interviews schedule "Li Wei" --start 2026-11-12T15:00+08:00 --online https://vc.feishu.cn/j/324385898 --code "324 385 898"',
791
+ run: async (ctx) => {
792
+ const where = place(ctx.values);
793
+ if (!where) throw new CliError("USAGE", "Say where: --online <meeting link> or --offline <address>");
794
+ const id = await applicationId(ctx.hr, joined(ctx, "a candidate"), { job: ctx.values.job, queue: "to_schedule" });
795
+ const participants = await personIds(ctx.hr, ctx.values.with);
796
+ return described(ctx.hr, await ctx.hr.post(`/applications/${id}/interviews`, { ...slot(ctx.values), ...where, ...participants ? { participants } : {} }));
797
+ }
798
+ },
799
+ {
800
+ name: "interviews list",
801
+ usage: "hr interviews list <application id>",
802
+ does: "Every interview of one application, latest first.",
803
+ returns: InterviewReturns,
804
+ run: async ({ hr, args }) => {
805
+ const id = needed("an application id", args[0]);
806
+ const url = `${await hr.appOrigin()}/applications/${id}`;
807
+ return (await hr.get("/interviews", { applicationId: id })).map((interview) => ({ ...interview, url }));
808
+ }
809
+ },
810
+ {
811
+ name: "interviews mine",
812
+ usage: "hr interviews mine",
813
+ does: "Interviews the caller takes part in that are not cancelled, to fill in evaluations.",
814
+ returns: InterviewReturns.replace(", talentName, jobTitle, url", ""),
815
+ run: ({ hr }) => hr.get("/interviews")
816
+ },
817
+ {
818
+ name: "interviews show",
819
+ usage: "hr interviews show <interview id>",
820
+ does: "One interview.",
821
+ returns: InterviewReturns,
822
+ run: async ({ hr, args }) => described(hr, await hr.get(`/interviews/${needed("an interview id", args[0])}`))
823
+ },
824
+ {
825
+ name: "interviews reschedule",
826
+ usage: "hr interviews reschedule <interview id> [--start <time>] [--end <time> | --minutes n] [--online <link> [--code <meeting id>] | --offline <address>]",
827
+ does: "Move or relocate an interview. A new --start keeps the length unless --end or --minutes is given. A new time or place mails the candidate the invitation again and asks them to confirm again.",
828
+ returns: `${InterviewReturns.slice(0, -1)}, ${InviteReturns}`,
829
+ run: async ({ hr, args, values }) => {
830
+ const id = needed("an interview id", args[0]);
831
+ const where = place(values);
832
+ if (!values.start && !values.end && !values.minutes && !where) throw new CliError("USAGE", "Pass --start, --end, --minutes, --online or --offline");
362
833
  const current = await hr.get(`/interviews/${id}`);
363
834
  const times = values.start || values.end || values.minutes ? slot(values, current) : {};
364
- return described(hr, await hr.patch(`/interviews/${id}`, { ...times, ...values.location !== void 0 ? { locationOrLink: values.location } : {} }));
365
- }
366
- case "interviews cancel":
367
- return described(hr, await hr.patch(`/interviews/${needed("an interview id", rest[0])}`, { status: "cancelled" }));
368
- case "people search": {
369
- const everyone = await people(hr);
370
- const wanted = rest.join(" ").trim().toLowerCase();
371
- return everyone.filter((person) => !wanted || [person.displayName, person.email].some((value) => value?.toLowerCase().includes(wanted))).map(describePerson);
372
- }
373
- case "reasons list":
374
- return hr.get("/reject-reasons");
375
- case "approvals status":
376
- return approvalStatus(hr, deps, needed("an approval id", rest[0]), Boolean(values.wait), Number(values.timeout ?? 300));
377
- default:
378
- throw new CliError("USAGE", `Unknown command: ${positionals.join(" ") || "(none)"}. Run \`hr --help\``);
835
+ return described(hr, await hr.patch(`/interviews/${id}`, { ...times, ...where ?? {} }));
836
+ }
837
+ },
838
+ {
839
+ name: "interviews complete",
840
+ usage: "hr interviews complete <interview id>",
841
+ does: "Mark an interview as held. HR does this by itself once every interviewer has submitted.",
842
+ returns: InterviewReturns,
843
+ run: async ({ hr, args }) => described(hr, await hr.patch(`/interviews/${needed("an interview id", args[0])}`, { status: "completed" }))
844
+ },
845
+ {
846
+ name: "interviews cancel",
847
+ usage: "hr interviews cancel <interview id>",
848
+ does: "Cancel an interview.",
849
+ returns: InterviewReturns,
850
+ run: async ({ hr, args }) => described(hr, await hr.patch(`/interviews/${needed("an interview id", args[0])}`, { status: "cancelled" }))
851
+ },
852
+ {
853
+ name: "interviews confirm",
854
+ usage: "hr interviews confirm <interview id> [--status confirmed|declined|reschedule_requested|pending]",
855
+ does: "Record the candidate's answer by hand (they called, or HR read their reply wrong). Defaults to confirmed. Recording declined does not withdraw the application.",
856
+ returns: InterviewReturns,
857
+ run: async ({ hr, args, values }) => {
858
+ const status = oneOf("--status", values.status, AnswerStatuses) ?? "confirmed";
859
+ return described(hr, await hr.post(`/interviews/${needed("an interview id", args[0])}/candidate-status`, { status }));
860
+ }
861
+ },
862
+ // ---------- Replies ----------
863
+ {
864
+ name: "replies list",
865
+ usage: "hr replies list [--application <application id>]",
866
+ does: "Candidate replies nobody has dealt with yet, newest first. HR reads replies to interview invitations itself: a sure confirmation or decline is handled and never listed; asking for another time, unclear replies and mail it could not tie to one interview are.",
867
+ returns: "data: { total, items: [{ id, talentId, talentName, jobTitle, stageName, subject, textBody, sentAt, replyIntent, applicationId, interview, resumeId, url }] }. replyIntent: confirm | decline | reschedule | unclear, or null when not read. interview is the one it answers, or null. url is the application's page.",
868
+ run: async ({ hr, values }) => {
869
+ const origin = await hr.appOrigin();
870
+ const result = await hr.get("/replies", { applicationId: values.application, pageSize: 200 });
871
+ return { ...result, items: result.items.map((item) => ({ ...item, url: item.applicationId ? `${origin}/applications/${item.applicationId}` : `${origin}/talents/${item.talentId}` })) };
872
+ }
873
+ },
874
+ {
875
+ name: "replies done",
876
+ usage: "hr replies done <reply id>",
877
+ does: "Mark a reply as dealt with (answered elsewhere, or nothing to answer). Mailing the candidate marks their replies dealt with by itself.",
878
+ returns: "data: { id, handled: true }",
879
+ run: ({ hr, args }) => hr.post(`/replies/${needed("a reply id", args[0])}/handled`, {})
880
+ },
881
+ // ---------- Evaluations ----------
882
+ {
883
+ name: "evaluations submit",
884
+ usage: `hr evaluations submit <interview id> --verdict strong_yes|yes|hold|no|strong_no [--summary <text>] [--json '{"items":[\u2026]}']`,
885
+ does: `Submit the caller's own evaluation of an interview they took part in, with the reasons in --summary. Once every interviewer has, a stage set to move on does: all yes to the next round, all no to rejected, otherwise to the decision stage.${takesJson("items: [{ criterionId, score 1-5, evidence, comment }] for per-criterion scores (ids from `hr evaluations show`)")}`,
886
+ returns: "data: { id, status, recommendation, summary, overallScore, items }",
887
+ run: async (ctx) => {
888
+ const interviewId = needed("an interview id", ctx.args[0]);
889
+ const verdict = oneOf("--verdict", needed("--verdict", ctx.values.verdict), Verdicts);
890
+ const [me, interview] = await Promise.all([ctx.hr.get("/me"), ctx.hr.get(`/interviews/${interviewId}`)]);
891
+ const mine = interview.participants.find((participant) => participant.principalId === me.principalId);
892
+ if (!mine?.evaluationId) throw new CliError("USAGE", "Only an interviewer of this interview submits its evaluation");
893
+ return ctx.hr.patch(`/evaluations/${mine.evaluationId}`, { items: [], ...await bodyOf(ctx, { recommendation: verdict, summary: ctx.values.summary ?? "" }), submit: true });
894
+ }
895
+ },
896
+ {
897
+ name: "evaluations show",
898
+ usage: "hr evaluations show <evaluation id>",
899
+ does: "One evaluation (AI screening, interview or manual) with its criteria, scores and evidence. Drafts are only visible to their author.",
900
+ returns: "data: { id, kind, status, evaluatorPrincipalId, recommendation, summary, overallScore, gatePassed, questions, items: [{ criterion: { id, kind, name }, score, gateResult, evidence, comment }] }",
901
+ run: ({ hr, args }) => hr.get(`/evaluations/${needed("an evaluation id", args[0])}`)
902
+ },
903
+ {
904
+ name: "evaluations write",
905
+ usage: "hr evaluations write <talent name|id> [--application <application id>]",
906
+ does: "Start a manual evaluation of a talent (outside an interview), on the job's scorecard. Fill it with `hr evaluations save`.",
907
+ returns: "data: the draft evaluation, with its items to fill.",
908
+ run: async (ctx) => ctx.hr.post(`/talents/${await talentId(ctx.hr, joined(ctx, "a talent"))}/evaluations`, { applicationId: ctx.values.application ?? null })
909
+ },
910
+ {
911
+ name: "evaluations save",
912
+ usage: `hr evaluations save <evaluation id> [--verdict <verdict>] [--summary <text>] [--json '{"items":[\u2026]}'] [--confirm]`,
913
+ does: `Save the caller's own draft; --confirm submits it, after which it cannot change. A submission needs --verdict.${takesJson("items: [{ criterionId, score 1-5, gateResult pass|fail|unknown, evidence, comment }]")}`,
914
+ returns: "data: { id, status, recommendation, summary, overallScore, items }",
915
+ run: async (ctx) => {
916
+ const id = needed("an evaluation id", ctx.args[0]);
917
+ const input = await bodyOf(ctx, { recommendation: oneOf("--verdict", ctx.values.verdict, Verdicts), summary: ctx.values.summary });
918
+ return ctx.hr.patch(`/evaluations/${id}`, { items: [], ...input, submit: Boolean(ctx.values.confirm) });
919
+ }
920
+ },
921
+ // ---------- Reports ----------
922
+ {
923
+ name: "reports funnel",
924
+ usage: "hr reports funnel [--job <job>] [--from <date>] [--to <date>]",
925
+ does: "The recruiting report: applications per stage category, channels, average days in each stage, reject reasons, stale applications and how many interview evaluations were submitted. --from / --to are dates (2026-11-01).",
926
+ returns: "data: { funnel: [{ category, applications }], channels: [{ source, detail, applications, interviewed, offered, hired }], timeInStage: [{ stage, category, avgDays, samples }], rejectReasons: [{ reason, applications }], staleApplications, evaluations: { total, submitted } }",
927
+ run: async ({ hr, values }) => hr.get("/reports/recruiting", { jobId: await jobId(hr, values.job), from: values.from, to: values.to })
928
+ }
929
+ ];
930
+
931
+ // src/commands/settings.ts
932
+ var TemplateKinds = ["acknowledge", "reject", "invite", "other"];
933
+ var StageFields = "stages [{ id (keep it to keep the stage), name, category new|screening|interview|decision|offer|hired|rejected|withdrawn, slaDays, requiresEvaluation, onEnterActions [{ kind send_mail, templateId } | { kind notify, principalIds } | { kind archive_mail, onlyAfterInterview } | { kind interview, interviewerIds, inviteTemplateId, reminderTemplateId, requireConfirm, remindHoursBefore, giveUpHoursBefore, autoAdvance }] }]";
934
+ var Variables = "{{talent.name}}, {{job.title}}, {{stage.name}}, {{interview.time}}, {{interview.where}}, {{interview.round}}, {{interview.start}}, {{interview.end}}, {{interview.link}}, {{interview.meeting_code}}, {{interview.address}}";
935
+ async function pipelineOf(ctx, value) {
936
+ const pipelines = await ctx.hr.get("/pipelines");
937
+ return pickOne(pipelines, value, (pipeline) => [pipeline.id, pipeline.name], (pipeline) => ({ id: pipeline.id, name: pipeline.name }), "pipeline");
938
+ }
939
+ async function templateOf(ctx, value) {
940
+ const templates = await ctx.hr.get("/mail-templates");
941
+ return pickOne(templates, value, (template) => [template.id, template.name], (template) => ({ id: template.id, name: template.name, kind: template.kind }), "template");
942
+ }
943
+ var settingsCommands = [
944
+ // ---------- Pipelines ----------
945
+ {
946
+ name: "pipelines list",
947
+ usage: "hr pipelines list",
948
+ does: "Pipelines (stage templates jobs use), the default first, with each stage's actions on entry.",
949
+ returns: "data: [{ id, name, isDefault, stages: [{ id, name, sequence, category, slaDays, requiresEvaluation, onEnterActions }] }]",
950
+ run: ({ hr }) => hr.get("/pipelines")
951
+ },
952
+ {
953
+ name: "pipelines show",
954
+ usage: "hr pipelines show <pipeline name|id>",
955
+ does: "One pipeline, as `hr pipelines list` returns it: a starting point for `hr pipelines save --json`.",
956
+ returns: "data: { id, name, isDefault, stages }",
957
+ run: async (ctx) => pipelineOf(ctx, joined(ctx, "a pipeline"))
958
+ },
959
+ {
960
+ name: "pipelines save",
961
+ usage: "hr pipelines save [<pipeline name|id>] --json @pipeline.json [--name <name>] [--confirm]",
962
+ does: `Create a pipeline, or replace one's stages when named (stages applications passed through cannot be removed). Every pipeline needs a new stage and the hired and rejected outcomes; interview settings go on interview stages only. --confirm makes it the default for new jobs.${takesJson(`name, ${StageFields}`)}`,
963
+ returns: "data: the saved pipeline.",
964
+ run: async (ctx) => {
965
+ const current = ctx.args.length ? await pipelineOf(ctx, ctx.args.join(" ")) : null;
966
+ const body = await bodyOf(ctx, { name: ctx.values.name ?? current?.name, ...ctx.values.confirm ? { isDefault: true } : {} });
967
+ if (!body.stages) throw new CliError("USAGE", "Pass the stages in --json (start from `hr pipelines show`)");
968
+ return current ? ctx.hr.put(`/pipelines/${current.id}`, body) : ctx.hr.post("/pipelines", body);
969
+ }
970
+ },
971
+ // ---------- Scorecards ----------
972
+ { name: "scorecards list", usage: "hr scorecards list", does: "Scorecards (the newest version of each).", returns: "data: [{ id, familyId, name, version, criteria }]", run: ({ hr }) => hr.get("/scorecards") },
973
+ {
974
+ name: "scorecards show",
975
+ usage: "hr scorecards show <scorecard name|id>",
976
+ does: "One scorecard with its gates and dimensions.",
977
+ returns: "data: { id, name, version, criteria: [{ id, kind gate|dimension, name, description, weight, rubric { 1..5 }, gateRule, appliesTo ai|interview|both }] }",
978
+ run: async (ctx) => ctx.hr.get(`/scorecards/${await namedId(ctx.hr, "/scorecards", joined(ctx, "a scorecard"), "scorecard")}`)
979
+ },
980
+ {
981
+ name: "scorecards save",
982
+ usage: "hr scorecards save [<scorecard name|id>] --json @scorecard.json [--name <name>]",
983
+ does: `Create a scorecard, or change one when named (one that has evaluations gets a new version; old evaluations keep theirs).${takesJson('name, criteria [{ kind gate|dimension, name, description, weight, rubric { "1", "3", "5" }, gateRule, appliesTo }]')}`,
984
+ returns: "data: the saved scorecard.",
985
+ run: async (ctx) => {
986
+ const id = ctx.args.length ? await namedId(ctx.hr, "/scorecards", ctx.args.join(" "), "scorecard") : null;
987
+ const body = await bodyOf(ctx, { name: ctx.values.name });
988
+ if (!body.criteria) throw new CliError("USAGE", "Pass the criteria in --json (start from `hr scorecards show`)");
989
+ if (!body.name && id) body.name = (await ctx.hr.get(`/scorecards/${id}`)).name;
990
+ return id ? ctx.hr.put(`/scorecards/${id}`, body) : ctx.hr.post("/scorecards", body);
991
+ }
992
+ },
993
+ // ---------- Skill dictionary ----------
994
+ { name: "skills list", usage: "hr skills list", does: "The skill dictionary: names, aliases and how many talents have each.", returns: "data: [{ id, name, aliases, category, talents }]", run: ({ hr }) => hr.get("/skills") },
995
+ {
996
+ name: "skills save",
997
+ usage: 'hr skills save [<skill name|id>] --name <name> [--keywords "alias, alias"] [--kind <category>]',
998
+ does: "Add a skill to the dictionary, or change one when named. Aliases make other spellings count as this skill.",
999
+ returns: "data: { id, name, aliases, category }",
1000
+ run: async (ctx) => {
1001
+ const id = ctx.args.length ? await namedId(ctx.hr, "/skills", ctx.args.join(" "), "skill") : null;
1002
+ const body = { name: needed("--name", ctx.values.name), aliases: list(ctx.values.keywords) ?? [], category: ctx.values.kind ?? null };
1003
+ return id ? ctx.hr.put(`/skills/${id}`, body) : ctx.hr.post("/skills", body);
1004
+ }
1005
+ },
1006
+ // ---------- Mail templates ----------
1007
+ { name: "templates list", usage: "hr templates list", does: `Mail templates (acknowledgement, rejection, invitation\u2026). Variables: ${Variables}.`, returns: "data: [{ id, name, kind, subject, body }]", run: ({ hr }) => hr.get("/mail-templates") },
1008
+ { name: "templates show", usage: "hr templates show <template name|id>", does: "One mail template.", returns: "data: { id, name, kind, subject, body }", run: async (ctx) => templateOf(ctx, joined(ctx, "a template")) },
1009
+ {
1010
+ name: "templates save",
1011
+ usage: "hr templates save [<template name|id>] --name <name> --kind acknowledge|reject|invite|other --subject <text> --body <text>",
1012
+ does: `Create a mail template, or change one when named (flags left out keep their value). Variables: ${Variables}.`,
1013
+ returns: "data: { id, name, kind, subject, body }",
1014
+ run: async (ctx) => {
1015
+ const current = ctx.args.length ? await templateOf(ctx, ctx.args.join(" ")) : null;
1016
+ const body = {
1017
+ name: needed("--name", ctx.values.name ?? current?.name),
1018
+ kind: oneOf("--kind", needed("--kind", ctx.values.kind ?? current?.kind), TemplateKinds),
1019
+ subject: needed("--subject", ctx.values.subject ?? current?.subject),
1020
+ body: needed("--body", ctx.values.body ?? current?.body)
1021
+ };
1022
+ return current ? ctx.hr.put(`/mail-templates/${current.id}`, body) : ctx.hr.post("/mail-templates", body);
1023
+ }
1024
+ },
1025
+ // ---------- Job board rules ----------
1026
+ {
1027
+ name: "job-boards list",
1028
+ usage: "hr job-boards list",
1029
+ does: "Job board sender rules: mail from these senders carries a candidate in its body (LinkedIn is preset).",
1030
+ returns: "data: [{ id, senderPattern, board, strategy llm|regex, nameRegex }]",
1031
+ run: ({ hr }) => hr.get("/job-board-senders")
1032
+ },
1033
+ {
1034
+ name: "job-boards save",
1035
+ usage: "hr job-boards save [<rule id>] --address <sender or *@domain> --name <board> [--kind llm|regex] [--q <name regex>]",
1036
+ does: "Add a job board sender rule, or change one by id. regex reads the candidate's name from the subject with --q (its first group); llm (the default) has the model read the mail.",
1037
+ returns: "data: { id, senderPattern, board, strategy, nameRegex }",
1038
+ run: async (ctx) => {
1039
+ const id = ctx.args[0];
1040
+ const current = id ? (await ctx.hr.get("/job-board-senders")).find((rule) => rule.id === id) : void 0;
1041
+ if (id && !current) throw new CliError("NOT_FOUND", "No job board rule has that id");
1042
+ const body = {
1043
+ senderPattern: needed("--address", ctx.values.address ?? current?.senderPattern),
1044
+ board: needed("--name", ctx.values.name ?? current?.board),
1045
+ strategy: oneOf("--kind", ctx.values.kind ?? current?.strategy ?? "llm", ["llm", "regex"]),
1046
+ nameRegex: ctx.values.q ?? current?.nameRegex ?? null
1047
+ };
1048
+ return current ? ctx.hr.put(`/job-board-senders/${current.id}`, body) : ctx.hr.post("/job-board-senders", body);
1049
+ }
1050
+ },
1051
+ { name: "job-boards delete", usage: "hr job-boards delete <rule id>", does: "Delete a job board sender rule.", returns: "data: { id }", run: ({ hr, args }) => hr.delete(`/job-board-senders/${needed("a rule id", args[0])}`) },
1052
+ // ---------- Event webhook ----------
1053
+ {
1054
+ name: "webhook show",
1055
+ usage: "hr webhook show",
1056
+ does: "Where HR sends its events (signed POSTs: new talents, stage changes, interviews, replies\u2026), and how delivery is going.",
1057
+ returns: "data: { url, pending, failed, lastDeliveredAt, lastError } or null when none is set.",
1058
+ run: ({ hr }) => hr.get("/event-webhook")
1059
+ },
1060
+ {
1061
+ name: "webhook set",
1062
+ usage: "hr webhook set --url <https address>",
1063
+ does: "Set the event webhook. The first time, a signing secret is generated and shown once only: hand it to the receiver, never into chat logs.",
1064
+ returns: "data: { url, \u2026, secret (only when generated) }",
1065
+ run: ({ hr, values }) => hr.put("/event-webhook", { url: needed("--url", values.url) })
1066
+ },
1067
+ { name: "webhook rotate", usage: "hr webhook rotate", does: "Replace the signing secret; the old one stops working at once.", returns: "data: { secret }", run: ({ hr }) => hr.post("/event-webhook/secret", {}) },
1068
+ { name: "webhook test", usage: "hr webhook test", does: "Queue a webhook.test event to the receiver.", returns: "data: { queued: true }", run: ({ hr }) => hr.post("/event-webhook/test", {}) },
1069
+ { name: "webhook delete", usage: "hr webhook delete", does: "Stop sending events; waiting ones are dropped.", returns: "data: { deleted: true }", run: ({ hr }) => hr.delete("/event-webhook") }
1070
+ ];
1071
+
1072
+ // src/commands/talents.ts
1073
+ import { readFile as readFile3, writeFile as writeFile2 } from "node:fs/promises";
1074
+ import path2 from "node:path";
1075
+ var Ratings = ["S", "A", "B", "C"];
1076
+ var ContactKinds = ["email", "phone", "wechat", "linkedin", "github", "other"];
1077
+ var Statuses2 = ["active", "hired", "do_not_contact", "archived"];
1078
+ var Sources = ["direct_email", "job_board", "referral", "agency", "upload", "agent"];
1079
+ var UploadSources = ["agency", "referral", "upload"];
1080
+ var TalentFields = "headline, currentCompany, currentTitle, city, yearsOfExperience, highestDegree (none|high_school|associate|bachelor|master|phd), profile { experience, education, projects, intent }, ownerPrincipalId, sourceNote, referrerPrincipalId";
1081
+ var TalentReturns = "data: the talent { id, displayName, headline, status, rating, contacts (when the caller may see them), skills, tags, documents, applications, \u2026 } with url.";
1082
+ function skillsOf(value) {
1083
+ return list(value).map((entry) => {
1084
+ const match = /^(.+?)\s+(\d{1,2})$/.exec(entry);
1085
+ if (!match || Number(match[2]) < 1 || Number(match[2]) > 10) throw new CliError("USAGE", `--skill takes "name level" pairs with levels 1-10, such as "Go 8, React 5" (got "${entry}")`);
1086
+ return { name: match[1], level: Number(match[2]) };
1087
+ });
1088
+ }
1089
+ async function showTalent(hr, id) {
1090
+ const talent = await hr.get(`/talents/${id}`);
1091
+ const origin = await hr.appOrigin();
1092
+ return { ...talent, url: `${origin}/talents/${talent.id}`, ...talent.applications ? { applications: talent.applications.map((application) => ({ ...application, url: `${origin}/applications/${application.id}` })) } : {} };
1093
+ }
1094
+ async function uploadMeta(ctx) {
1095
+ const source = oneOf("--source", ctx.values.source ?? "upload", UploadSources);
1096
+ return {
1097
+ source,
1098
+ sourceNote: ctx.values.note ?? null,
1099
+ referrerPrincipalId: ctx.values.referrer ? await personId(ctx.hr, ctx.values.referrer) : null,
1100
+ jobId: await jobId(ctx.hr, ctx.values.job) ?? null
1101
+ };
1102
+ }
1103
+ async function filesForm(files, meta) {
1104
+ const form = new FormData();
1105
+ for (const file of files) {
1106
+ const bytes = await readFile3(file).catch(() => Promise.reject(new CliError("USAGE", `Cannot read ${file}`)));
1107
+ form.append(files.length === 1 ? "file" : "files", new Blob([bytes]), path2.basename(file));
379
1108
  }
1109
+ form.append("meta", JSON.stringify(meta));
1110
+ return form;
1111
+ }
1112
+ var UploadFlags = "--source upload|agency|referral [--note <agency name>] [--referrer <colleague>] [--job <job>]";
1113
+ var UploadHint = "--source says where the resume came from: an agency needs --note with its name, a referral needs --referrer. --job also files an application for that job.";
1114
+ var talentCommands = [
1115
+ {
1116
+ name: "talents search",
1117
+ usage: "hr talents search [text] [--job <job>] [--status <status>] [--rating S|A|B|C] [--source <source>] [--tag <tag>] [--pool <pool>] [--skill <name>] [--page n] [--page-size n]",
1118
+ does: "Talents in the pool, optionally matching text (name, headline, contact), applying to a job, or filtered. Page size defaults to 50, at most 200.",
1119
+ returns: "data: { total, items: [{ id, displayName, headline, status, rating, tags, skills, applicationCount, jobTitles, bestScore, url }] }. total counts every match, not just this page.",
1120
+ example: "hr talents search --page-size 1 # data.total is the size of the pool",
1121
+ run: async ({ hr, args, values, page: page2 }) => {
1122
+ const query = {
1123
+ q: args.join(" ") || void 0,
1124
+ jobId: await jobId(hr, values.job),
1125
+ status: oneOf("--status", values.status, Statuses2),
1126
+ rating: oneOf("--rating", values.rating, Ratings),
1127
+ source: oneOf("--source", values.source, Sources),
1128
+ tagId: values.tag ? await namedId(hr, "/tags", values.tag, "tag") : void 0,
1129
+ poolId: values.pool ? await namedId(hr, "/pools", values.pool, "pool") : void 0,
1130
+ skill: values.skill,
1131
+ ...page2
1132
+ };
1133
+ return linkedPage(hr, await hr.get("/talents", query), "talents");
1134
+ }
1135
+ },
1136
+ {
1137
+ name: "talents show",
1138
+ usage: "hr talents show <name|id>",
1139
+ does: "One talent with contacts (when the caller may see them), documents, skills, applications, evaluations, timeline and mail.",
1140
+ returns: "data: { id, displayName, \u2026, url, activities, evaluations, mail, applications: [{ id, jobTitle, stageName, status, url }] }",
1141
+ run: async (ctx) => showTalent(ctx.hr, await talentId(ctx.hr, joined(ctx, "a name or id")))
1142
+ },
1143
+ {
1144
+ name: "talents create",
1145
+ usage: "hr talents create --name <name> --source <source> [--json '{\u2026}']",
1146
+ does: `Add a person to the pool by hand (no resume; \`hr uploads add\` reads one). <source>: direct_email, job_board, referral, agency, upload or agent.${takesJson(`${TalentFields}, contacts [{ kind, value }], skills [{ name, level }]`)}`,
1147
+ returns: TalentReturns,
1148
+ run: async (ctx) => {
1149
+ const body = await bodyOf(ctx, { displayName: ctx.values.name, source: oneOf("--source", ctx.values.source, Sources) });
1150
+ if (!body.displayName || !body.source) throw new CliError("USAGE", "Pass --name and --source");
1151
+ return linkedOne(ctx.hr, await ctx.hr.post("/talents", body), "talents");
1152
+ }
1153
+ },
1154
+ {
1155
+ name: "talents update",
1156
+ usage: "hr talents update <name|id> [--name <name>] [--status active|hired|do_not_contact|archived] --json '{\u2026}'",
1157
+ does: `Change a talent's profile. do_not_contact stops all mail to them.${takesJson(`${TalentFields}, consentStatus (implied|notified|consented|withdrawn), incomplete`)}`,
1158
+ returns: TalentReturns,
1159
+ run: async (ctx) => {
1160
+ const id = await talentId(ctx.hr, joined(ctx, "a name or id"));
1161
+ return linkedOne(ctx.hr, await ctx.hr.patch(`/talents/${id}`, await bodyOf(ctx, { displayName: ctx.values.name, status: oneOf("--status", ctx.values.status, Statuses2) })), "talents");
1162
+ }
1163
+ },
1164
+ {
1165
+ name: "talents rate",
1166
+ usage: "hr talents rate <name|id> --rating S|A|B|C|none",
1167
+ does: "Set (or clear with none) the talent's overall rating.",
1168
+ returns: TalentReturns,
1169
+ run: async (ctx) => {
1170
+ const rating = needed("--rating", ctx.values.rating);
1171
+ if (rating !== "none") oneOf("--rating", rating, Ratings);
1172
+ return ctx.hr.put(`/talents/${await talentId(ctx.hr, joined(ctx, "a name or id"))}/rating`, { rating: rating === "none" ? null : rating });
1173
+ }
1174
+ },
1175
+ {
1176
+ name: "talents contact-add",
1177
+ usage: "hr talents contact-add <name|id> --kind email|phone|wechat|linkedin|github|other --value <value>",
1178
+ does: "Add a contact. One that already belongs to another talent is refused (they may be the same person: see `hr talents merge`).",
1179
+ returns: "data: the talent's contacts [{ id, kind, value, isPrimary }]",
1180
+ run: async (ctx) => ctx.hr.post(`/talents/${await talentId(ctx.hr, joined(ctx, "a name or id"))}/contacts`, { kind: oneOf("--kind", needed("--kind", ctx.values.kind), ContactKinds), value: needed("--value", ctx.values.value) })
1181
+ },
1182
+ {
1183
+ name: "talents contact-remove",
1184
+ usage: "hr talents contact-remove <talent id> <contact id>",
1185
+ does: "Remove a contact (ids from `hr talents show`).",
1186
+ returns: "data: { id }",
1187
+ run: ({ hr, args }) => hr.delete(`/talents/${needed("a talent id", args[0])}/contacts/${needed("a contact id", args[1])}`)
1188
+ },
1189
+ {
1190
+ name: "talents skills",
1191
+ usage: 'hr talents skills <name|id> --skill "Go 8, React 5"',
1192
+ does: "Add skills or change their level (1-10). Names go through the skill dictionary, so aliases count as one skill.",
1193
+ returns: "data: the talent's skills [{ skillId, name, level, evidence }]",
1194
+ run: async (ctx) => ctx.hr.put(`/talents/${await talentId(ctx.hr, joined(ctx, "a name or id"))}/skills`, { skills: skillsOf(needed("--skill", ctx.values.skill)) })
1195
+ },
1196
+ {
1197
+ name: "talents skill-remove",
1198
+ usage: "hr talents skill-remove <talent id> <skill id>",
1199
+ does: "Remove one skill from a talent.",
1200
+ returns: "data: { id }",
1201
+ run: ({ hr, args }) => hr.delete(`/talents/${needed("a talent id", args[0])}/skills/${needed("a skill id", args[1])}`)
1202
+ },
1203
+ {
1204
+ name: "talents tags",
1205
+ usage: 'hr talents tags <name|id> --tag "tag one, tag two"',
1206
+ does: 'Set a talent\'s tags (replacing the old ones; an empty --tag "" clears them). Tags by name or id, from `hr tags list`.',
1207
+ returns: "data: { tagIds }",
1208
+ run: async (ctx) => {
1209
+ const names = list(ctx.values.tag ?? "") ?? [];
1210
+ if (ctx.values.tag === void 0) throw new CliError("USAGE", "Pass --tag");
1211
+ const tagIds = await Promise.all(names.map((name) => namedId(ctx.hr, "/tags", name, "tag")));
1212
+ return ctx.hr.put(`/talents/${await talentId(ctx.hr, joined(ctx, "a name or id"))}/tags`, { tagIds });
1213
+ }
1214
+ },
1215
+ {
1216
+ name: "talents merge",
1217
+ usage: "hr talents merge <kept talent id> <merged talent id>",
1218
+ does: "Merge two records of the same person into the first: contacts, resumes, applications, evaluations and mail move over; the second is kept only as a pointer. Cannot be undone.",
1219
+ returns: "data: { id } of the kept talent.",
1220
+ run: ({ hr, args }) => hr.post(`/talents/${needed("the kept talent id", args[0])}/merge`, { mergeId: needed("the merged talent id", args[1]) })
1221
+ },
1222
+ {
1223
+ name: "talents export",
1224
+ usage: "hr talents export <name|id> [--out <file.json>]",
1225
+ does: "Everything HR holds about a person (PDPA access request): profile, contacts, applications, evaluations, mail and timeline. --out writes it to a file instead of printing it.",
1226
+ returns: "data: the export, or { file } when written to --out.",
1227
+ run: async (ctx) => {
1228
+ const data = await ctx.hr.get(`/talents/${await talentId(ctx.hr, joined(ctx, "a name or id"))}/export`);
1229
+ if (!ctx.values.out) return data;
1230
+ await writeFile2(ctx.values.out, JSON.stringify(data, null, 2));
1231
+ return { file: path2.resolve(ctx.values.out) };
1232
+ }
1233
+ },
1234
+ {
1235
+ name: "talents erase",
1236
+ usage: "hr talents erase <talent id> --confirm",
1237
+ does: "Erase a person (PDPA deletion request): their personal data, resumes and raw mail are deleted for good. Needs the id and --confirm.",
1238
+ returns: "data: { id }",
1239
+ run: ({ hr, args, values }) => {
1240
+ const id = needed("a talent id", args[0]);
1241
+ if (!isId(id)) throw new CliError("USAGE", "Erasing takes the talent's id, never a name");
1242
+ if (!values.confirm) throw new CliError("USAGE", "Erasing cannot be undone: pass --confirm");
1243
+ return hr.post(`/talents/${id}/erase`, { confirm: true });
1244
+ }
1245
+ },
1246
+ {
1247
+ name: "documents download",
1248
+ usage: "hr documents download <document id> [--out <file>]",
1249
+ does: "A resume or other document (ids in `hr talents show`): a link that works for a few minutes, or with --out the file itself.",
1250
+ returns: "data: { url, fileName, mime }, or { file, fileName, mime } with --out.",
1251
+ run: async ({ hr, args, values }) => {
1252
+ const link = await hr.get(`/documents/${needed("a document id", args[0])}/download`);
1253
+ if (!values.out) return link;
1254
+ await writeFile2(values.out, await hr.download(link.url));
1255
+ return { file: path2.resolve(values.out), fileName: link.fileName, mime: link.mime };
1256
+ }
1257
+ },
1258
+ // ---------- Tags and pools ----------
1259
+ { name: "tags list", usage: "hr tags list", does: "Tags, with how many talents carry each.", returns: "data: [{ id, name, color, count }]", run: ({ hr }) => hr.get("/tags") },
1260
+ {
1261
+ name: "tags create",
1262
+ usage: "hr tags create --name <name> [--color <color>]",
1263
+ does: "A new tag.",
1264
+ returns: "data: { id, name, color, count }",
1265
+ run: (ctx) => ctx.hr.post("/tags", { name: needed("--name", ctx.values.name), ...ctx.values.color ? { color: ctx.values.color } : {} })
1266
+ },
1267
+ { name: "tags delete", usage: "hr tags delete <tag name|id>", does: "Delete a tag (needs settings management).", returns: "data: { id }", run: async (ctx) => ctx.hr.delete(`/tags/${await namedId(ctx.hr, "/tags", joined(ctx, "a tag"), "tag")}`) },
1268
+ { name: "pools list", usage: "hr pools list", does: "Talent pools (hand-picked lists).", returns: "data: [{ id, name, description, ownerPrincipalId, members, createdAt }]", run: ({ hr }) => hr.get("/pools") },
1269
+ {
1270
+ name: "pools create",
1271
+ usage: "hr pools create --name <name> [--description <text>]",
1272
+ does: "A new talent pool.",
1273
+ returns: "data: the pool.",
1274
+ run: (ctx) => ctx.hr.post("/pools", { name: needed("--name", ctx.values.name), ...ctx.values.description ? { description: ctx.values.description } : {} })
1275
+ },
1276
+ {
1277
+ name: "pools update",
1278
+ usage: "hr pools update <pool name|id> [--name <name>] [--description <text>]",
1279
+ does: "Rename a pool or change its description.",
1280
+ returns: "data: the pool.",
1281
+ run: async (ctx) => {
1282
+ const id = await namedId(ctx.hr, "/pools", joined(ctx, "a pool"), "pool");
1283
+ const current = (await ctx.hr.get("/pools")).find((pool) => pool.id === id);
1284
+ return ctx.hr.patch(`/pools/${id}`, { name: ctx.values.name ?? current.name, description: ctx.values.description ?? current.description });
1285
+ }
1286
+ },
1287
+ { name: "pools delete", usage: "hr pools delete <pool name|id>", does: "Delete a pool (its talents stay in the pool of all talents).", returns: "data: { id }", run: async (ctx) => ctx.hr.delete(`/pools/${await namedId(ctx.hr, "/pools", joined(ctx, "a pool"), "pool")}`) },
1288
+ {
1289
+ name: "pools add",
1290
+ usage: "hr pools add <pool name|id> --talent <name|id>[,<name|id>\u2026] [--note <text>]",
1291
+ does: "Put talents into a pool.",
1292
+ returns: "data: { added }",
1293
+ run: async (ctx) => {
1294
+ const pool = await namedId(ctx.hr, "/pools", joined(ctx, "a pool"), "pool");
1295
+ const talentIds = await Promise.all((list(needed("--talent", ctx.values.talent)) ?? []).map((who) => talentId(ctx.hr, who)));
1296
+ return ctx.hr.post(`/pools/${pool}/members`, { talentIds, ...ctx.values.note ? { note: ctx.values.note } : {} });
1297
+ }
1298
+ },
1299
+ {
1300
+ name: "pools remove",
1301
+ usage: "hr pools remove <pool name|id> --talent <name|id>",
1302
+ does: "Take a talent out of a pool.",
1303
+ returns: "data: { id }",
1304
+ run: async (ctx) => ctx.hr.delete(`/pools/${await namedId(ctx.hr, "/pools", joined(ctx, "a pool"), "pool")}/members/${await talentId(ctx.hr, needed("--talent", ctx.values.talent))}`)
1305
+ },
1306
+ // ---------- Possible duplicates ----------
1307
+ {
1308
+ name: "review list",
1309
+ usage: "hr review list [--status open|resolved]",
1310
+ does: "Incoming candidates HR was not sure about: they may be a talent already in the pool. Each waits for a person to merge, create or ignore.",
1311
+ returns: "data: [{ id, reason, candidate, suspects: [{ id, displayName, \u2026 }], status, createdAt }]",
1312
+ run: ({ hr, values }) => hr.get("/review-items", { status: oneOf("--status", values.status, ["open", "resolved"]) })
1313
+ },
1314
+ {
1315
+ name: "review resolve",
1316
+ usage: "hr review resolve <item id> (--talent <talent id> | --status create|ignore)",
1317
+ does: "Decide a possible duplicate: --talent merges it into that talent (one of the suspects), --status create makes a new talent, --status ignore drops it.",
1318
+ returns: "data: { talentId }",
1319
+ run: ({ hr, args, values }) => {
1320
+ const id = needed("a review item id", args[0]);
1321
+ if (values.talent) return hr.post(`/review-items/${id}/resolve`, { resolution: "merged", talentId: values.talent });
1322
+ const resolution = oneOf("--status", needed("--talent <id> to merge, or --status create|ignore", values.status), ["create", "ignore"]);
1323
+ return hr.post(`/review-items/${id}/resolve`, { resolution: resolution === "create" ? "created" : "ignored" });
1324
+ }
1325
+ },
1326
+ // ---------- Uploads ----------
1327
+ {
1328
+ name: "uploads add",
1329
+ usage: `hr uploads add <file> ${UploadFlags}`,
1330
+ does: `Add one resume (PDF, Word, image or text) to the pool: HR reads it, then saves it as read, through the same path as mail (an existing talent is enriched, not duplicated). ${UploadHint} To check what was read before saving, use \`hr uploads preview\`.`,
1331
+ returns: "data: { upload, result: { status: created | linked | needs_review, talentId, applicationId } }",
1332
+ run: async (ctx) => {
1333
+ const meta = await uploadMeta(ctx);
1334
+ const preview = await ctx.hr.upload("/uploads/preview", await filesForm([needed("a file", ctx.args[0])], meta));
1335
+ return ctx.hr.post(`/uploads/${preview.upload.id}/confirm`, { candidate: preview.candidate, meta });
1336
+ }
1337
+ },
1338
+ {
1339
+ name: "uploads preview",
1340
+ usage: `hr uploads preview <file> ${UploadFlags}`,
1341
+ does: `Read one resume without saving it: what HR extracted, and whether the person is already in the pool. Save it with \`hr uploads confirm\`. ${UploadHint}`,
1342
+ returns: "data: { upload: { id }, candidate: { name, contacts, headline, \u2026 }, existingTalentId, suspectedTalentIds }",
1343
+ run: async (ctx) => ctx.hr.upload("/uploads/preview", await filesForm([needed("a file", ctx.args[0])], await uploadMeta(ctx)))
1344
+ },
1345
+ {
1346
+ name: "uploads confirm",
1347
+ usage: `hr uploads confirm <upload id> --json '{"candidate":{\u2026}}'`,
1348
+ does: "Save a previewed resume, with the candidate as read or corrected (the candidate object from `hr uploads preview`).",
1349
+ returns: "data: { upload, result: { status, talentId, applicationId } }",
1350
+ run: async (ctx) => {
1351
+ const body = await bodyOf(ctx);
1352
+ if (!body.candidate) throw new CliError("USAGE", "Pass --json with the candidate from `hr uploads preview`");
1353
+ return ctx.hr.post(`/uploads/${needed("an upload id", ctx.args[0])}/confirm`, body);
1354
+ }
1355
+ },
1356
+ {
1357
+ name: "uploads batch",
1358
+ usage: `hr uploads batch <file> [<file>\u2026] ${UploadFlags}`,
1359
+ does: `Add many resumes (or a .zip of them) at once; HR reads and saves them in the background. Follow with \`hr uploads list --batch <id>\`. ${UploadHint}`,
1360
+ returns: "data: { batchId, uploads: [{ id, fileName, status }] }",
1361
+ run: async (ctx) => {
1362
+ if (!ctx.args.length) throw new CliError("USAGE", "Pass the files to upload");
1363
+ return ctx.hr.upload("/uploads/batch", await filesForm(ctx.args, await uploadMeta(ctx)));
1364
+ }
1365
+ },
1366
+ {
1367
+ name: "uploads list",
1368
+ usage: "hr uploads list [--batch <batch id>]",
1369
+ does: "The caller's uploads, or one batch's, with how each went.",
1370
+ returns: "data: [{ id, fileName, status, talentId, applicationId, error, createdAt }]",
1371
+ run: ({ hr, values }) => hr.get("/uploads", { batchId: values.batch })
1372
+ }
1373
+ ];
1374
+
1375
+ // src/run.ts
1376
+ var Groups = [
1377
+ { title: "Sign-in, people and approvals", commands: coreCommands },
1378
+ { title: "Screening, interviews, replies, evaluations, reports", commands: recruitingCommands },
1379
+ { title: "Applications", commands: applicationCommands },
1380
+ { title: "Talents, tags, pools, possible duplicates, uploads", commands: talentCommands },
1381
+ { title: "Jobs and reject reasons", commands: jobCommands },
1382
+ { title: "Mail and mailboxes", commands: mailCommands },
1383
+ { title: "Settings: pipelines, scorecards, skills, templates, job boards, webhook", commands: settingsCommands }
1384
+ ];
1385
+ var Commands = Groups.flatMap((group) => group.commands);
1386
+ var Overall = `hr: SpringBrand HR from the command line. Output is JSON on stdout.
1387
+
1388
+ Setup
1389
+ HR_API_URL this deployment's HR address (or --api-url)
1390
+ HR_AGENT_KEY an Agent key from IAM; without it, run \`hr login\`
1391
+ IAM_URL optional; by default HR says where IAM is
1392
+
1393
+ Commands (\`hr <command> --help\` shows what one takes and returns; \`hr <group> --help\` lists a group)
1394
+ ${Groups.map((group) => `
1395
+ ${group.title}
1396
+ ${group.commands.map((command) => ` ${command.usage}`).join("\n")}`).join("\n")}
1397
+
1398
+ Every command prints { ok: true, data } or { ok: false, error: { code, message } }.
1399
+ <job> is a title, slug or id; a talent or candidate is a name or id (AMBIGUOUS lists the matches).
1400
+ Talents, applications and jobs carry url, their page in the HR console.
1401
+ --json takes an object (or @file) for the fields a command has no flag for.
1402
+ A command without the permission answers with data.pendingApproval: the action waits for a person to decide in IAM.`;
1403
+ function find(words) {
1404
+ for (const length of [2, 1]) {
1405
+ const name = words.slice(0, length).join(" ");
1406
+ const command = Commands.find((entry) => entry.name === name);
1407
+ if (command) return { command, rest: words.slice(length) };
1408
+ }
1409
+ return null;
1410
+ }
1411
+ function describe(command) {
1412
+ return [command.usage, "", command.does, "", `Returns ${command.returns}`, ...command.example ? ["", `Example: ${command.example}`] : []].join("\n");
1413
+ }
1414
+ function helpFor(args) {
1415
+ const words = args.filter((arg) => !arg.startsWith("-"));
1416
+ const found = find(words.slice(0, 2));
1417
+ if (found) return describe(found.command);
1418
+ const group = Commands.filter((command) => command.name.split(" ")[0] === words[0]);
1419
+ if (group.length) return group.map(describe).join("\n\n---\n\n");
1420
+ return Overall;
1421
+ }
1422
+ async function dispatch(args, deps) {
1423
+ const { values, positionals } = parseArgs({ args, options: Options, allowPositionals: true });
1424
+ const found = find(positionals);
1425
+ if (!found) throw new CliError("USAGE", `Unknown command: ${positionals.join(" ") || "(none)"}. Run \`hr --help\``);
1426
+ const hr = new Hr(deps, values["api-url"]);
1427
+ return found.command.run({ hr, deps, values, args: found.rest, page: { page: values.page, pageSize: values["page-size"] } });
380
1428
  }
381
1429
  async function run(args, deps) {
382
1430
  if (!args.length || args.includes("--help") || args.includes("-h")) {