maidang 29.11.1 → 29.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -184,60 +184,6 @@ var career_default = {
184
184
  // src/constants/api.ts
185
185
  var DEFAULT_API_URL = "https://api.maidang.me";
186
186
 
187
- // src/utils/api-client.ts
188
- var cachedTicket = null;
189
- var PUBLIC_CONTENT_READ = /^\/v1\/(?:posts|projects|career|changelog|links|skills|tools|images|news|activity|music|sitemap)(?:\/|$)/;
190
- function apiBaseUrl() {
191
- return (process.env.MAIDANG_API_URL || DEFAULT_API_URL).replace(/\/+$/, "");
192
- }
193
- function resolveUrl(path) {
194
- if (path.startsWith("http://") || path.startsWith("https://")) return path;
195
- return `${apiBaseUrl()}${path.startsWith("/") ? path : `/${path}`}`;
196
- }
197
- async function visitorTicket() {
198
- if (cachedTicket) return cachedTicket;
199
- try {
200
- const response = await fetch(`${apiBaseUrl()}/v1/auth/tickets`, {
201
- method: "POST",
202
- headers: {
203
- accept: "application/json",
204
- "content-type": "application/json"
205
- },
206
- body: "{}"
207
- });
208
- if (!response.ok) return null;
209
- const payload = await response.json();
210
- const ticket = payload.data?.ticket;
211
- if (typeof ticket !== "string" || !ticket) return null;
212
- cachedTicket = ticket;
213
- return ticket;
214
- } catch {
215
- return null;
216
- }
217
- }
218
- function isAnonymousContentRead(url, method) {
219
- const verb = method.toUpperCase();
220
- if (verb !== "GET" && verb !== "HEAD") return false;
221
- try {
222
- return PUBLIC_CONTENT_READ.test(new URL(url).pathname);
223
- } catch {
224
- return false;
225
- }
226
- }
227
- async function apiFetch(path, init) {
228
- const headers = new Headers(init?.headers);
229
- if (!headers.has("accept")) headers.set("accept", "application/json");
230
- const url = resolveUrl(path);
231
- const method = init?.method ?? "GET";
232
- const first = await fetch(url, { ...init, headers });
233
- if (first.status !== 401 || headers.has("authorization") || isAnonymousContentRead(url, method)) return first;
234
- const ticket = await visitorTicket();
235
- if (!ticket) return first;
236
- const authed = new Headers(headers);
237
- authed.set("authorization", `Bearer ${ticket}`);
238
- return fetch(url, { ...init, headers: authed });
239
- }
240
-
241
187
  // src/utils/api-response.ts
242
188
  var ApiRequestError = class extends Error {
243
189
  constructor(message, status) {
@@ -278,28 +224,153 @@ async function readApiData(response) {
278
224
  return payload;
279
225
  }
280
226
 
227
+ // src/utils/api-client.ts
228
+ var TICKET_ERROR = "\u9886\u53D6\u8BBF\u5BA2\u7968\u5931\u8D25\uFF0C\u6682\u65F6\u6CA1\u6CD5\u5F00\u59CB\u5BF9\u8BDD";
229
+ function apiBaseUrl() {
230
+ return (process.env.MAIDANG_API_URL || DEFAULT_API_URL).replace(/\/+$/, "");
231
+ }
232
+ function resolveUrl(path) {
233
+ if (path.startsWith("http://") || path.startsWith("https://")) return path;
234
+ return `${apiBaseUrl()}${path.startsWith("/") ? path : `/${path}`}`;
235
+ }
236
+ async function apiFetch(path, init) {
237
+ const headers = new Headers(init?.headers);
238
+ if (!headers.has("accept")) headers.set("accept", "application/json");
239
+ return fetch(resolveUrl(path), { ...init, headers });
240
+ }
241
+ function readableTicketFailure(message) {
242
+ const text = message.trim();
243
+ if (!text || /^[A-Za-z0-9_ .-]+$/.test(text)) return TICKET_ERROR;
244
+ return text;
245
+ }
246
+ async function issueVisitorTicket() {
247
+ let response;
248
+ try {
249
+ response = await fetch(`${apiBaseUrl()}/v1/auth/tickets`, {
250
+ method: "POST",
251
+ headers: {
252
+ accept: "application/json",
253
+ "content-type": "application/json"
254
+ },
255
+ body: "{}"
256
+ });
257
+ } catch {
258
+ throw new ApiRequestError(TICKET_ERROR, 401);
259
+ }
260
+ let message = "";
261
+ let code;
262
+ let ticket;
263
+ try {
264
+ const payload = await response.json();
265
+ code = payload.code;
266
+ if (typeof payload.message === "string") message = payload.message;
267
+ ticket = payload.data?.ticket;
268
+ } catch {
269
+ ticket = void 0;
270
+ }
271
+ const accepted = response.ok && (typeof code !== "number" || code === 0);
272
+ if (accepted && typeof ticket === "string" && ticket.startsWith("tkt_") && ticket.length > "tkt_".length) {
273
+ return ticket;
274
+ }
275
+ throw new ApiRequestError(readableTicketFailure(message), 401);
276
+ }
277
+
281
278
  // src/utils/os-agent-api.ts
282
- import { mkdirSync, readFileSync, writeFileSync } from "fs";
279
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "fs";
283
280
  import { homedir } from "os";
284
281
  import { join } from "path";
285
282
  var AGENT_HEADER = "x-maidang-agent";
286
283
  var CONFIG_DIR = process.env.MAIDANG_CLI_HOME || join(homedir(), ".maidang");
287
284
  var CONFIG_PATH = join(CONFIG_DIR, "cli.json");
288
285
  var RUN_TIMEOUT_MS = 18e4;
289
- function loadConfig() {
286
+ var RESUME_MISS = "\u8FD9\u4E2A\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u5F53\u524D\u8BBF\u5BA2\u7968\u636E\uFF0C\u65E0\u6CD5\u7EED\u63A5";
287
+ function readConfigString(value) {
288
+ return typeof value === "string" && value.trim() ? value : void 0;
289
+ }
290
+ function usableVisitorTicket(value) {
291
+ if (typeof value !== "string") return void 0;
292
+ const ticket = value.trim();
293
+ if (!ticket.startsWith("tkt_") || ticket.length <= "tkt_".length) return void 0;
294
+ return ticket;
295
+ }
296
+ function readConfigFile() {
290
297
  try {
291
- return JSON.parse(readFileSync(CONFIG_PATH, "utf8"));
298
+ const raw = JSON.parse(readFileSync(CONFIG_PATH, "utf8"));
299
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
300
+ return { ...raw };
292
301
  } catch {
293
302
  return {};
294
303
  }
295
304
  }
296
- function saveConfig(config) {
305
+ function loadConfig() {
306
+ const record = readConfigFile();
307
+ const config = {};
308
+ const agentToken = readConfigString(record.agentToken);
309
+ const sessionId = readConfigString(record.sessionId);
310
+ const visitorTicket = usableVisitorTicket(record.visitorTicket);
311
+ if (agentToken) config.agentToken = agentToken;
312
+ if (sessionId) config.sessionId = sessionId;
313
+ if (visitorTicket) config.visitorTicket = visitorTicket;
314
+ return config;
315
+ }
316
+ function writeConfig(next) {
297
317
  try {
298
318
  mkdirSync(CONFIG_DIR, { recursive: true });
299
- writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), { mode: 384 });
319
+ writeFileSync(CONFIG_PATH, JSON.stringify(next, null, 2), { mode: 384 });
320
+ chmodSync(CONFIG_PATH, 384);
300
321
  } catch {
301
322
  }
302
323
  }
324
+ function saveConfig(patch) {
325
+ const next = readConfigFile();
326
+ if (patch.agentToken) next.agentToken = patch.agentToken;
327
+ if (patch.sessionId) next.sessionId = patch.sessionId;
328
+ if (patch.visitorTicket) next.visitorTicket = patch.visitorTicket;
329
+ writeConfig(next);
330
+ }
331
+ function clearStoredVisitorTicket() {
332
+ const next = readConfigFile();
333
+ if (!Object.prototype.hasOwnProperty.call(next, "visitorTicket")) return;
334
+ delete next.visitorTicket;
335
+ writeConfig(next);
336
+ }
337
+ function saveVisitorTicket(ticket) {
338
+ const current = loadConfig();
339
+ saveConfig({
340
+ visitorTicket: ticket,
341
+ ...current.sessionId ? { sessionId: current.sessionId } : {}
342
+ });
343
+ }
344
+ async function ensureVisitorTicket(config) {
345
+ if (config.visitorTicket) return config.visitorTicket;
346
+ const ticket = await issueVisitorTicket();
347
+ saveVisitorTicket(ticket);
348
+ return ticket;
349
+ }
350
+ async function refreshVisitorTicket(auth) {
351
+ auth.refreshed = true;
352
+ clearStoredVisitorTicket();
353
+ auth.ticket = await issueVisitorTicket();
354
+ saveVisitorTicket(auth.ticket);
355
+ }
356
+ async function chatFetch(auth, path, init) {
357
+ const send = () => {
358
+ const headers = new Headers(init.headers);
359
+ headers.set("authorization", `Bearer ${auth.ticket}`);
360
+ return apiFetch(path, { ...init, headers });
361
+ };
362
+ const first = await send();
363
+ if (first.status !== 401 || auth.refreshed) return first;
364
+ await first.body?.cancel().catch(() => void 0);
365
+ await refreshVisitorTicket(auth);
366
+ return send();
367
+ }
368
+ async function rejectChat(response, sessionId) {
369
+ if (sessionId && response.status === 404) {
370
+ throw new ApiRequestError(RESUME_MISS, response.status);
371
+ }
372
+ return readError(response);
373
+ }
303
374
  function readLastSessionId() {
304
375
  return loadConfig().sessionId;
305
376
  }
@@ -326,9 +397,13 @@ async function readError(response) {
326
397
  }
327
398
  async function runAgentChat(input) {
328
399
  const config = loadConfig();
400
+ const auth = {
401
+ ticket: await ensureVisitorTicket(config),
402
+ refreshed: false
403
+ };
329
404
  const token = config.agentToken;
330
405
  const sessionId = input.sessionId;
331
- const runsResponse = await apiFetch("/v1/hat/runs", {
406
+ const runsResponse = await chatFetch(auth, "/v1/hat/runs", {
332
407
  method: "POST",
333
408
  headers: {
334
409
  "Content-Type": "application/json",
@@ -343,19 +418,18 @@ async function runAgentChat(input) {
343
418
  }
344
419
  })
345
420
  });
346
- if (!runsResponse.ok) await readError(runsResponse);
421
+ if (!runsResponse.ok) await rejectChat(runsResponse, sessionId);
347
422
  const issuedToken = runsResponse.headers.get(AGENT_HEADER) ?? token;
348
423
  const queued = (await runsResponse.json()).data ?? {};
349
424
  const runId = queued.runId ?? queued.id;
350
425
  const newSessionId = queued.sessionId ?? "";
351
426
  if (!runId) throw new Error("\u670D\u52A1\u7AEF\u672A\u8FD4\u56DE runId");
352
- if (issuedToken || newSessionId) {
353
- saveConfig({
354
- ...issuedToken ? { agentToken: issuedToken } : {},
355
- ...newSessionId ? { sessionId: newSessionId } : {}
356
- });
357
- }
358
- const eventsResponse = await apiFetch(`/v1/hat/runs/${runId}/events`, {
427
+ saveConfig({
428
+ ...issuedToken ? { agentToken: issuedToken } : {},
429
+ ...newSessionId ? { sessionId: newSessionId } : {},
430
+ visitorTicket: auth.ticket
431
+ });
432
+ const eventsResponse = await chatFetch(auth, `/v1/hat/runs/${runId}/events`, {
359
433
  method: "POST",
360
434
  headers: {
361
435
  accept: "text/event-stream",
@@ -363,7 +437,7 @@ async function runAgentChat(input) {
363
437
  },
364
438
  signal: AbortSignal.timeout(RUN_TIMEOUT_MS)
365
439
  });
366
- if (!eventsResponse.ok) await readError(eventsResponse);
440
+ if (!eventsResponse.ok) await rejectChat(eventsResponse, sessionId);
367
441
  if (!eventsResponse.body) throw new Error("\u4E8B\u4EF6\u6D41\u4E3A\u7A7A");
368
442
  let response = "";
369
443
  let deltaText = "";
@@ -1813,15 +1887,28 @@ import { Command as Command10 } from "commander";
1813
1887
  import chalk2 from "chalk";
1814
1888
 
1815
1889
  // src/utils/contact-api.ts
1816
- async function sendContactMessage(input) {
1817
- const res = await apiFetch("/v1/contact", {
1890
+ function postContact(input, ticket) {
1891
+ return apiFetch("/v1/contact", {
1818
1892
  method: "POST",
1819
1893
  headers: {
1820
- "Content-Type": "application/json"
1894
+ "Content-Type": "application/json",
1895
+ ...ticket ? { authorization: `Bearer ${ticket}` } : {}
1821
1896
  },
1822
1897
  body: JSON.stringify(input)
1823
1898
  });
1824
- return readApiData(res);
1899
+ }
1900
+ async function sendContactMessage(input) {
1901
+ const first = await postContact(input);
1902
+ if (first.status !== 401) return readApiData(first);
1903
+ let ticket = null;
1904
+ try {
1905
+ ticket = await issueVisitorTicket();
1906
+ } catch {
1907
+ ticket = null;
1908
+ }
1909
+ if (!ticket) return readApiData(first);
1910
+ await first.body?.cancel().catch(() => void 0);
1911
+ return readApiData(await postContact(input, ticket));
1825
1912
  }
1826
1913
 
1827
1914
  // src/commands/contact.ts