jitda-agent 0.1.2 → 0.1.4

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/install.mjs CHANGED
@@ -41,8 +41,8 @@ var require_windows = __commonJS({
41
41
  "node_modules/isexe/windows.js"(exports, module) {
42
42
  module.exports = isexe;
43
43
  isexe.sync = sync;
44
- var fs3 = __require("fs");
45
- function checkPathExt(path3, options) {
44
+ var fs9 = __require("fs");
45
+ function checkPathExt(path9, options) {
46
46
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
47
47
  if (!pathext) {
48
48
  return true;
@@ -53,25 +53,25 @@ var require_windows = __commonJS({
53
53
  }
54
54
  for (var i = 0; i < pathext.length; i++) {
55
55
  var p = pathext[i].toLowerCase();
56
- if (p && path3.substr(-p.length).toLowerCase() === p) {
56
+ if (p && path9.substr(-p.length).toLowerCase() === p) {
57
57
  return true;
58
58
  }
59
59
  }
60
60
  return false;
61
61
  }
62
- function checkStat(stat, path3, options) {
62
+ function checkStat(stat, path9, options) {
63
63
  if (!stat.isSymbolicLink() && !stat.isFile()) {
64
64
  return false;
65
65
  }
66
- return checkPathExt(path3, options);
66
+ return checkPathExt(path9, options);
67
67
  }
68
- function isexe(path3, options, cb) {
69
- fs3.stat(path3, function(er, stat) {
70
- cb(er, er ? false : checkStat(stat, path3, options));
68
+ function isexe(path9, options, cb) {
69
+ fs9.stat(path9, function(er, stat) {
70
+ cb(er, er ? false : checkStat(stat, path9, options));
71
71
  });
72
72
  }
73
- function sync(path3, options) {
74
- return checkStat(fs3.statSync(path3), path3, options);
73
+ function sync(path9, options) {
74
+ return checkStat(fs9.statSync(path9), path9, options);
75
75
  }
76
76
  }
77
77
  });
@@ -81,14 +81,14 @@ var require_mode = __commonJS({
81
81
  "node_modules/isexe/mode.js"(exports, module) {
82
82
  module.exports = isexe;
83
83
  isexe.sync = sync;
84
- var fs3 = __require("fs");
85
- function isexe(path3, options, cb) {
86
- fs3.stat(path3, function(er, stat) {
84
+ var fs9 = __require("fs");
85
+ function isexe(path9, options, cb) {
86
+ fs9.stat(path9, function(er, stat) {
87
87
  cb(er, er ? false : checkStat(stat, options));
88
88
  });
89
89
  }
90
- function sync(path3, options) {
91
- return checkStat(fs3.statSync(path3), options);
90
+ function sync(path9, options) {
91
+ return checkStat(fs9.statSync(path9), options);
92
92
  }
93
93
  function checkStat(stat, options) {
94
94
  return stat.isFile() && checkMode(stat, options);
@@ -112,7 +112,7 @@ var require_mode = __commonJS({
112
112
  // node_modules/isexe/index.js
113
113
  var require_isexe = __commonJS({
114
114
  "node_modules/isexe/index.js"(exports, module) {
115
- var fs3 = __require("fs");
115
+ var fs9 = __require("fs");
116
116
  var core;
117
117
  if (process.platform === "win32" || global.TESTING_WINDOWS) {
118
118
  core = require_windows();
@@ -121,7 +121,7 @@ var require_isexe = __commonJS({
121
121
  }
122
122
  module.exports = isexe;
123
123
  isexe.sync = sync;
124
- function isexe(path3, options, cb) {
124
+ function isexe(path9, options, cb) {
125
125
  if (typeof options === "function") {
126
126
  cb = options;
127
127
  options = {};
@@ -131,7 +131,7 @@ var require_isexe = __commonJS({
131
131
  throw new TypeError("callback not provided");
132
132
  }
133
133
  return new Promise(function(resolve, reject) {
134
- isexe(path3, options || {}, function(er, is) {
134
+ isexe(path9, options || {}, function(er, is) {
135
135
  if (er) {
136
136
  reject(er);
137
137
  } else {
@@ -140,7 +140,7 @@ var require_isexe = __commonJS({
140
140
  });
141
141
  });
142
142
  }
143
- core(path3, options || {}, function(er, is) {
143
+ core(path9, options || {}, function(er, is) {
144
144
  if (er) {
145
145
  if (er.code === "EACCES" || options && options.ignoreErrors) {
146
146
  er = null;
@@ -150,9 +150,9 @@ var require_isexe = __commonJS({
150
150
  cb(er, is);
151
151
  });
152
152
  }
153
- function sync(path3, options) {
153
+ function sync(path9, options) {
154
154
  try {
155
- return core.sync(path3, options || {});
155
+ return core.sync(path9, options || {});
156
156
  } catch (er) {
157
157
  if (options && options.ignoreErrors || er.code === "EACCES") {
158
158
  return false;
@@ -168,7 +168,7 @@ var require_isexe = __commonJS({
168
168
  var require_which = __commonJS({
169
169
  "node_modules/which/which.js"(exports, module) {
170
170
  var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
171
- var path3 = __require("path");
171
+ var path9 = __require("path");
172
172
  var COLON = isWindows ? ";" : ":";
173
173
  var isexe = require_isexe();
174
174
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -206,7 +206,7 @@ var require_which = __commonJS({
206
206
  return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
207
207
  const ppRaw = pathEnv[i];
208
208
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
209
- const pCmd = path3.join(pathPart, cmd);
209
+ const pCmd = path9.join(pathPart, cmd);
210
210
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
211
211
  resolve(subStep(p, i, 0));
212
212
  });
@@ -233,7 +233,7 @@ var require_which = __commonJS({
233
233
  for (let i = 0; i < pathEnv.length; i++) {
234
234
  const ppRaw = pathEnv[i];
235
235
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
236
- const pCmd = path3.join(pathPart, cmd);
236
+ const pCmd = path9.join(pathPart, cmd);
237
237
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
238
238
  for (let j = 0; j < pathExt.length; j++) {
239
239
  const cur = p + pathExt[j];
@@ -281,7 +281,7 @@ var require_path_key = __commonJS({
281
281
  var require_resolveCommand = __commonJS({
282
282
  "node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
283
283
  "use strict";
284
- var path3 = __require("path");
284
+ var path9 = __require("path");
285
285
  var which = require_which();
286
286
  var getPathKey = require_path_key();
287
287
  function resolveCommandAttempt(parsed, withoutPathExt) {
@@ -299,7 +299,7 @@ var require_resolveCommand = __commonJS({
299
299
  try {
300
300
  resolved = which.sync(parsed.command, {
301
301
  path: env[getPathKey({ env })],
302
- pathExt: withoutPathExt ? path3.delimiter : void 0
302
+ pathExt: withoutPathExt ? path9.delimiter : void 0
303
303
  });
304
304
  } catch (e) {
305
305
  } finally {
@@ -308,7 +308,7 @@ var require_resolveCommand = __commonJS({
308
308
  }
309
309
  }
310
310
  if (resolved) {
311
- resolved = path3.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
311
+ resolved = path9.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
312
312
  }
313
313
  return resolved;
314
314
  }
@@ -362,8 +362,8 @@ var require_shebang_command = __commonJS({
362
362
  if (!match) {
363
363
  return null;
364
364
  }
365
- const [path3, argument] = match[0].replace(/#! ?/, "").split(" ");
366
- const binary = path3.split("/").pop();
365
+ const [path9, argument] = match[0].replace(/#! ?/, "").split(" ");
366
+ const binary = path9.split("/").pop();
367
367
  if (binary === "env") {
368
368
  return argument;
369
369
  }
@@ -376,16 +376,16 @@ var require_shebang_command = __commonJS({
376
376
  var require_readShebang = __commonJS({
377
377
  "node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
378
378
  "use strict";
379
- var fs3 = __require("fs");
379
+ var fs9 = __require("fs");
380
380
  var shebangCommand = require_shebang_command();
381
381
  function readShebang(command) {
382
382
  const size = 150;
383
383
  const buffer = Buffer.alloc(size);
384
384
  let fd;
385
385
  try {
386
- fd = fs3.openSync(command, "r");
387
- fs3.readSync(fd, buffer, 0, size, 0);
388
- fs3.closeSync(fd);
386
+ fd = fs9.openSync(command, "r");
387
+ fs9.readSync(fd, buffer, 0, size, 0);
388
+ fs9.closeSync(fd);
389
389
  } catch (e) {
390
390
  }
391
391
  return shebangCommand(buffer.toString());
@@ -398,7 +398,7 @@ var require_readShebang = __commonJS({
398
398
  var require_parse = __commonJS({
399
399
  "node_modules/cross-spawn/lib/parse.js"(exports, module) {
400
400
  "use strict";
401
- var path3 = __require("path");
401
+ var path9 = __require("path");
402
402
  var resolveCommand = require_resolveCommand();
403
403
  var escape = require_escape();
404
404
  var readShebang = require_readShebang();
@@ -423,7 +423,7 @@ var require_parse = __commonJS({
423
423
  const needsShell = !isExecutableRegExp.test(commandFile);
424
424
  if (parsed.options.forceShell || needsShell) {
425
425
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
426
- parsed.command = path3.normalize(parsed.command);
426
+ parsed.command = path9.normalize(parsed.command);
427
427
  parsed.command = escape.command(parsed.command);
428
428
  parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
429
429
  const shellCommand = [parsed.command].concat(parsed.args).join(" ");
@@ -513,7 +513,7 @@ var require_cross_spawn = __commonJS({
513
513
  var cp = __require("child_process");
514
514
  var parse = require_parse();
515
515
  var enoent = require_enoent();
516
- function spawn(command, args, options) {
516
+ function spawn2(command, args, options) {
517
517
  const parsed = parse(command, args, options);
518
518
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
519
519
  enoent.hookChildProcess(spawned, parsed);
@@ -525,8 +525,8 @@ var require_cross_spawn = __commonJS({
525
525
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
526
526
  return result;
527
527
  }
528
- module.exports = spawn;
529
- module.exports.spawn = spawn;
528
+ module.exports = spawn2;
529
+ module.exports.spawn = spawn2;
530
530
  module.exports.sync = spawnSync;
531
531
  module.exports._parse = parse;
532
532
  module.exports._enoent = enoent;
@@ -535,45 +535,2458 @@ var require_cross_spawn = __commonJS({
535
535
 
536
536
  // src/install.ts
537
537
  var import_cross_spawn = __toESM(require_cross_spawn(), 1);
538
+ import fs8 from "node:fs";
539
+ import os6 from "node:os";
540
+ import path8 from "node:path";
541
+ import { fileURLToPath } from "node:url";
542
+
543
+ // src/outbox.ts
544
+ import crypto from "node:crypto";
538
545
  import fs2 from "node:fs";
539
- import os2 from "node:os";
540
546
  import path2 from "node:path";
541
- import { fileURLToPath } from "node:url";
542
547
 
543
- // src/store.ts
544
- import fs from "node:fs";
545
- import os from "node:os";
546
- import path from "node:path";
547
- function stateHome() {
548
- return process.env.JITDA_MCP_HOME || path.join(os.homedir(), ".jitda", "mcp");
548
+ // src/api.ts
549
+ var TIMEOUT_MS = 1e4;
550
+ var ApiError = class extends Error {
551
+ constructor(status, body, revoked = false) {
552
+ super(`HTTP ${status}: ${(typeof body === "string" ? body : JSON.stringify(body) ?? "").slice(0, 200)}`);
553
+ this.status = status;
554
+ this.body = body;
555
+ this.revoked = revoked;
556
+ }
557
+ status;
558
+ body;
559
+ revoked;
560
+ /** JSON:API 오류의 title (예: OutsidePeriod) */
561
+ get title() {
562
+ return this.firstError?.title ?? null;
563
+ }
564
+ /** JSON:API 오류의 meta (예: 이미 등록된 다른 폴더의 PC 이름·등록 시각) */
565
+ get meta() {
566
+ return this.firstError?.meta ?? null;
567
+ }
568
+ /** JSON:API 오류의 detail. rails 가 사람이 읽을 한국어 설명을 넣는다 */
569
+ get detail() {
570
+ return this.firstError?.detail ?? null;
571
+ }
572
+ get firstError() {
573
+ return this.body?.errors?.[0];
574
+ }
575
+ };
576
+ var JitdaApi = class {
577
+ constructor(baseUrl, fetchImpl = globalThis.fetch) {
578
+ this.fetchImpl = fetchImpl;
579
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
580
+ }
581
+ fetchImpl;
582
+ baseUrl;
583
+ async send(method, pathname, { auth, body } = {}) {
584
+ const response = await this.fetchImpl(`${this.baseUrl}${pathname}`, {
585
+ method,
586
+ headers: {
587
+ Accept: "application/json",
588
+ ...body ? { "Content-Type": "application/json" } : {},
589
+ ...auth ? { Authorization: auth } : {}
590
+ },
591
+ body: body ? JSON.stringify(body) : void 0,
592
+ signal: AbortSignal.timeout(TIMEOUT_MS)
593
+ });
594
+ const text = await response.text();
595
+ let parsed = text;
596
+ try {
597
+ parsed = text ? JSON.parse(text) : null;
598
+ } catch {
599
+ }
600
+ if (!response.ok) throw new ApiError(response.status, parsed, response.headers.get("x-agent-workspace-revoked") === "true");
601
+ return { status: response.status, body: parsed };
602
+ }
603
+ async request(method, pathname, options = {}) {
604
+ return (await this.send(method, pathname, options)).body;
605
+ }
606
+ /**
607
+ * 일회용 코드 로그인 요청을 등록한다(인증 없음). 참가자가 웹에서 user_code 를 보고 승인하면
608
+ * 서버가 이 폴더를 작업 폴더로 등록하고, device_code 로 결과를 받는다. 사람 토큰은 PC 로 오지 않는다.
609
+ */
610
+ async createLoginRequest(input) {
611
+ const body = await this.request("POST", "/api/v1/agent/login_requests", {
612
+ body: {
613
+ agent: input.agent,
614
+ folder_label: input.folderLabel,
615
+ cwd_fingerprint: input.cwdFingerprint,
616
+ machine_label: input.machineLabel,
617
+ ...input.hackathonId ? { hackathon_id: input.hackathonId } : {},
618
+ ...input.loopbackPort ? { loopback_port: input.loopbackPort } : {}
619
+ }
620
+ });
621
+ const attributes = body?.data?.attributes ?? {};
622
+ const deviceCode = attributes.device_code;
623
+ const userCode = attributes.user_code;
624
+ if (typeof deviceCode !== "string" || !deviceCode || typeof userCode !== "string" || !userCode) {
625
+ throw new Error("\uC11C\uBC84\uAC00 \uB85C\uADF8\uC778 \uD655\uC778 \uCF54\uB4DC\uB97C \uC8FC\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4");
626
+ }
627
+ return {
628
+ device_code: deviceCode,
629
+ user_code: userCode,
630
+ expires_at: typeof attributes.expires_at === "string" ? attributes.expires_at : null,
631
+ interval: typeof attributes.interval === "number" ? attributes.interval : null
632
+ };
633
+ }
634
+ /**
635
+ * 로그인 요청의 결과를 묻는다(인증 없음, device_code 로). 아직 승인 전이면 pending(202),
636
+ * 승인됐으면 서버가 그 자리에서 작업 폴더를 등록하고 POST /workspace 와 같은 응답(201)을 준다.
637
+ * 다른 폴더가 활성이면 409 AnotherFolderActive, 거절은 403 LoginDenied, 없음·만료·이미 씀은 404 (ApiError).
638
+ * 로컬 콜백 요청은 브라우저가 넘긴 approvalCode 가 맞아야 등록되고, 없거나 틀리면 계속 pending 이다.
639
+ */
640
+ async pollLoginToken(deviceCode, replace = false, approvalCode = null) {
641
+ const { status, body } = await this.send("POST", "/api/v1/agent/login_requests/token", {
642
+ body: { device_code: deviceCode, replace, ...approvalCode ? { approval_code: approvalCode } : {} }
643
+ });
644
+ if (status === 202) {
645
+ const interval = body?.meta?.interval;
646
+ return { status: "pending", interval: typeof interval === "number" ? interval : null };
647
+ }
648
+ return { status: "registered", workspace: workspaceFromResponse(body) };
649
+ }
650
+ /**
651
+ * 더 쓰지 않을 로그인 요청을 취소한다(인증 없음, device_code 로). 서버는 pending/approved 면 거절로 바꾸고 204,
652
+ * 그 밖에는 그냥 204 를 준다(멱등). 이전 브라우저 탭에서 늦게 승인해도 쓸 수 없게 하는 정리용이라 실패해도 무시한다(던지지 않는다).
653
+ */
654
+ async cancelLoginRequest(deviceCode) {
655
+ try {
656
+ await this.send("POST", "/api/v1/agent/login_requests/cancel", { body: { device_code: deviceCode } });
657
+ } catch {
658
+ }
659
+ }
660
+ async showWorkspace(workspaceToken) {
661
+ return workspaceFromResponse(await this.request("GET", "/api/v1/agent/workspace", { auth: `token ${workspaceToken}` }));
662
+ }
663
+ postEvents(workspaceToken, batch) {
664
+ return this.request("POST", "/api/v1/agent/events", { auth: `token ${workspaceToken}`, body: batch });
665
+ }
666
+ };
667
+ function workspaceFromResponse(body) {
668
+ const doc = body;
669
+ const included = doc?.included ?? [];
670
+ const profile = included.find((item) => item.type === "profile");
671
+ const hackathon = included.find((item) => item.type === "hackathon");
672
+ const team = included.find((item) => item.type === "team");
673
+ return {
674
+ workspace_id: String(doc?.data?.id ?? ""),
675
+ token: doc?.data?.attributes?.token ?? null,
676
+ profile_name: profile?.attributes?.name ?? null,
677
+ profile_id: profile?.id ? String(profile.id) : null,
678
+ hackathon_id: hackathon?.id ?? null,
679
+ hackathon_name: hackathon?.attributes?.name ?? null,
680
+ team_name: team && !team.attributes?.is_personal ? team.attributes?.name ?? null : null
681
+ };
682
+ }
683
+
684
+ // src/store.ts
685
+ import fs from "node:fs";
686
+ import os from "node:os";
687
+ import path from "node:path";
688
+ function stateHome() {
689
+ return process.env.JITDA_MCP_HOME || path.join(os.homedir(), ".jitda", "mcp");
690
+ }
691
+ function folderDir(fp) {
692
+ return path.join(stateHome(), "folders", fp);
693
+ }
694
+ function configFile() {
695
+ return path.join(stateHome(), "config.json");
696
+ }
697
+ function readServerConfig() {
698
+ return readJson(configFile()) ?? {};
699
+ }
700
+ function writeServerConfig(config) {
701
+ if (!config.api_url && !config.web_url) {
702
+ fs.rmSync(configFile(), { force: true });
703
+ return;
704
+ }
705
+ writeAtomic(configFile(), `${JSON.stringify(config, null, 2)}
706
+ `, 384);
707
+ }
708
+ function writeAtomic(file, text, mode) {
709
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
710
+ const tmp = `${file}.${process.pid}.tmp`;
711
+ fs.writeFileSync(tmp, text, mode ? { mode } : void 0);
712
+ if (mode) fs.chmodSync(tmp, mode);
713
+ fs.renameSync(tmp, file);
714
+ }
715
+ function readJson(file) {
716
+ try {
717
+ return JSON.parse(fs.readFileSync(file, "utf8"));
718
+ } catch {
719
+ return null;
720
+ }
721
+ }
722
+ function credentialsDir() {
723
+ return path.join(stateHome(), "credentials");
724
+ }
725
+ function credentialFile(fp) {
726
+ return path.join(credentialsDir(), `${fp.replace(/[^A-Za-z0-9_.-]/g, "_")}.json`);
727
+ }
728
+ function readCredentials() {
729
+ let names;
730
+ try {
731
+ names = fs.readdirSync(credentialsDir());
732
+ } catch {
733
+ return {};
734
+ }
735
+ const all = {};
736
+ for (const name of names) {
737
+ if (!name.endsWith(".json")) continue;
738
+ const credential = readJson(path.join(credentialsDir(), name));
739
+ if (credential) all[name.slice(0, -".json".length)] = credential;
740
+ }
741
+ return all;
742
+ }
743
+ function credentialFor(fp) {
744
+ return readJson(credentialFile(fp));
745
+ }
746
+ function saveCredential(fp, credential) {
747
+ writeAtomic(credentialFile(fp), `${JSON.stringify(credential, null, 2)}
748
+ `, 384);
749
+ }
750
+ function removeCredential(fp, token) {
751
+ if (token !== void 0 && credentialFor(fp)?.token !== token) return;
752
+ fs.rmSync(credentialFile(fp), { force: true });
753
+ }
754
+ function sessionFile(fp, agent, sessionId) {
755
+ return path.join(folderDir(fp), "sessions", `${agent}__${sessionId.replace(/[^A-Za-z0-9_.-]/g, "_")}.json`);
756
+ }
757
+ var STALE_LOCK_MS = 3e4;
758
+ function tryLockSession(fp, agent, sessionId, retry = true) {
759
+ const file = `${sessionFile(fp, agent, sessionId)}.lock`;
760
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
761
+ try {
762
+ const fd = fs.openSync(file, "wx");
763
+ fs.writeSync(fd, String(process.pid));
764
+ fs.closeSync(fd);
765
+ return () => fs.rmSync(file, { force: true });
766
+ } catch (error) {
767
+ if (error.code !== "EEXIST") throw error;
768
+ try {
769
+ if (retry && Date.now() - fs.statSync(file).mtimeMs > STALE_LOCK_MS) {
770
+ fs.rmSync(file, { force: true });
771
+ return tryLockSession(fp, agent, sessionId, false);
772
+ }
773
+ } catch {
774
+ }
775
+ return null;
776
+ }
777
+ }
778
+ function loadSession(fp, agent, sessionId) {
779
+ return readJson(sessionFile(fp, agent, sessionId)) ?? {
780
+ agent,
781
+ session_id: sessionId,
782
+ transcript_path: null,
783
+ offset: 0,
784
+ seq: 0,
785
+ started_at: null,
786
+ cwd: null,
787
+ codex: {}
788
+ };
789
+ }
790
+ function saveSession(fp, state) {
791
+ writeAtomic(sessionFile(fp, state.agent, state.session_id), JSON.stringify(state));
792
+ }
793
+ function listSessions(fp) {
794
+ const dir = path.join(folderDir(fp), "sessions");
795
+ let names;
796
+ try {
797
+ names = fs.readdirSync(dir);
798
+ } catch {
799
+ return [];
800
+ }
801
+ return names.filter((name) => name.endsWith(".json")).flatMap((name) => readJson(path.join(dir, name)) ?? []);
802
+ }
803
+ function loginOutcomeFile(fp) {
804
+ return path.join(folderDir(fp), "login-outcome.json");
805
+ }
806
+ function saveLoginOutcome(fp, outcome) {
807
+ writeAtomic(loginOutcomeFile(fp), JSON.stringify(outcome), 384);
808
+ }
809
+ function movedFile(fp) {
810
+ return path.join(folderDir(fp), "moved-away.json");
811
+ }
812
+ function markMovedAway(fp) {
813
+ writeAtomic(movedFile(fp), JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString() }));
814
+ }
815
+ function movedAway(fp) {
816
+ return readJson(movedFile(fp));
817
+ }
818
+ function clearMovedAway(fp) {
819
+ fs.rmSync(movedFile(fp), { force: true });
820
+ }
821
+ function discardLoginOutcome(fp, message) {
822
+ const file = loginOutcomeFile(fp);
823
+ if (readJson(file)?.message === message) fs.rmSync(file, { force: true });
824
+ }
825
+ function takeLoginOutcome(fp) {
826
+ const file = loginOutcomeFile(fp);
827
+ const outcome = readJson(file);
828
+ if (outcome) fs.rmSync(file, { force: true });
829
+ return outcome;
830
+ }
831
+
832
+ // src/outbox.ts
833
+ var MAX_BATCH = 500;
834
+ var STALE_SENDING_MS = 12e4;
835
+ function destinationKey(dest) {
836
+ return crypto.createHash("sha256").update(`${dest.api_url}|${dest.hackathon_id}|${dest.workspace_id}`).digest("hex").slice(0, 16);
837
+ }
838
+ function outboxDir(fp, dest) {
839
+ return path2.join(folderDir(fp), "outbox", dest);
840
+ }
841
+ function toLines(entries) {
842
+ return entries.map((entry) => `${JSON.stringify(entry)}
843
+ `).join("");
844
+ }
845
+ function publish(file, entries) {
846
+ fs2.mkdirSync(path2.dirname(file), { recursive: true, mode: 448 });
847
+ const tmp = `${file}.${process.pid}-${crypto.randomBytes(4).toString("hex")}.tmp`;
848
+ fs2.writeFileSync(tmp, toLines(entries));
849
+ fs2.renameSync(tmp, file);
850
+ }
851
+ function readDestinationMeta(dir) {
852
+ try {
853
+ return JSON.parse(fs2.readFileSync(path2.join(dir, "destination.json"), "utf8"));
854
+ } catch {
855
+ return null;
856
+ }
857
+ }
858
+ function writeDestinationMeta(fp, dest, meta) {
859
+ const dir = outboxDir(fp, dest);
860
+ const current = readDestinationMeta(dir);
861
+ if (current && (current.profile_id || !meta.profile_id)) return;
862
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
863
+ const file = path2.join(dir, "destination.json");
864
+ const tmp = `${file}.${process.pid}-${crypto.randomBytes(4).toString("hex")}.tmp`;
865
+ fs2.writeFileSync(tmp, JSON.stringify(meta));
866
+ fs2.renameSync(tmp, file);
867
+ }
868
+ function adoptPending(fp, dest, match) {
869
+ const root = path2.join(folderDir(fp), "outbox");
870
+ let moved = 0;
871
+ for (const other of listDir(root)) {
872
+ if (other === dest) continue;
873
+ const dir = path2.join(root, other);
874
+ const meta = readDestinationMeta(dir);
875
+ if (!meta || !match(meta)) continue;
876
+ for (const name of listDir(dir)) {
877
+ const isSending = name.endsWith(".sending");
878
+ if (!name.endsWith(".jsonl") && !isSending) continue;
879
+ const file = path2.join(dir, name);
880
+ try {
881
+ if (isSending && Date.now() - fs2.statSync(file).mtimeMs < STALE_SENDING_MS) continue;
882
+ const original = isSending ? `${name.split(".jsonl.")[0]}.jsonl` : name;
883
+ const count = countEntries(file);
884
+ fs2.mkdirSync(outboxDir(fp, dest), { recursive: true, mode: 448 });
885
+ let target = path2.join(outboxDir(fp, dest), original);
886
+ if (fs2.existsSync(target)) target = target.replace(/\.jsonl$/, `-${crypto.randomBytes(4).toString("hex")}.jsonl`);
887
+ fs2.renameSync(file, target);
888
+ moved += count;
889
+ } catch {
890
+ }
891
+ }
892
+ }
893
+ return moved;
894
+ }
895
+ function appendOutbox(fp, dest, entries) {
896
+ if (!entries.length) return;
897
+ const name = `${Date.now().toString().padStart(15, "0")}-${process.pid}-${crypto.randomBytes(4).toString("hex")}.jsonl`;
898
+ publish(path2.join(outboxDir(fp, dest), name), entries);
899
+ }
900
+ function parseEntries(text) {
901
+ const out = [];
902
+ for (const line of text.split("\n")) {
903
+ if (!line.trim()) continue;
904
+ try {
905
+ out.push(JSON.parse(line));
906
+ } catch {
907
+ }
908
+ }
909
+ return out;
910
+ }
911
+ function countEntries(file) {
912
+ try {
913
+ return parseEntries(fs2.readFileSync(file, "utf8")).length;
914
+ } catch {
915
+ return 0;
916
+ }
917
+ }
918
+ function listDir(dir) {
919
+ try {
920
+ return fs2.readdirSync(dir).sort();
921
+ } catch {
922
+ return [];
923
+ }
924
+ }
925
+ function pendingCount(fp, dest) {
926
+ const root = path2.join(folderDir(fp), "outbox");
927
+ const dirs = dest ? [outboxDir(fp, dest)] : listDir(root).map((name) => path2.join(root, name));
928
+ let total = 0;
929
+ for (const dir of dirs) {
930
+ for (const name of listDir(dir)) {
931
+ if (name.endsWith(".jsonl") || name.endsWith(".sending")) total += countEntries(path2.join(dir, name));
932
+ }
933
+ }
934
+ return total;
935
+ }
936
+ function touch(file) {
937
+ try {
938
+ const now = /* @__PURE__ */ new Date();
939
+ fs2.utimesSync(file, now, now);
940
+ } catch {
941
+ }
942
+ }
943
+ function claimOne(dir, skip, listing) {
944
+ let busy = false;
945
+ for (; ; ) {
946
+ if (listing.next >= listing.names.length) {
947
+ const fresh = listDir(dir).filter((name2) => !listing.seen.has(name2));
948
+ if (!fresh.length) break;
949
+ for (const name2 of fresh) listing.seen.add(name2);
950
+ listing.names = fresh;
951
+ listing.next = 0;
952
+ }
953
+ const name = listing.names[listing.next++];
954
+ let original;
955
+ if (name.endsWith(".jsonl")) {
956
+ original = name;
957
+ } else if (name.endsWith(".sending")) {
958
+ try {
959
+ if (Date.now() - fs2.statSync(path2.join(dir, name)).mtimeMs < STALE_SENDING_MS) {
960
+ busy = true;
961
+ continue;
962
+ }
963
+ } catch {
964
+ continue;
965
+ }
966
+ original = `${name.split(".jsonl.")[0]}.jsonl`;
967
+ } else {
968
+ continue;
969
+ }
970
+ if (skip.has(original)) continue;
971
+ if (!fs2.existsSync(path2.join(dir, name))) continue;
972
+ const claimed = path2.join(dir, `${original}.${process.pid}-${crypto.randomBytes(4).toString("hex")}.sending`);
973
+ try {
974
+ fs2.renameSync(path2.join(dir, name), claimed);
975
+ touch(claimed);
976
+ return { claim: { claimed, original: path2.join(dir, original) }, busy };
977
+ } catch {
978
+ }
979
+ }
980
+ return { claim: null, busy };
981
+ }
982
+ var MAX_BATCH_BYTES = 1024 * 1024;
983
+ function batches(entries) {
984
+ const out = [];
985
+ let current = [];
986
+ let bytes = 0;
987
+ for (const entry of entries) {
988
+ const size = Buffer.byteLength(JSON.stringify(entry.event));
989
+ if (current.length && (current.length >= MAX_BATCH || bytes + size > MAX_BATCH_BYTES)) {
990
+ out.push(current);
991
+ current = [];
992
+ bytes = 0;
993
+ }
994
+ current.push(entry);
995
+ bytes += size;
996
+ }
997
+ if (current.length) out.push(current);
998
+ return out;
999
+ }
1000
+ function retryableStatus(status) {
1001
+ return status === 404 || status === 408 || status === 429 || status >= 500;
1002
+ }
1003
+ var SPLIT_422_BUDGET = 32;
1004
+ var SPLIT_PAUSE_MS = 500;
1005
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1006
+ async function sendSplitting(api, token, batch, result, budget) {
1007
+ if (budget.left422 <= 0 || budget.stop()) {
1008
+ budget.deferred.push(...batch);
1009
+ return;
1010
+ }
1011
+ try {
1012
+ budget.heartbeat();
1013
+ await sendChunk(api, token, batch);
1014
+ result.sent += batch.length;
1015
+ for (const entry of batch) budget.handled.add(entry);
1016
+ } catch (error) {
1017
+ if (!(error instanceof ApiError) || error.status !== 413 && error.status !== 422) throw error;
1018
+ if (error.status === 422) budget.left422 -= 1;
1019
+ if (batch.length === 1) {
1020
+ result.dropped += 1;
1021
+ result.error = error.message;
1022
+ budget.handled.add(batch[0]);
1023
+ return;
1024
+ }
1025
+ const half = Math.ceil(batch.length / 2);
1026
+ await sendSplitting(api, token, batch.slice(0, half), result, budget);
1027
+ await sendSplitting(api, token, batch.slice(half), result, budget);
1028
+ }
1029
+ }
1030
+ async function flushOutbox(fp, dest, api, token, shouldStop = () => false, splitPauseMs = SPLIT_PAUSE_MS) {
1031
+ const result = { sent: 0, dropped: 0, remaining: 0, error: null, retryable: false, unauthorized: false, busy: false };
1032
+ const dir = outboxDir(fp, dest);
1033
+ const done = /* @__PURE__ */ new Set();
1034
+ const listing = { names: [], next: 0, seen: /* @__PURE__ */ new Set() };
1035
+ let halted = false;
1036
+ let dropRest = false;
1037
+ while (!halted && !shouldStop()) {
1038
+ const { claim, busy } = claimOne(dir, done, listing);
1039
+ result.busy ||= busy;
1040
+ if (!claim) break;
1041
+ const { claimed, original } = claim;
1042
+ done.add(path2.basename(original));
1043
+ let entries;
1044
+ try {
1045
+ entries = parseEntries(fs2.readFileSync(claimed, "utf8"));
1046
+ } catch (error) {
1047
+ result.error = `\uBCF4\uB0BC \uAE30\uB85D\uC744 \uC77D\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${error instanceof Error ? error.message : error}`;
1048
+ result.retryable = true;
1049
+ restore(claimed, original);
1050
+ continue;
1051
+ }
1052
+ const keep = [];
1053
+ let sentFromFile = 0;
1054
+ for (const batch of batches(entries)) {
1055
+ if (dropRest) {
1056
+ result.dropped += batch.length;
1057
+ continue;
1058
+ }
1059
+ if (halted || shouldStop()) {
1060
+ keep.push(...batch);
1061
+ continue;
1062
+ }
1063
+ let pending = batch;
1064
+ let handled = /* @__PURE__ */ new Set();
1065
+ try {
1066
+ for (let round = 0; pending.length; round++) {
1067
+ if (round > 0) {
1068
+ if (shouldStop()) {
1069
+ keep.push(...pending);
1070
+ break;
1071
+ }
1072
+ await sleep(splitPauseMs);
1073
+ }
1074
+ handled = /* @__PURE__ */ new Set();
1075
+ const budget = { left422: SPLIT_422_BUDGET, stop: shouldStop, deferred: [], handled, heartbeat: () => touch(claimed) };
1076
+ await sendSplitting(api, token, pending, result, budget);
1077
+ const progressed = handled.size;
1078
+ sentFromFile += progressed;
1079
+ handled = /* @__PURE__ */ new Set();
1080
+ pending = budget.deferred;
1081
+ if (pending.length && shouldStop()) {
1082
+ keep.push(...pending);
1083
+ break;
1084
+ }
1085
+ if (pending.length && progressed === 0) {
1086
+ keep.push(...pending);
1087
+ result.retryable = true;
1088
+ break;
1089
+ }
1090
+ }
1091
+ } catch (error) {
1092
+ result.error = error instanceof Error ? error.message : String(error);
1093
+ if (handled.size) {
1094
+ sentFromFile += handled.size;
1095
+ pending = pending.filter((entry) => !handled.has(entry));
1096
+ }
1097
+ if (!(error instanceof ApiError)) {
1098
+ result.retryable = true;
1099
+ halted = true;
1100
+ keep.push(...pending);
1101
+ } else if (error.status === 403 && error.title === "OutsidePeriod") {
1102
+ result.dropped += pending.length;
1103
+ sentFromFile += pending.length;
1104
+ dropRest = true;
1105
+ } else if (error.status === 401 || error.status === 403) {
1106
+ result.unauthorized = error.status === 401;
1107
+ if (error.revoked) result.revoked = true;
1108
+ halted = true;
1109
+ keep.push(...pending);
1110
+ } else if (retryableStatus(error.status)) {
1111
+ result.retryable = true;
1112
+ halted = true;
1113
+ keep.push(...pending);
1114
+ } else {
1115
+ result.dropped += pending.length;
1116
+ sentFromFile += pending.length;
1117
+ }
1118
+ }
1119
+ }
1120
+ if (keep.length && sentFromFile === 0 && !dropRest) {
1121
+ restore(claimed, original);
1122
+ continue;
1123
+ }
1124
+ if (keep.length) publish(original, keep);
1125
+ fs2.rmSync(claimed, { force: true });
1126
+ }
1127
+ result.remaining = pendingCount(fp, dest);
1128
+ return result;
1129
+ }
1130
+ function restore(claimed, original) {
1131
+ try {
1132
+ fs2.renameSync(claimed, original);
1133
+ } catch {
1134
+ }
1135
+ }
1136
+ async function sendChunk(api, token, chunk) {
1137
+ const groups = /* @__PURE__ */ new Map();
1138
+ for (const entry of chunk) {
1139
+ const id = `${entry.agent}:${entry.session.external_session_id}`;
1140
+ const list = groups.get(id) ?? [];
1141
+ list.push(entry);
1142
+ groups.set(id, list);
1143
+ }
1144
+ for (const list of groups.values()) {
1145
+ const latest = list[list.length - 1].session;
1146
+ await api.postEvents(token, { agent: list[0].agent, session: latest, events: list.map((entry) => entry.event) });
1147
+ }
1148
+ }
1149
+
1150
+ // src/recorder.ts
1151
+ import fs7 from "node:fs";
1152
+ import os5 from "node:os";
1153
+ import path7 from "node:path";
1154
+
1155
+ // src/redact.ts
1156
+ var KEEP_PREFIX = /* @__PURE__ */ new Set();
1157
+ function prefixed(pattern) {
1158
+ KEEP_PREFIX.add(pattern);
1159
+ return pattern;
1160
+ }
1161
+ var JWT_RUN = /[A-Za-z0-9_.-]{22,}/g;
1162
+ function jwtInRun(run2) {
1163
+ let dot = -1;
1164
+ for (let from = 0; ; ) {
1165
+ const at = run2.indexOf("eyJ", from);
1166
+ if (at < 0) return run2;
1167
+ if (at === 0 || "-._".includes(run2[at - 1])) {
1168
+ if (dot < at + 3) dot = run2.indexOf(".", at + 3);
1169
+ if (dot < 0) return run2;
1170
+ if (dot - (at + 3) >= 8 && run2.length - dot - 1 >= 10) return `${run2.slice(0, at)}[REDACTED]`;
1171
+ }
1172
+ from = at + 3;
1173
+ }
1174
+ }
1175
+ var PATTERNS = [
1176
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
1177
+ // END 줄이 없는(잘린) 개인키 블록: 머리글 뒤의 키 본문을 끝까지 가린다(앞부분만 보고 가릴 때 END 가 잘려 나가도 새지 않게)
1178
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[A-Za-z0-9+/=\s]*/g,
1179
+ /\b(sk|rk)-[A-Za-z0-9_-]{16,}\b/g,
1180
+ // Stripe 등: sk_live_…, sk_test_…, rk_live_…
1181
+ /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{10,}\b/g,
1182
+ /\bsk-ant-[A-Za-z0-9_-]{16,}\b/g,
1183
+ /\bAKIA[0-9A-Z]{16}\b/g,
1184
+ /\b(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b/g,
1185
+ /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,
1186
+ /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g,
1187
+ /\bAIza[0-9A-Za-z_-]{30,}\b/g,
1188
+ // JWT 는 위 JWT_RUN·jwtInRun 으로 가린다(정규식 하나로는 긴 글에서 되돌아가며 느려진다)
1189
+ JWT_RUN,
1190
+ // 앞부분(키 이름, "Bearer ")은 남기고 값만 가린다
1191
+ prefixed(/(\b(?:Bearer|Basic)\s+)[A-Za-z0-9._~+/=-]{16,}/gi),
1192
+ prefixed(/((?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|client[_-]?secret)["']?\s*[=:]\s*["']?)([^\s"'&<>]{6,})/gi),
1193
+ // .env 처럼 이름 앞뒤에 다른 말이 붙은 대문자 키: SECRET_KEY_BASE=…, STRIPE_SECRET_KEY=…, WALLET_PRIVATE_KEY=…
1194
+ // 대문자·밑줄만, 앞뒤 길이에 상한을 둬 긴 글에서 느려지지 않게 하고 코드의 tokenCount = … 같은 대입은 건드리지 않는다
1195
+ prefixed(/(\b[A-Z0-9_]{0,40}(?:SECRET|PASSWORD|PASSWD|TOKEN|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CREDENTIALS?)[A-Z0-9_]{0,40}["']?[ \t]*[=:][ \t]*["']?)([^\s"'&<>]{6,})/g),
1196
+ // 주소 속 사용자 정보: postgres://user:비밀번호@host → 비밀번호만 가린다(각 부분 길이에 상한)
1197
+ prefixed(/(\b[a-z][a-z0-9+.-]{0,20}:\/\/[^\s/:@]{1,128}:)([^\s/@]{1,256})(?=@)/gi),
1198
+ // 짓다 입장권 링크(…/ticket#name=…&code=…)의 참여 코드와 이름. 붙여 넣으면 대화 기록에 남는다
1199
+ prefixed(/([#&?]code=)[A-Za-z0-9]{4,}/gi),
1200
+ // 이름 값은 길이로 자르지 않고 끝까지 가린다(한글 이름은 퍼센트 인코딩으로 한 글자에 9자). 앞부분에만 상한을 둬 느려지지 않게
1201
+ prefixed(/(\/ticket[^\s#]{0,256}#(?:[^\s&]{0,256}&){0,32}name=)[^\s&]+/gi)
1202
+ ];
1203
+ function redact(text) {
1204
+ if (!text) return text;
1205
+ let out = text;
1206
+ for (const pattern of PATTERNS) {
1207
+ if (pattern === JWT_RUN) out = out.replace(pattern, jwtInRun);
1208
+ else out = out.replace(pattern, (_match, prefix) => KEEP_PREFIX.has(pattern) ? `${prefix}[REDACTED]` : "[REDACTED]");
1209
+ }
1210
+ return out;
1211
+ }
1212
+ var SECRET_KEY = /(?:^|_)(?:password|passwd|secret|token|api_?key|access_?key|private_?key|secret_?key|client_?secret|authorization|cookie)$/;
1213
+ function isSecretKey(key) {
1214
+ return SECRET_KEY.test(
1215
+ key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase()
1216
+ );
1217
+ }
1218
+ var CLIP_MARGIN = 8192;
1219
+ var CLIP_WINDOW_MAX = 256 * 1024;
1220
+ function redactClip(text, limit) {
1221
+ if (text.length <= limit) return redact(text);
1222
+ let window = limit + CLIP_MARGIN;
1223
+ for (; ; ) {
1224
+ const whole = window >= text.length;
1225
+ const out = redact(whole ? text : text.slice(0, window));
1226
+ const safe = whole ? out.length : out.length - CLIP_MARGIN;
1227
+ if (whole || safe >= limit || window >= CLIP_WINDOW_MAX) {
1228
+ const kept = out.slice(0, Math.max(0, Math.min(limit, safe)));
1229
+ if (whole && out.length <= limit) return out;
1230
+ return `${kept}\u2026[+${Math.max(0, text.length - window) + Math.max(0, out.length - kept.length)}]`;
1231
+ }
1232
+ window = Math.min(text.length, window * 2);
1233
+ }
1234
+ }
1235
+ function redactDeep(value, depth = 0, limit) {
1236
+ if (typeof value === "string") return limit ? redactClip(value, limit) : redact(value);
1237
+ if (depth > 8) return value && typeof value === "object" ? "[\uC0DD\uB7B5: \uB108\uBB34 \uAE4A\uC740 \uAC12]" : value;
1238
+ if (Array.isArray(value)) return value.map((item) => redactDeep(item, depth + 1, limit));
1239
+ if (value && typeof value === "object") {
1240
+ const out = {};
1241
+ for (const [key, item] of Object.entries(value)) {
1242
+ out[key] = typeof item === "string" && item && isSecretKey(key) ? "[REDACTED]" : redactDeep(item, depth + 1, limit);
1243
+ }
1244
+ return out;
1245
+ }
1246
+ return value;
1247
+ }
1248
+
1249
+ // src/events.ts
1250
+ var SCHEMA_VERSION = 1;
1251
+ var TEXT_LIMIT = 2e4;
1252
+ var TOOL_LIMIT = 4e3;
1253
+ function safeText(text, limit = TEXT_LIMIT) {
1254
+ return redactClip(typeof text === "string" ? text : "", limit);
1255
+ }
1256
+ var HOOK_EVENT_TYPES = {
1257
+ SessionStart: "session_start",
1258
+ Stop: "stop",
1259
+ SubagentStop: "stop",
1260
+ PreCompact: "compact",
1261
+ SessionEnd: "session_end"
1262
+ };
1263
+ function hookEvent(agent, input, now = /* @__PURE__ */ new Date()) {
1264
+ const type = HOOK_EVENT_TYPES[input.hook_event_name];
1265
+ if (!type) return null;
1266
+ const payload = { hook: input.hook_event_name };
1267
+ for (const key of ["source", "reason", "trigger", "model", "turn_id", "agent_id", "agent_type"]) {
1268
+ if (input[key]) payload[key] = input[key];
1269
+ }
1270
+ if ((input.hook_event_name === "Stop" || input.hook_event_name === "SessionEnd") && input.last_assistant_message) {
1271
+ payload.last_assistant_message = safeText(input.last_assistant_message);
1272
+ }
1273
+ const occurred = now.toISOString();
1274
+ return {
1275
+ event_key: `${agent}:${input.session_id}:${input.hook_event_name}:${input.turn_id ?? occurred}`,
1276
+ event_type: type,
1277
+ role: null,
1278
+ schema_version: SCHEMA_VERSION,
1279
+ occurred_at: occurred,
1280
+ payload
1281
+ };
1282
+ }
1283
+ function normalizeUsage(u) {
1284
+ const input = u.input ?? 0;
1285
+ const cacheRead = u.cacheRead ?? 0;
1286
+ return {
1287
+ input_tokens: Math.max(0, input - cacheRead),
1288
+ output_tokens: u.output ?? 0,
1289
+ cache_read_input_tokens: cacheRead,
1290
+ cache_creation_input_tokens: u.cacheWrite ?? 0,
1291
+ reasoning_output_tokens: u.reasoning ?? 0
1292
+ };
1293
+ }
1294
+
1295
+ // src/transcript.ts
1296
+ import fs3 from "node:fs";
1297
+ var CHUNK = 4 * 1024 * 1024;
1298
+ var READ_BUDGET = 16 * 1024 * 1024;
1299
+ var MAX_LINE = 8 * 1024 * 1024;
1300
+ function readNewLines(file, offset, budget = READ_BUDGET) {
1301
+ let fd;
1302
+ try {
1303
+ fd = fs3.openSync(file, "r");
1304
+ } catch {
1305
+ return { lines: [], offset, done: true, skipped: 0 };
1306
+ }
1307
+ try {
1308
+ const size = fs3.fstatSync(fd).size;
1309
+ if (size < offset) offset = 0;
1310
+ const lines = [];
1311
+ let partial = [];
1312
+ let partialLength = 0;
1313
+ let skipping = false;
1314
+ let skipped = 0;
1315
+ let committed = offset;
1316
+ let pos = offset;
1317
+ const buffer = Buffer.alloc(Math.max(1, Math.min(CHUNK, budget, size - offset)));
1318
+ while (pos < size && (skipping || committed === offset || pos - offset < budget)) {
1319
+ const n = fs3.readSync(fd, buffer, 0, Math.min(buffer.length, size - pos), pos);
1320
+ if (n <= 0) break;
1321
+ const chunk = buffer.subarray(0, n);
1322
+ let start = 0;
1323
+ for (; ; ) {
1324
+ const newline = chunk.indexOf(10, start);
1325
+ if (newline === -1) break;
1326
+ const piece = chunk.subarray(start, newline);
1327
+ if (skipping || partialLength + piece.length > MAX_LINE) {
1328
+ skipping = false;
1329
+ skipped += 1;
1330
+ } else {
1331
+ const line = partialLength ? Buffer.concat([...partial, piece]) : piece;
1332
+ if (line.length) lines.push(line.toString("utf8"));
1333
+ }
1334
+ partial = [];
1335
+ partialLength = 0;
1336
+ start = newline + 1;
1337
+ committed = pos + newline + 1;
1338
+ }
1339
+ const rest = chunk.subarray(start);
1340
+ if (!skipping && rest.length) {
1341
+ partial.push(Buffer.from(rest));
1342
+ partialLength += rest.length;
1343
+ if (partialLength > MAX_LINE) {
1344
+ skipping = true;
1345
+ partial = [];
1346
+ partialLength = 0;
1347
+ }
1348
+ }
1349
+ pos += n;
1350
+ }
1351
+ return { lines, offset: committed, done: pos >= size, skipped };
1352
+ } finally {
1353
+ fs3.closeSync(fd);
1354
+ }
1355
+ }
1356
+ function parseLines(lines) {
1357
+ const out = [];
1358
+ for (const line of lines) {
1359
+ try {
1360
+ out.push(JSON.parse(line));
1361
+ } catch {
1362
+ }
1363
+ }
1364
+ return out;
1365
+ }
1366
+
1367
+ // src/adapters/claude.ts
1368
+ function blockText(content) {
1369
+ if (typeof content === "string") return content;
1370
+ if (!Array.isArray(content)) return "";
1371
+ return content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
1372
+ }
1373
+ function transcriptEvents(lines, sessionId) {
1374
+ const events = [];
1375
+ for (const entry of parseLines(lines)) {
1376
+ const event = toEvent(entry, sessionId);
1377
+ if (event) events.push(event);
1378
+ }
1379
+ return events;
1380
+ }
1381
+ function toEvent(entry, sessionId) {
1382
+ if (!entry?.uuid || !entry.message) return null;
1383
+ const message = entry.message;
1384
+ const base = {
1385
+ event_key: `claude:${sessionId}:${entry.uuid}`,
1386
+ schema_version: SCHEMA_VERSION,
1387
+ occurred_at: entry.timestamp || (/* @__PURE__ */ new Date()).toISOString()
1388
+ };
1389
+ const common = {
1390
+ uuid: entry.uuid,
1391
+ parent_uuid: entry.parentUuid ?? null,
1392
+ sidechain: Boolean(entry.isSidechain),
1393
+ agent_id: entry.agentId ?? null,
1394
+ cwd: entry.cwd ?? null,
1395
+ version: entry.version ?? null
1396
+ };
1397
+ if (entry.type === "user") {
1398
+ const content = message.content;
1399
+ const results = Array.isArray(content) ? content.filter((block) => block?.type === "tool_result") : [];
1400
+ if (results.length) {
1401
+ return {
1402
+ ...base,
1403
+ event_type: "tool_result",
1404
+ role: "user",
1405
+ payload: {
1406
+ ...common,
1407
+ results: results.map((block) => ({
1408
+ tool_use_id: block.tool_use_id,
1409
+ is_error: Boolean(block.is_error),
1410
+ content: safeText(blockText(block.content), TOOL_LIMIT)
1411
+ }))
1412
+ }
1413
+ };
1414
+ }
1415
+ const text = blockText(content);
1416
+ if (!text.trim()) return null;
1417
+ const injected = entry.isMeta ? "meta" : entry.isCompactSummary ? "compact_summary" : null;
1418
+ return {
1419
+ ...base,
1420
+ event_type: "prompt",
1421
+ role: "user",
1422
+ payload: { ...common, text: safeText(text), ...injected ? { injected } : {} }
1423
+ };
1424
+ }
1425
+ if (entry.type === "assistant") {
1426
+ const content = Array.isArray(message.content) ? message.content : [];
1427
+ const text = blockText(content);
1428
+ const toolUses = content.filter((block) => block?.type === "tool_use");
1429
+ if (!text.trim() && !toolUses.length) return null;
1430
+ const thinking = content.filter((block) => block?.type === "thinking").reduce((sum, block) => sum + (block.thinking?.length ?? 0), 0);
1431
+ const u = message.usage;
1432
+ return {
1433
+ ...base,
1434
+ event_type: toolUses.length && !text.trim() ? "tool_use" : "assistant",
1435
+ role: "assistant",
1436
+ payload: {
1437
+ ...common,
1438
+ model: message.model ?? null,
1439
+ message_id: message.id ?? null,
1440
+ stop_reason: message.stop_reason ?? null,
1441
+ usage: u ? {
1442
+ input_tokens: u.input_tokens ?? 0,
1443
+ output_tokens: u.output_tokens ?? 0,
1444
+ cache_read_input_tokens: u.cache_read_input_tokens ?? 0,
1445
+ cache_creation_input_tokens: u.cache_creation_input_tokens ?? 0
1446
+ } : null,
1447
+ thinking_chars: thinking,
1448
+ text: safeText(text),
1449
+ tool_uses: toolUses.map((block) => ({ id: block.id, name: block.name, input: redactDeep(block.input ?? {}, 0, TOOL_LIMIT) }))
1450
+ }
1451
+ };
1452
+ }
1453
+ return null;
1454
+ }
1455
+
1456
+ // src/adapters/codex.ts
1457
+ import crypto2 from "node:crypto";
1458
+ import fs4 from "node:fs";
1459
+ import os2 from "node:os";
1460
+ import path3 from "node:path";
1461
+ var CALL_TYPES = ["function_call", "custom_tool_call", "local_shell_call", "web_search_call", "tool_search_call"];
1462
+ var OUTPUT_TYPES = ["function_call_output", "custom_tool_call_output", "local_shell_call_output", "tool_search_output"];
1463
+ function findRollout(root, sessionId, depth = 0) {
1464
+ if (depth > 4) return null;
1465
+ let entries;
1466
+ try {
1467
+ entries = fs4.readdirSync(root, { withFileTypes: true });
1468
+ } catch {
1469
+ return null;
1470
+ }
1471
+ for (const entry of entries.sort((a, b) => b.name.localeCompare(a.name))) {
1472
+ const full = path3.join(root, entry.name);
1473
+ if (entry.isDirectory()) {
1474
+ const found = findRollout(full, sessionId, depth + 1);
1475
+ if (found) return found;
1476
+ } else if (entry.name.startsWith("rollout-") && entry.name.endsWith(`${sessionId}.jsonl`)) {
1477
+ return full;
1478
+ }
1479
+ }
1480
+ return null;
1481
+ }
1482
+ function locateTranscript(sessionId) {
1483
+ const home = process.env.CODEX_HOME || path3.join(os2.homedir(), ".codex");
1484
+ return findRollout(path3.join(home, "sessions"), sessionId);
1485
+ }
1486
+ function textOf(content, types) {
1487
+ if (typeof content === "string") return content;
1488
+ if (!Array.isArray(content)) return "";
1489
+ return content.filter((block) => typeof block?.text === "string" && (!types || types.includes(block.type ?? ""))).map((block) => block.text).join("\n");
1490
+ }
1491
+ function parseMaybeJson(value) {
1492
+ if (typeof value !== "string") return value ?? {};
1493
+ try {
1494
+ return JSON.parse(value);
1495
+ } catch {
1496
+ return value;
1497
+ }
1498
+ }
1499
+ function digest(text) {
1500
+ return crypto2.createHash("sha1").update(text).digest("hex").slice(0, 16);
1501
+ }
1502
+ function transcriptEvents2(lines, sessionId, ctx = {}) {
1503
+ const events = [];
1504
+ const seen = /* @__PURE__ */ new Set();
1505
+ const push = (event) => {
1506
+ if (seen.has(event.event_key)) return;
1507
+ seen.add(event.event_key);
1508
+ events.push(event);
1509
+ };
1510
+ const key = (suffix) => `codex:${sessionId}:${suffix}`;
1511
+ for (const entry of parseLines(lines)) {
1512
+ const payload = entry?.payload ?? {};
1513
+ const base = { schema_version: SCHEMA_VERSION, occurred_at: entry?.timestamp || (/* @__PURE__ */ new Date()).toISOString() };
1514
+ if (entry.type === "turn_context") {
1515
+ if (payload.model) ctx.model = payload.model;
1516
+ if (payload.turn_id) ctx.turn_id = payload.turn_id;
1517
+ continue;
1518
+ }
1519
+ if (entry.type === "event_msg") {
1520
+ let text = null;
1521
+ let turnId = payload.turn_id ?? ctx.turn_id ?? "";
1522
+ if (payload.type === "item_completed" && payload.item?.type === "UserMessage") {
1523
+ text = textOf(payload.item.content, ["text", "input_text"]);
1524
+ } else if (payload.type === "user_message") {
1525
+ text = typeof payload.message === "string" ? payload.message : textOf(payload.content);
1526
+ }
1527
+ if (text && text.trim()) {
1528
+ push({
1529
+ ...base,
1530
+ event_key: key(`prompt:${turnId}:${digest(text)}`),
1531
+ event_type: "prompt",
1532
+ role: "user",
1533
+ payload: { turn_id: turnId || null, text: safeText(text) }
1534
+ });
1535
+ }
1536
+ continue;
1537
+ }
1538
+ if (entry.type === "token_usage_record") {
1539
+ const usage = payload.usage;
1540
+ const id = payload.response_id;
1541
+ if (!usage || !id) continue;
1542
+ push({
1543
+ ...base,
1544
+ event_key: key(`usage:${id}`),
1545
+ event_type: "usage",
1546
+ role: "assistant",
1547
+ payload: {
1548
+ message_id: id,
1549
+ response_id: id,
1550
+ turn_id: payload.turn_id ?? null,
1551
+ model: ctx.model ?? null,
1552
+ usage: normalizeUsage({
1553
+ input: usage.input_tokens,
1554
+ output: usage.output_tokens,
1555
+ cacheRead: usage.cached_input_tokens,
1556
+ cacheWrite: usage.cache_write_input_tokens,
1557
+ reasoning: usage.reasoning_output_tokens
1558
+ }),
1559
+ usage_raw: usage
1560
+ }
1561
+ });
1562
+ continue;
1563
+ }
1564
+ if (entry.type !== "response_item") continue;
1565
+ if (payload.type === "message") {
1566
+ if (payload.role !== "assistant") continue;
1567
+ const text = textOf(payload.content, ["output_text", "text"]);
1568
+ if (!text.trim()) continue;
1569
+ push({
1570
+ ...base,
1571
+ // id·순번이 없으면 내용만으로는 다른 턴의 같은 답("Done.")이 겹친다. 턴과 시각을 더한다
1572
+ event_key: key(`msg:${payload.id ?? entry.ordinal ?? `${payload.internal_chat_message_metadata_passthrough?.turn_id ?? ctx.turn_id ?? ""}:${entry.timestamp ?? ""}:${digest(text)}`}`),
1573
+ event_type: "assistant",
1574
+ role: "assistant",
1575
+ payload: {
1576
+ message_id: payload.id ?? null,
1577
+ model: ctx.model ?? null,
1578
+ phase: payload.phase ?? null,
1579
+ turn_id: payload.internal_chat_message_metadata_passthrough?.turn_id ?? ctx.turn_id ?? null,
1580
+ text: safeText(text)
1581
+ }
1582
+ });
1583
+ continue;
1584
+ }
1585
+ if (CALL_TYPES.includes(payload.type)) {
1586
+ const callId = payload.call_id ?? payload.id ?? `ord${entry.ordinal}`;
1587
+ const input = parseMaybeJson(payload.arguments ?? payload.input ?? payload.action);
1588
+ push({
1589
+ ...base,
1590
+ event_key: key(`call:${callId}`),
1591
+ event_type: "tool_use",
1592
+ role: "assistant",
1593
+ payload: {
1594
+ model: ctx.model ?? null,
1595
+ turn_id: ctx.turn_id ?? null,
1596
+ tool_uses: [{ id: callId, name: payload.name ?? payload.type, input: redactDeep(typeof input === "string" ? { text: input } : input, 0, TOOL_LIMIT) }]
1597
+ }
1598
+ });
1599
+ continue;
1600
+ }
1601
+ if (OUTPUT_TYPES.includes(payload.type)) {
1602
+ const callId = payload.call_id ?? payload.id ?? `ord${entry.ordinal}`;
1603
+ const output = typeof payload.output === "string" ? payload.output : textOf(payload.output) || JSON.stringify(payload.output ?? "");
1604
+ push({
1605
+ ...base,
1606
+ event_key: key(`out:${callId}`),
1607
+ event_type: "tool_result",
1608
+ role: "user",
1609
+ payload: {
1610
+ turn_id: ctx.turn_id ?? null,
1611
+ results: [{ tool_use_id: callId, is_error: payload.status === "failed", content: safeText(output, TOOL_LIMIT) }]
1612
+ }
1613
+ });
1614
+ }
1615
+ }
1616
+ return events;
1617
+ }
1618
+
1619
+ // src/loopback.ts
1620
+ import http from "node:http";
1621
+ var APPROVAL_CODE = /^[A-Za-z0-9_-]{16,128}$/;
1622
+ async function startCallbackServer() {
1623
+ let code = null;
1624
+ let returnUrl = null;
1625
+ let waiters = [];
1626
+ const server = http.createServer((req, res) => {
1627
+ let url;
1628
+ try {
1629
+ url = new URL(req.url ?? "/", "http://127.0.0.1");
1630
+ } catch {
1631
+ res.writeHead(400).end();
1632
+ return;
1633
+ }
1634
+ if (req.headers.host !== `127.0.0.1:${port}` || req.method !== "GET" || url.pathname !== "/callback") {
1635
+ res.writeHead(404).end();
1636
+ return;
1637
+ }
1638
+ const received = url.searchParams.get("code");
1639
+ if (!received || !APPROVAL_CODE.test(received)) {
1640
+ res.writeHead(400, { "content-type": "text/plain; charset=utf-8" }).end("\uC798\uBABB\uB41C \uC694\uCCAD\uC785\uB2C8\uB2E4.");
1641
+ return;
1642
+ }
1643
+ code = received;
1644
+ const woken = waiters;
1645
+ waiters = [];
1646
+ for (const wake of woken) wake();
1647
+ if (returnUrl) {
1648
+ res.writeHead(302, { location: returnUrl, "cache-control": "no-store" }).end();
1649
+ } else {
1650
+ res.writeHead(200, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" }).end("\uC2B9\uC778\uC744 \uBC1B\uC558\uC2B5\uB2C8\uB2E4. \uC774 \uCC3D\uC744 \uB2EB\uACE0 \uC5D0\uC774\uC804\uD2B8\uB85C \uB3CC\uC544\uAC00\uC138\uC694.");
1651
+ }
1652
+ });
1653
+ let port = 0;
1654
+ try {
1655
+ await new Promise((resolve, reject) => {
1656
+ server.once("error", reject);
1657
+ server.listen(0, "127.0.0.1", () => {
1658
+ server.off("error", reject);
1659
+ resolve();
1660
+ });
1661
+ });
1662
+ } catch {
1663
+ return null;
1664
+ }
1665
+ server.unref();
1666
+ port = server.address().port;
1667
+ return {
1668
+ port,
1669
+ approvalCode: () => code,
1670
+ nextCode: () => new Promise((resolve) => waiters.push(resolve)),
1671
+ setReturnUrl(url) {
1672
+ returnUrl = url;
1673
+ },
1674
+ close() {
1675
+ const woken = waiters;
1676
+ waiters = [];
1677
+ for (const wake of woken) wake();
1678
+ server.close();
1679
+ server.closeAllConnections();
1680
+ }
1681
+ };
1682
+ }
1683
+
1684
+ // src/login.ts
1685
+ import { spawn } from "node:child_process";
1686
+ function openBrowser(url) {
1687
+ if (!/^https?:\/\//i.test(url)) return Promise.resolve(false);
1688
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
1689
+ return new Promise((resolve) => {
1690
+ try {
1691
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
1692
+ const timer = setTimeout(() => resolve(true), 5e3);
1693
+ timer.unref();
1694
+ child.on("error", () => {
1695
+ clearTimeout(timer);
1696
+ resolve(false);
1697
+ });
1698
+ child.on("exit", (code) => {
1699
+ clearTimeout(timer);
1700
+ resolve(code === 0);
1701
+ });
1702
+ child.unref();
1703
+ } catch {
1704
+ resolve(false);
1705
+ }
1706
+ });
1707
+ }
1708
+ function ticketFragment(ticket) {
1709
+ let url;
1710
+ try {
1711
+ url = new URL(ticket.trim());
1712
+ } catch {
1713
+ return null;
1714
+ }
1715
+ const params = new URLSearchParams(url.hash.replace(/^#/, ""));
1716
+ const name = params.get("name")?.trim();
1717
+ const code = params.get("code")?.trim();
1718
+ if (!name || name.length > 100 || /[\u0000-\u001f]/.test(name)) return null;
1719
+ if (!code || !/^[A-Za-z0-9]{4,12}$/.test(code)) return null;
1720
+ const out = new URLSearchParams({ name, code });
1721
+ const expires = params.get("expires");
1722
+ if (expires && /^\d{4}-\d{2}-\d{2}$/.test(expires)) out.set("expires", expires);
1723
+ return out.toString();
1724
+ }
1725
+ var AGENT_PARAMS = { claude: "claude-code", codex: "codex" };
1726
+ function connectUrl(webUrl, userCode, ticket) {
1727
+ const url = new URL("/agent/connect", webUrl);
1728
+ url.search = `code=${encodeURIComponent(userCode)}`;
1729
+ if (ticket) url.hash = ticket;
1730
+ return url.toString();
1731
+ }
1732
+ function doneUrl(webUrl, userCode) {
1733
+ const url = new URL(connectUrl(webUrl, userCode));
1734
+ url.searchParams.set("done", "1");
1735
+ return url.toString();
1736
+ }
1737
+ var AnotherFolderActiveError = class extends Error {
1738
+ constructor(meta) {
1739
+ super("AnotherFolderActive");
1740
+ this.meta = meta;
1741
+ }
1742
+ meta;
1743
+ };
1744
+ var MIN_POLL_MS = 1e3;
1745
+ var MAX_BACKOFF_MS = 6e4;
1746
+ var EXPIRED_MESSAGE = "\uD655\uC778 \uCF54\uB4DC\uAC00 \uB9CC\uB8CC\uB410\uAC70\uB098 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. login \uC744 \uB2E4\uC2DC \uBD88\uB7EC \uC0C8 \uD655\uC778 \uCF54\uB4DC\uB85C \uC2DC\uC791\uD558\uC138\uC694.";
1747
+ var DENIED_MESSAGE = "\uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C \uC774 \uB85C\uADF8\uC778\uC744 \uAC70\uC808\uD588\uC2B5\uB2C8\uB2E4. \uB4F1\uB85D\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4. \uB2E4\uC2DC \uD558\uB824\uBA74 login \uC744 \uB2E4\uC2DC \uBD80\uB974\uC138\uC694.";
1748
+ var CANCELLED_MESSAGE = "\uB354 \uC0C8\uB85C\uC6B4 \uB85C\uADF8\uC778\uC744 \uC2DC\uC791\uD574 \uC774 \uB85C\uADF8\uC778\uC740 \uCDE8\uC18C\uD588\uC2B5\uB2C8\uB2E4.";
1749
+ async function pollLogin({
1750
+ api,
1751
+ deviceCode,
1752
+ replace = false,
1753
+ intervalMs,
1754
+ deadline,
1755
+ signal,
1756
+ minPollMs = MIN_POLL_MS,
1757
+ approvalCode = () => null,
1758
+ nextCode
1759
+ }) {
1760
+ let interval = Math.max(minPollMs, intervalMs);
1761
+ let failures = 0;
1762
+ for (; ; ) {
1763
+ if (signal?.aborted) throw new Error(CANCELLED_MESSAGE);
1764
+ if (Date.now() >= deadline) throw new Error(EXPIRED_MESSAGE);
1765
+ let wait = interval;
1766
+ try {
1767
+ const result = await api.pollLoginToken(deviceCode, replace, approvalCode());
1768
+ if (signal?.aborted) throw new Error(CANCELLED_MESSAGE);
1769
+ if (result.status === "registered") return result.workspace;
1770
+ failures = 0;
1771
+ if (result.interval !== null) interval = Math.max(minPollMs, result.interval * 1e3);
1772
+ wait = interval;
1773
+ } catch (error) {
1774
+ if (!(error instanceof ApiError)) {
1775
+ if (signal?.aborted || error instanceof Error && error.message === CANCELLED_MESSAGE) throw new Error(CANCELLED_MESSAGE);
1776
+ failures += 1;
1777
+ wait = Math.min(MAX_BACKOFF_MS, interval * 2 ** failures);
1778
+ } else if (error.status === 409 && error.title === "AnotherFolderActive") {
1779
+ throw new AnotherFolderActiveError(error.meta);
1780
+ } else if (error.status === 403 && error.title === "LoginDenied") {
1781
+ throw new Error(DENIED_MESSAGE);
1782
+ } else if (error.status === 404) {
1783
+ throw new Error(EXPIRED_MESSAGE);
1784
+ } else if (error.status === 429 || error.status >= 500 || error.status === 408) {
1785
+ failures += 1;
1786
+ wait = Math.min(MAX_BACKOFF_MS, interval * 2 ** failures);
1787
+ } else {
1788
+ throw error;
1789
+ }
1790
+ }
1791
+ await sleep2(Math.min(wait, Math.max(0, deadline - Date.now())), signal, nextCode?.());
1792
+ }
1793
+ }
1794
+ function sleep2(ms, signal, wake) {
1795
+ return new Promise((resolve) => {
1796
+ if (signal?.aborted) return resolve();
1797
+ const timer = setTimeout(done, ms);
1798
+ timer.unref?.();
1799
+ let finished = false;
1800
+ function done() {
1801
+ if (finished) return;
1802
+ finished = true;
1803
+ clearTimeout(timer);
1804
+ signal?.removeEventListener("abort", done);
1805
+ resolve();
1806
+ }
1807
+ signal?.addEventListener("abort", done, { once: true });
1808
+ void wake?.then(done);
1809
+ });
1810
+ }
1811
+
1812
+ // src/marker.ts
1813
+ import crypto3 from "node:crypto";
1814
+ import fs5 from "node:fs";
1815
+ import os3 from "node:os";
1816
+ import path4 from "node:path";
1817
+ var MARKER_NAME = ".jitda";
1818
+ function parseMarker(text) {
1819
+ const out = {};
1820
+ for (const raw of text.split(/\r?\n/)) {
1821
+ const line = raw.trim();
1822
+ if (!line || line.startsWith("#")) continue;
1823
+ const match = /^([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^#\s]+))\s*(?:#.*)?$/.exec(line);
1824
+ if (match) out[match[1]] = match[2] ?? match[3] ?? match[4];
1825
+ }
1826
+ return out;
1827
+ }
1828
+ function formatMarker(hackathon) {
1829
+ return [
1830
+ "# \uC9D3\uB2E4 \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354 \uD45C\uC2DC \uD30C\uC77C\uC785\uB2C8\uB2E4.",
1831
+ "# \uC774 \uD3F4\uB354\uC5D0\uC11C \uC5F0 Claude Code\xB7Codex \uC138\uC158\uC758 \uB300\uD654\uAC00 \uC2EC\uC0AC\uC6A9\uC73C\uB85C \uC9D3\uB2E4\uC5D0 \uAE30\uB85D\uB429\uB2C8\uB2E4.",
1832
+ "# \uBE44\uBC00\uAC12\uC774 \uC5C6\uC5B4 \uCEE4\uBC0B\uD574\uB3C4 \uB429\uB2C8\uB2E4. \uC9C0\uC6B0\uBA74 \uAE30\uB85D\uC774 \uBA48\uCDA5\uB2C8\uB2E4.",
1833
+ `hackathon = "${hackathon.replace(/"/g, "")}"`,
1834
+ ""
1835
+ ].join("\n");
1836
+ }
1837
+ function homeDir() {
1838
+ return path4.resolve(process.env.JITDA_MARKER_HOME || os3.homedir());
1839
+ }
1840
+ function findMarker(cwd) {
1841
+ const home = homeDir();
1842
+ let dir = path4.resolve(cwd);
1843
+ for (; ; ) {
1844
+ if (dir === home || !isInside(dir, home)) return null;
1845
+ const file = path4.join(dir, MARKER_NAME);
1846
+ try {
1847
+ if (fs5.statSync(file).isFile()) {
1848
+ const hackathon = parseMarker(fs5.readFileSync(file, "utf8")).hackathon;
1849
+ return hackathon ? { root: dir, hackathon } : null;
1850
+ }
1851
+ } catch {
1852
+ }
1853
+ const parent = path4.dirname(dir);
1854
+ if (parent === dir) return null;
1855
+ dir = parent;
1856
+ }
1857
+ }
1858
+ function canHoldMarker(dir) {
1859
+ const home = homeDir();
1860
+ const resolved = path4.resolve(dir);
1861
+ return resolved !== home && isInside(resolved, home);
1862
+ }
1863
+ function folderLabel(root, cwd) {
1864
+ if (!cwd) return null;
1865
+ const base = path4.basename(path4.resolve(root));
1866
+ const resolved = path4.resolve(cwd);
1867
+ if (resolved === path4.resolve(root)) return base;
1868
+ if (isInside(resolved, path4.resolve(root))) return [base, ...path4.relative(root, resolved).split(path4.sep)].join("/");
1869
+ return path4.basename(resolved);
1870
+ }
1871
+ function consentLabel(root) {
1872
+ const rel = path4.relative(homeDir(), path4.resolve(root)).split(path4.sep).join("/");
1873
+ return `~/${rel}`.normalize("NFC");
1874
+ }
1875
+ var SEP = String.raw`(?:\\{1,2}|/)`;
1876
+ var NAME_CHAR = String.raw`[\p{L}\p{N}_~-]`;
1877
+ function escapeRegExp(text) {
1878
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1879
+ }
1880
+ function pathPattern(absolute) {
1881
+ const parts = absolute.split(/[\\/]+/).filter(Boolean);
1882
+ const drive = /^([A-Za-z]):$/.exec(parts[0] ?? "");
1883
+ if (drive) {
1884
+ if (parts.length < 2) return null;
1885
+ const letter = `[${drive[1].toUpperCase()}${drive[1].toLowerCase()}]`;
1886
+ return `(?:${letter}:|/(?:mnt/)?${letter})${SEP}${parts.slice(1).map(escapeRegExp).join(SEP)}`;
1887
+ }
1888
+ if (!parts.length) return null;
1889
+ return `${SEP}${parts.map(escapeRegExp).join(SEP)}`;
1890
+ }
1891
+ function pathScrubber(root, options = {}) {
1892
+ const impl = options.path ?? path4;
1893
+ const ignoreCase = options.ignoreCase ?? (impl === path4.win32 || process.platform === "win32" || process.platform === "darwin");
1894
+ const forms = (p) => [.../* @__PURE__ */ new Set([p, p.normalize("NFC"), p.normalize("NFD")])];
1895
+ const alternatives = (paths) => [...new Set(paths.flatMap(forms))].sort((a, b) => b.length - a.length).map(pathPattern).filter((pattern) => pattern !== null);
1896
+ const resolvedRoot = impl.resolve(root);
1897
+ const rootName = impl.basename(resolvedRoot);
1898
+ const rootPatterns = alternatives([resolvedRoot]);
1899
+ const homes = (options.homes ?? [os3.homedir(), homeDir()]).map((home) => impl.resolve(home));
1900
+ const homePatterns = alternatives(homes);
1901
+ const end = `(?!${NAME_CHAR}|\\.${NAME_CHAR})`;
1902
+ const none = "(?!)";
1903
+ const finder = new RegExp(
1904
+ `(?:(${rootPatterns.join("|") || none})|(${homePatterns.join("|") || none}))${end}`,
1905
+ `gu${ignoreCase ? "i" : ""}`
1906
+ );
1907
+ return (text) => {
1908
+ if (!text) return text;
1909
+ return text.replace(finder, (_match, inRoot) => inRoot !== void 0 ? rootName : "~");
1910
+ };
1911
+ }
1912
+ function isInside(dir, parent) {
1913
+ const rel = path4.relative(parent, dir);
1914
+ return rel !== "" && !rel.startsWith("..") && !path4.isAbsolute(rel);
1915
+ }
1916
+ function fingerprint(dir) {
1917
+ let real = path4.resolve(dir);
1918
+ try {
1919
+ real = fs5.realpathSync(real);
1920
+ } catch {
1921
+ }
1922
+ return crypto3.createHash("sha256").update(`${os3.hostname()}
1923
+ ${real}`).digest("hex");
1924
+ }
1925
+ function writeMarker(dir, hackathon) {
1926
+ const file = path4.join(dir, MARKER_NAME);
1927
+ fs5.writeFileSync(file, formatMarker(hackathon), { flag: "wx" });
1928
+ return file;
1929
+ }
1930
+
1931
+ // src/notice.ts
1932
+ import path5 from "node:path";
1933
+ function movedAwayMessage(root) {
1934
+ return `\uC9D3\uB2E4 \uAE30\uB85D\uC774 \uBA48\uCDB0 \uC788\uC2B5\uB2C8\uB2E4: \uC774 \uD3F4\uB354(${root})\uB294 \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354\uB97C \uB2E4\uB978 \uD3F4\uB354\uB85C \uC62E\uACA8 \uB354\uB294 \uAE30\uB85D\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. \uC0AC\uC6A9\uC790\uC5D0\uAC8C \uC54C\uB9AC\uC138\uC694. \uC774 \uD3F4\uB354\uB97C \uB2E4\uC2DC \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354\uB85C \uC4F0\uB824\uBA74 jitda \uC758 login \uB3C4\uAD6C\uB85C \uB2E4\uC2DC \uB85C\uADF8\uC778\uD574 \uC62E\uAE30\uBA74 \uB429\uB2C8\uB2E4.`;
549
1935
  }
550
- function configFile() {
551
- return path.join(stateHome(), "config.json");
1936
+ function loginRequiredMessage(root) {
1937
+ return `\uC9D3\uB2E4 \uAE30\uB85D\uC774 \uBA48\uCDB0 \uC788\uC2B5\uB2C8\uB2E4: \uC774 \uD3F4\uB354(${root})\uB294 \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354\uC9C0\uB9CC \uB85C\uADF8\uC778\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. \uC0AC\uC6A9\uC790\uC5D0\uAC8C \uC54C\uB9AC\uACE0 jitda \uC758 login \uB3C4\uAD6C\uB85C \uB85C\uADF8\uC778\uD558\uC138\uC694.`;
552
1938
  }
553
- function readServerConfig() {
554
- return readJson(configFile()) ?? {};
1939
+ function lateLoginNotice(cwd) {
1940
+ let dir = path5.resolve(cwd);
1941
+ for (let i = 0; i < 12; i++) {
1942
+ const outcome = takeLoginOutcome(fingerprint(dir));
1943
+ if (outcome) {
1944
+ return outcome.ok ? `\uC9D3\uB2E4 \uBE0C\uB77C\uC6B0\uC800 \uB85C\uADF8\uC778\uC774 \uB05D\uB0AC\uC2B5\uB2C8\uB2E4. ${outcome.message.replace(/\n/g, " ")} \uC0AC\uC6A9\uC790\uC5D0\uAC8C \uC54C\uB824 \uC8FC\uC138\uC694.` : `\uC9D3\uB2E4 \uBE0C\uB77C\uC6B0\uC800 \uB85C\uADF8\uC778\uC744 \uB9C8\uCE58\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${outcome.message} \uC0AC\uC6A9\uC790\uC5D0\uAC8C \uC774\uC720\uC640 \uD560 \uC77C\uC744 \uC54C\uB824 \uC8FC\uC138\uC694.`;
1945
+ }
1946
+ const parent = path5.dirname(dir);
1947
+ if (parent === dir) break;
1948
+ dir = parent;
1949
+ }
1950
+ return void 0;
555
1951
  }
556
- function writeServerConfig(config) {
557
- if (!config.api_url && !config.web_url) {
558
- fs.rmSync(configFile(), { force: true });
559
- return;
1952
+
1953
+ // src/transcript-files.ts
1954
+ import fs6 from "node:fs";
1955
+ import os4 from "node:os";
1956
+ import path6 from "node:path";
1957
+ var IDENTITY_MAX_BYTES = 32 * 1024 * 1024;
1958
+ var READ_CHUNK = 256 * 1024;
1959
+ function transcriptRoot(agent) {
1960
+ if (agent === "codex") return path6.join(process.env.CODEX_HOME || path6.join(os4.homedir(), ".codex"), "sessions");
1961
+ return path6.join(process.env.CLAUDE_CONFIG_DIR || path6.join(os4.homedir(), ".claude"), "projects");
1962
+ }
1963
+ function readIdentity(agent, file, maxBytes = IDENTITY_MAX_BYTES) {
1964
+ let fd;
1965
+ try {
1966
+ fd = fs6.openSync(file, "r");
1967
+ } catch {
1968
+ return null;
1969
+ }
1970
+ try {
1971
+ const buffer = Buffer.alloc(READ_CHUNK);
1972
+ const pending = [];
1973
+ let position = 0;
1974
+ while (position < maxBytes) {
1975
+ const read = fs6.readSync(fd, buffer, 0, Math.min(READ_CHUNK, maxBytes - position), position);
1976
+ if (read === 0) break;
1977
+ position += read;
1978
+ let chunk = buffer.subarray(0, read);
1979
+ for (let newline = chunk.indexOf(10); newline !== -1; newline = chunk.indexOf(10)) {
1980
+ pending.push(chunk.subarray(0, newline));
1981
+ const found = identityOf(agent, Buffer.concat(pending).toString("utf8"));
1982
+ pending.length = 0;
1983
+ if (found) return found;
1984
+ chunk = chunk.subarray(newline + 1);
1985
+ }
1986
+ if (chunk.length) pending.push(Buffer.from(chunk));
1987
+ }
1988
+ return null;
1989
+ } catch {
1990
+ return null;
1991
+ } finally {
1992
+ fs6.closeSync(fd);
560
1993
  }
561
- writeAtomic(configFile(), `${JSON.stringify(config, null, 2)}
562
- `, 384);
563
1994
  }
564
- function writeAtomic(file, text, mode) {
565
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
566
- const tmp = `${file}.${process.pid}.tmp`;
567
- fs.writeFileSync(tmp, text, mode ? { mode } : void 0);
568
- if (mode) fs.chmodSync(tmp, mode);
569
- fs.renameSync(tmp, file);
1995
+ function identityOf(agent, line) {
1996
+ if (!line.trim()) return null;
1997
+ let entry;
1998
+ try {
1999
+ entry = JSON.parse(line);
2000
+ } catch {
2001
+ return null;
2002
+ }
2003
+ if (agent === "codex") {
2004
+ if (entry?.type === "session_meta" && entry.payload?.id && entry.payload?.cwd) return { sessionId: String(entry.payload.id), cwd: String(entry.payload.cwd) };
2005
+ } else if (typeof entry?.cwd === "string" && typeof entry?.sessionId === "string") {
2006
+ return { sessionId: entry.sessionId, cwd: entry.cwd };
2007
+ }
2008
+ return null;
570
2009
  }
571
- function readJson(file) {
2010
+ function isTranscript(agent, root, file) {
2011
+ if (!file.endsWith(".jsonl")) return false;
2012
+ const rel = path6.relative(root, file);
2013
+ if (rel.startsWith("..") || path6.isAbsolute(rel)) return false;
2014
+ if (agent === "codex") return path6.basename(file).startsWith("rollout-");
2015
+ const parts = rel.split(path6.sep);
2016
+ return parts.length === 2 || isSubagentFile(parts);
2017
+ }
2018
+ function isSubagentFile(parts) {
2019
+ return parts.length === 4 && parts[2] === "subagents" && parts[3].startsWith("agent-");
2020
+ }
2021
+ function subagentKey(root, file) {
2022
+ const parts = path6.relative(root, file).split(path6.sep);
2023
+ return isSubagentFile(parts) ? `${parts[1]}/subagents/${parts[3].slice(0, -".jsonl".length)}` : null;
2024
+ }
2025
+ function trustedTranscript(agent, sessionId, file) {
2026
+ if (!file) return null;
2027
+ let real;
2028
+ let root;
572
2029
  try {
573
- return JSON.parse(fs.readFileSync(file, "utf8"));
2030
+ real = fs6.realpathSync(file);
2031
+ root = fs6.realpathSync(transcriptRoot(agent));
574
2032
  } catch {
575
2033
  return null;
576
2034
  }
2035
+ if (!isTranscript(agent, root, real) || subagentKey(root, real)) return null;
2036
+ return readIdentity(agent, real)?.sessionId === sessionId ? real : null;
2037
+ }
2038
+ function subagentFiles(mainTranscript, sessionId) {
2039
+ const dir = path6.join(path6.dirname(mainTranscript), sessionId, "subagents");
2040
+ let names;
2041
+ let realDir;
2042
+ try {
2043
+ names = fs6.readdirSync(dir).filter((name) => name.startsWith("agent-") && name.endsWith(".jsonl")).sort();
2044
+ realDir = fs6.realpathSync(dir);
2045
+ } catch {
2046
+ return [];
2047
+ }
2048
+ const out = [];
2049
+ for (const name of names) {
2050
+ const file = path6.join(dir, name);
2051
+ try {
2052
+ if (path6.dirname(fs6.realpathSync(file)) !== realDir) continue;
2053
+ } catch {
2054
+ continue;
2055
+ }
2056
+ if (readIdentity("claude", file)?.sessionId !== sessionId) continue;
2057
+ out.push([`${sessionId}/subagents/${name.slice(0, -".jsonl".length)}`, file]);
2058
+ }
2059
+ return out;
2060
+ }
2061
+
2062
+ // src/recorder.ts
2063
+ var BUSY = /* @__PURE__ */ Symbol("busy");
2064
+ var DEFAULT_API_URL = "https://hackathon.jitda.io";
2065
+ var DEFAULT_WEB_URL = "https://jitda.io";
2066
+ var RESUME_RETRY_MS = 35e3;
2067
+ var RESUME_RETRIES = 3;
2068
+ var HOLD_MOVE_MS = 10 * 6e4;
2069
+ var SUPERSEDED_MESSAGE = "\uC774 \uB85C\uADF8\uC778\uC740 \uC2DC\uC791\uD558\uB294 \uC0AC\uC774 \uAC19\uC740 \uD3F4\uB354\uC5D0\uC11C \uC0C8\uB85C \uC2DC\uC791\uB41C \uB85C\uADF8\uC778\uC73C\uB85C \uBC14\uB00C\uC5B4 \uCDE8\uC18C\uD588\uC2B5\uB2C8\uB2E4. \uC0C8 \uB85C\uADF8\uC778\uC758 \uD655\uC778 \uCF54\uB4DC\uB97C \uBCF4\uB824\uBA74 login \uC744 \uB2E4\uC2DC \uBD80\uB974\uC138\uC694.";
2070
+ var ABANDONED_MESSAGE = "\uB85C\uADF8\uC778\uC744 \uC2DC\uC791\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: \uC9D3\uB2E4 \uD50C\uB7EC\uADF8\uC778\uC774 \uC885\uB8CC\uB418\uB294 \uC911\uC785\uB2C8\uB2E4. \uC5D0\uC774\uC804\uD2B8\uB97C \uB2E4\uC2DC \uC5F0 \uB4A4 \uB2E4\uC2DC \uB85C\uADF8\uC778\uD558\uC138\uC694.";
2071
+ var FINAL_FLUSH_MS = 3e3;
2072
+ var DEFAULT_LOGIN_TTL_MS = 10 * 6e4;
2073
+ var LOGIN_GRACE_MS = 3e4;
2074
+ var MAX_LOGIN_TTL_MS = 20 * 6e4;
2075
+ var DEFAULT_POLL_SECONDS = 3;
2076
+ var CODEX_LOGIN_WAIT_MS = 45e3;
2077
+ var CLAUDE_LOGIN_WAIT_MS = 11e4;
2078
+ var Recorder = class {
2079
+ api;
2080
+ webUrl;
2081
+ fetchImpl;
2082
+ /** 로그인 정보에 저장된 서버 주소별 API. 기본 주소와 다르게 로그인한 폴더용 */
2083
+ apis = /* @__PURE__ */ new Map();
2084
+ openUrl;
2085
+ retryBaseMs;
2086
+ loginWaitMs;
2087
+ codeWaitMs;
2088
+ minPollMs;
2089
+ startCallback;
2090
+ readBudget;
2091
+ folders = /* @__PURE__ */ new Map();
2092
+ sessionLocks = /* @__PURE__ */ new Map();
2093
+ logins = /* @__PURE__ */ new Map();
2094
+ /**
2095
+ * 다른 폴더가 이미 등록돼 있어 "옮길까요?" 답을 기다리는 승인된 로그인 요청(폴더 지문별).
2096
+ * device_code 는 메모리에만 잠시 둔다. 답하면 같은 요청으로 replace: true 를 넣어 다시 묻는다
2097
+ */
2098
+ pendingMoves = /* @__PURE__ */ new Map();
2099
+ /**
2100
+ * 폴더별로 마지막에 시작한 로그인 요청 등록의 번호. 등록 응답을 기다리는 사이 같은 폴더에서 새 로그인이 시작되면
2101
+ * 늦게 온 이전 응답은 쓰지 않고 취소한다(목록에 아직 없어 위의 밀어내기가 보지 못한다)
2102
+ */
2103
+ loginGenerations = /* @__PURE__ */ new Map();
2104
+ /** "옮긴다"고 답해 replace 로 등록을 묻는 중인 요청(폴더 지문별). 끝나기 전에 프로세스를 끝내면 취소한다 */
2105
+ movingLogins = /* @__PURE__ */ new Map();
2106
+ /** 프로세스를 끝내는 중(abandonLogins 뒤). 그 뒤에 만들어진 로그인 요청은 쓰지 않고 바로 취소한다 */
2107
+ abandoned = false;
2108
+ /** 그만 보내기(제거 직전). 보내는 중인 묶음은 끝까지 가고, 다음 묶음부터 보내지 않는다 */
2109
+ stopped = false;
2110
+ stopSending() {
2111
+ this.stopped = true;
2112
+ }
2113
+ constructor(options = {}) {
2114
+ this.fetchImpl = options.fetchImpl;
2115
+ const config = readServerConfig();
2116
+ this.api = new JitdaApi(options.apiUrl ?? process.env.JITDA_API_URL ?? config.api_url ?? DEFAULT_API_URL, options.fetchImpl);
2117
+ this.webUrl = options.webUrl ?? process.env.JITDA_WEB_URL ?? config.web_url ?? DEFAULT_WEB_URL;
2118
+ this.openUrl = options.openUrl ?? openBrowser;
2119
+ this.retryBaseMs = options.retryBaseMs ?? 2e3;
2120
+ this.loginWaitMs = options.loginWaitMs;
2121
+ this.codeWaitMs = options.codeWaitMs ?? 0;
2122
+ this.minPollMs = options.minPollMs ?? MIN_POLL_MS;
2123
+ this.startCallback = options.startCallback ?? startCallbackServer;
2124
+ this.readBudget = options.readBudget;
2125
+ }
2126
+ // ── record ──────────────────────────────────────────
2127
+ /** 훅이 부른다. 받은 이벤트를 쌓기만 하고 바로 돌아온다. 전송은 뒤에서 한다. */
2128
+ async record(agent, input) {
2129
+ if (!input.session_id || !input.cwd) return { status: "ignored", message: "session_id \uB610\uB294 cwd \uAC00 \uC5C6\uC2B5\uB2C8\uB2E4" };
2130
+ const late = input.hook_event_name === "UserPromptSubmit" && agent === "claude" ? lateLoginNotice(input.cwd) : void 0;
2131
+ const marker = findMarker(input.cwd);
2132
+ if (!marker) return late ? { status: "ignored", notice: late } : { status: "ignored" };
2133
+ const fp = fingerprint(marker.root);
2134
+ const outcome = await this.withSession(fp, agent, input.session_id, () => {
2135
+ const state = loadSession(fp, agent, input.session_id);
2136
+ state.cwd = input.cwd ?? state.cwd;
2137
+ state.started_at ??= (/* @__PURE__ */ new Date()).toISOString();
2138
+ state.transcript_path ??= this.transcriptFor(agent, input.session_id, input.transcript_path, fp);
2139
+ state.hackathon ??= marker.hackathon;
2140
+ if (state.hackathon !== marker.hackathon) {
2141
+ saveSession(fp, state);
2142
+ return "other_hackathon";
2143
+ }
2144
+ const credential = credentialFor(fp);
2145
+ if (!credential || credential.hackathon_id !== marker.hackathon) {
2146
+ saveSession(fp, state);
2147
+ return null;
2148
+ }
2149
+ return this.ingest(fp, state, input, credential);
2150
+ });
2151
+ if (outcome === "other_hackathon") {
2152
+ return late ? { status: "ignored", notice: late } : { status: "ignored" };
2153
+ }
2154
+ if (!outcome) {
2155
+ const message = movedAway(fp) ? movedAwayMessage(marker.root) : loginRequiredMessage(marker.root);
2156
+ return { status: "login_required", message, notice: late ?? message };
2157
+ }
2158
+ if (!outcome.done) this.scheduleDrain(fp, agent, input.session_id);
2159
+ if (input.hook_event_name === "SessionEnd" || input.hook_event_name === "Stop") {
2160
+ await Promise.race([this.flushFinal(fp), sleep3(FINAL_FLUSH_MS)]);
2161
+ } else {
2162
+ this.scheduleFlush(fp, 1e3);
2163
+ }
2164
+ return late ? { status: "queued", queued: outcome.queued, notice: late } : { status: "queued", queued: outcome.queued };
2165
+ }
2166
+ /**
2167
+ * 훅이 말한 세션의 대화 기록 파일. 그 에이전트의 기록 폴더 안, 같은 세션의 파일이고, 파일에 적힌 작업 폴더가
2168
+ * 이 대회 작업 폴더(fp)일 때만 돌려준다. record 는 모델도 부를 수 있어 세션 ID·경로를 지어낼 수 있으므로,
2169
+ * 대회와 상관없는 다른 프로젝트의 대화를 이 폴더 기록으로 올리지 못하게 한다.
2170
+ */
2171
+ transcriptFor(agent, sessionId, given, fp) {
2172
+ const candidate = trustedTranscript(agent, sessionId, given) ?? (agent === "codex" ? trustedTranscript(agent, sessionId, locateTranscript(sessionId)) : null);
2173
+ if (!candidate) return null;
2174
+ const identity = readIdentity(agent, candidate);
2175
+ const marker = identity ? findMarker(identity.cwd) : null;
2176
+ return marker && fingerprint(marker.root) === fp ? candidate : null;
2177
+ }
2178
+ /**
2179
+ * 파일 감시가 부른다. 훅 없이 대화 기록 파일의 새 부분을 읽어 쌓고 보낸다(Codex 훅을 신뢰하지 않았거나,
2180
+ * 에이전트가 바로 꺼져 훅이 못 보낸 경우의 안전망). 읽은 위치는 훅과 같은 세션 상태를 쓰므로 겹쳐 보내지 않는다.
2181
+ * 쌓은 이벤트 수와 파일 끝까지 읽었는지를 돌려준다. 대회 작업 폴더가 아니면 0건·끝,
2182
+ * 다른 프로세스가 읽는 중이면 BUSY. 끝까지 못 읽었거나 BUSY 면 감시가 기억했다가 다시 읽는다.
2183
+ */
2184
+ async sweep(agent, sessionId, cwd, transcriptPath, externalId) {
2185
+ const marker = findMarker(cwd);
2186
+ if (!marker) return { queued: 0, finished: true };
2187
+ const fp = fingerprint(marker.root);
2188
+ const outcome = await this.withSessionTry(fp, agent, sessionId, () => {
2189
+ const state = loadSession(fp, agent, sessionId);
2190
+ state.cwd ??= cwd;
2191
+ state.started_at ??= (/* @__PURE__ */ new Date()).toISOString();
2192
+ state.transcript_path ??= transcriptPath;
2193
+ if (externalId && externalId !== sessionId) {
2194
+ state.external_id ??= externalId;
2195
+ state.hackathon ??= loadSession(fp, agent, externalId).hackathon ?? marker.hackathon;
2196
+ }
2197
+ state.hackathon ??= marker.hackathon;
2198
+ const credential = this.activeCredential(fp, state);
2199
+ if (!credential) {
2200
+ saveSession(fp, state);
2201
+ return null;
2202
+ }
2203
+ return this.ingest(fp, state, null, credential);
2204
+ });
2205
+ if (outcome === BUSY) return BUSY;
2206
+ if (!outcome) return { queued: 0, finished: true };
2207
+ if (!outcome.done) this.scheduleDrain(fp, agent, sessionId);
2208
+ if (outcome.queued) this.scheduleFlush(fp, 1e3);
2209
+ else this.ensureFlush(fp);
2210
+ return { queued: outcome.queued, finished: outcome.done };
2211
+ }
2212
+ /**
2213
+ * 켜질 때 부른다. 로그인된 폴더마다 지난번에 쌓아 두고 못 보낸 기록이 있으면 보낸다.
2214
+ * 그 폴더에 새 대화가 없어도(다른 폴더에서 에이전트를 열어도) 남은 기록이 PC 에 묶여 있지 않게 한다.
2215
+ * 보내기를 예약한 폴더 수를 돌려준다.
2216
+ */
2217
+ recoverPending() {
2218
+ let folders = 0;
2219
+ for (const fp of Object.keys(readCredentials())) {
2220
+ if (!pendingCount(fp)) continue;
2221
+ this.ensureFlush(fp);
2222
+ folders += 1;
2223
+ }
2224
+ return folders;
2225
+ }
2226
+ /** 이미 보내는 중이거나 (재시도 간격을 둔) 보내기가 예약돼 있으면 그대로 두고, 아니면 곧 보낸다 */
2227
+ ensureFlush(fp) {
2228
+ if (!pendingCount(fp)) return;
2229
+ const runtime = this.runtime(fp);
2230
+ if (runtime.timer || runtime.flushing) return;
2231
+ this.scheduleFlush(fp, 1e3);
2232
+ }
2233
+ /** 트랜스크립트의 새 부분(최대 READ_BUDGET)과 훅 이벤트를 쌓는다. 호출 전에 세션 잠금을 잡아야 한다. */
2234
+ ingest(fp, state, input, credential) {
2235
+ let main2 = null;
2236
+ let releaseMain = null;
2237
+ if (state.external_id && state.external_id !== state.session_id) {
2238
+ releaseMain = tryLockSession(fp, state.agent, state.external_id);
2239
+ if (!releaseMain) return { queued: 0, done: false };
2240
+ main2 = loadSession(fp, state.agent, state.external_id);
2241
+ if (main2.hackathon && main2.hackathon !== state.hackathon) {
2242
+ releaseMain();
2243
+ return { queued: 0, done: true };
2244
+ }
2245
+ }
2246
+ try {
2247
+ return this.ingestLocked(fp, state, input, credential, main2);
2248
+ } finally {
2249
+ releaseMain?.();
2250
+ }
2251
+ }
2252
+ ingestLocked(fp, state, input, credential, main2) {
2253
+ const events = [];
2254
+ let done = true;
2255
+ if (state.transcript_path) {
2256
+ const read = readNewLines(state.transcript_path, state.offset, this.readBudget);
2257
+ state.offset = read.offset;
2258
+ done = read.done;
2259
+ if (read.skipped) process.stderr.write(`[jitda] \uB108\uBB34 \uAE34 \uC904 ${read.skipped}\uAC1C\uB97C \uAC74\uB108\uB700: ${state.transcript_path}
2260
+ `);
2261
+ if (read.lines.length) {
2262
+ const id = state.external_id ?? state.session_id;
2263
+ events.push(...state.agent === "claude" ? transcriptEvents(read.lines, id) : transcriptEvents2(read.lines, id, state.codex));
2264
+ }
2265
+ }
2266
+ const hook = input && hookEvent(state.agent, input);
2267
+ if (hook) events.push(hook);
2268
+ const subs = !main2 && done && state.agent === "claude" && state.transcript_path ? this.takeSubagents(fp, state) : [];
2269
+ if (subs.length) events.splice(0, events.length, ...mergeByTime([events, ...subs.map((sub) => sub.events)]));
2270
+ if (subs.some((sub) => !sub.done)) done = false;
2271
+ if (events.length) {
2272
+ const label = (cwd) => folderLabel(credential.root, typeof cwd === "string" ? cwd : null);
2273
+ const scrub = pathScrubber(credential.root);
2274
+ const session = { external_session_id: state.external_id ?? state.session_id, started_at: state.started_at, cwd: label(state.cwd) };
2275
+ for (const event of events) {
2276
+ const payload = mapStrings(event.payload, scrub);
2277
+ if ("cwd" in payload) payload.cwd = label(event.payload.cwd);
2278
+ event.payload = payload;
2279
+ }
2280
+ const dest = destinationKey(credential);
2281
+ writeDestinationMeta(fp, dest, destinationMetaOf(credential));
2282
+ appendOutbox(
2283
+ fp,
2284
+ dest,
2285
+ events.map((event) => ({ agent: state.agent, session, event: { ...event, seq: main2 ? ++main2.seq : ++state.seq } }))
2286
+ );
2287
+ if (main2) saveSession(fp, main2);
2288
+ }
2289
+ saveSession(fp, state);
2290
+ for (const sub of subs) {
2291
+ saveSession(fp, sub.state);
2292
+ sub.release();
2293
+ }
2294
+ return { queued: events.length, done };
2295
+ }
2296
+ /**
2297
+ * 메인 세션(잠금을 잡은 상태)의 서브에이전트 대화 중 아직 안 읽은 줄을 읽는다. 다른 곳에서 읽는 중인 서브에이전트는 건너뛴다
2298
+ * (그쪽이 따로 읽는다). 돌려준 잠금은 부른 쪽이 상태를 저장한 뒤 푼다. 메인과 다른 해커톤에 묶인 것은 읽지 않는다.
2299
+ */
2300
+ takeSubagents(fp, state) {
2301
+ const out = [];
2302
+ for (const [key, file] of subagentFiles(state.transcript_path, state.session_id)) {
2303
+ const release = tryLockSession(fp, "claude", key);
2304
+ if (!release) continue;
2305
+ const sub = loadSession(fp, "claude", key);
2306
+ sub.cwd ??= state.cwd;
2307
+ sub.started_at ??= state.started_at;
2308
+ sub.transcript_path ??= file;
2309
+ sub.external_id ??= state.session_id;
2310
+ sub.hackathon ??= state.hackathon;
2311
+ if (sub.hackathon !== state.hackathon || sub.transcript_path !== file) {
2312
+ release();
2313
+ continue;
2314
+ }
2315
+ try {
2316
+ const read = readNewLines(file, sub.offset, this.readBudget);
2317
+ sub.offset = read.offset;
2318
+ out.push({ state: sub, events: read.lines.length ? transcriptEvents(read.lines, state.session_id) : [], done: read.done, release });
2319
+ } catch {
2320
+ release();
2321
+ }
2322
+ }
2323
+ return out;
2324
+ }
2325
+ /** 한 번에 다 못 읽은 큰 트랜스크립트를 뒤에서 이어 읽는다. */
2326
+ scheduleDrain(fp, agent, sessionId) {
2327
+ setTimeout(async () => {
2328
+ try {
2329
+ const outcome = await this.withSession(fp, agent, sessionId, () => {
2330
+ const state = loadSession(fp, agent, sessionId);
2331
+ const credential = this.activeCredential(fp, state);
2332
+ return credential ? this.ingest(fp, state, null, credential) : null;
2333
+ });
2334
+ if (outcome && !outcome.done) this.scheduleDrain(fp, agent, sessionId);
2335
+ this.scheduleFlush(fp, 0);
2336
+ } catch (error) {
2337
+ process.stderr.write(`[jitda] \uD2B8\uB79C\uC2A4\uD06C\uB9BD\uD2B8 \uC77D\uAE30 \uC2E4\uD328: ${error instanceof Error ? error.message : error}
2338
+ `);
2339
+ }
2340
+ }, 50).unref();
2341
+ }
2342
+ /**
2343
+ * 이 세션을 지금 보내도 되면 로그인 정보, 아니면 null.
2344
+ * 폴더가 여전히 기록 대상(.jitda 가 있고 같은 해커톤으로 로그인)이고, 세션이 처음 기록된 해커톤도 같아야 한다.
2345
+ */
2346
+ activeCredential(fp, state) {
2347
+ const marker = state.cwd ? findMarker(state.cwd) : null;
2348
+ if (!marker || fingerprint(marker.root) !== fp) return null;
2349
+ if (state.hackathon !== marker.hackathon) return null;
2350
+ const credential = credentialFor(fp);
2351
+ return credential && credential.hackathon_id === marker.hackathon ? credential : null;
2352
+ }
2353
+ /** 로그인 전에 기다리던 세션들의 트랜스크립트를 읽어 쌓는다. 로그인 직후 부른다. */
2354
+ resumeWaitingSessions(fp) {
2355
+ return this.resumeSessionsOf(fp, "wait");
2356
+ }
2357
+ /**
2358
+ * 켜질 때 부른다. 로그인된 폴더마다, 기록한 적 있는 세션 중 대화 기록 파일을 끝까지 읽지 못한 것(읽은 위치 < 파일 크기)을
2359
+ * 이어 읽는다. 이어 읽기 도중 프로세스가 꺼졌거나 잠겨 있어 못 읽은 세션도, 파일이 다시 바뀌지 않아도 빠짐없이 보낸다.
2360
+ * 이어 읽기 시작한 세션 수를 돌려준다.
2361
+ */
2362
+ async resumeSessions() {
2363
+ let resumed = 0;
2364
+ for (const fp of Object.keys(readCredentials())) resumed += await this.resumeSessionsOf(fp, "try");
2365
+ return resumed;
2366
+ }
2367
+ async resumeSessionsOf(fp, mode, attempt = 0) {
2368
+ let resumed = 0;
2369
+ let busy = false;
2370
+ for (const saved of listSessions(fp)) {
2371
+ if (!saved.transcript_path || !hasUnread(saved)) continue;
2372
+ try {
2373
+ const outcome = await this.runInSession(fp, saved.agent, saved.session_id, () => {
2374
+ const state = loadSession(fp, saved.agent, saved.session_id);
2375
+ const credential = this.activeCredential(fp, state);
2376
+ return credential ? this.ingest(fp, state, null, credential) : null;
2377
+ }, mode);
2378
+ if (outcome === BUSY) {
2379
+ busy = true;
2380
+ continue;
2381
+ }
2382
+ if (!outcome) continue;
2383
+ resumed += 1;
2384
+ if (!outcome.done) this.scheduleDrain(fp, saved.agent, saved.session_id);
2385
+ if (outcome.queued) this.scheduleFlush(fp, 1e3);
2386
+ } catch (error) {
2387
+ process.stderr.write(`[jitda] \uC138\uC158 \uC774\uC5B4 \uC77D\uAE30 \uC2E4\uD328: ${error instanceof Error ? error.message : error}
2388
+ `);
2389
+ }
2390
+ }
2391
+ if (busy && mode === "try" && attempt < RESUME_RETRIES) {
2392
+ setTimeout(() => void this.resumeSessionsOf(fp, "try", attempt + 1), RESUME_RETRY_MS).unref();
2393
+ }
2394
+ return resumed;
2395
+ }
2396
+ /** 같은 세션의 읽기·쓰기를 이 프로세스 안에서 한 줄로 세운다. */
2397
+ withSession(fp, agent, sessionId, fn) {
2398
+ return this.runInSession(fp, agent, sessionId, fn, "wait");
2399
+ }
2400
+ /** 다른 프로세스가 이 세션을 읽는 중이면 기다리지 않고 BUSY 를 돌려준다(파일 감시용). */
2401
+ withSessionTry(fp, agent, sessionId, fn) {
2402
+ return this.runInSession(fp, agent, sessionId, fn, "try");
2403
+ }
2404
+ /**
2405
+ * 같은 세션의 읽기·쓰기를 이 프로세스 안에서는 한 줄로 세우고(sessionLocks), 다른 프로세스와는 잠금 파일로 나눈다.
2406
+ * 기다리는 쪽(훅)은 최대 2초 기다린 뒤에도 못 잡으면 잠금 없이 진행한다(같은 기록을 두 번 보내도 서버가 한 번만 저장한다).
2407
+ */
2408
+ runInSession(fp, agent, sessionId, fn, mode) {
2409
+ const key = `${fp}:${agent}:${sessionId}`;
2410
+ const previous = this.sessionLocks.get(key) ?? Promise.resolve();
2411
+ const run2 = async () => {
2412
+ let release = tryLockSession(fp, agent, sessionId);
2413
+ if (!release && mode === "try") return BUSY;
2414
+ for (let waited = 0; !release && waited < 2e3; waited += 50) {
2415
+ await sleep3(50);
2416
+ release = tryLockSession(fp, agent, sessionId);
2417
+ }
2418
+ try {
2419
+ return fn();
2420
+ } finally {
2421
+ release?.();
2422
+ }
2423
+ };
2424
+ const next = previous.then(run2, run2);
2425
+ const settled = next.then(
2426
+ () => {
2427
+ },
2428
+ () => {
2429
+ }
2430
+ );
2431
+ this.sessionLocks.set(key, settled);
2432
+ void settled.then(() => {
2433
+ if (this.sessionLocks.get(key) === settled) this.sessionLocks.delete(key);
2434
+ });
2435
+ return next;
2436
+ }
2437
+ // ── 전송 ────────────────────────────────────────────
2438
+ runtime(fp) {
2439
+ let runtime = this.folders.get(fp);
2440
+ if (!runtime) {
2441
+ runtime = { failures: 0 };
2442
+ this.folders.set(fp, runtime);
2443
+ }
2444
+ return runtime;
2445
+ }
2446
+ scheduleFlush(fp, delayMs) {
2447
+ const runtime = this.runtime(fp);
2448
+ if (runtime.retryAt && Date.now() < runtime.retryAt) return;
2449
+ if (runtime.timer) clearTimeout(runtime.timer);
2450
+ runtime.timer = setTimeout(() => {
2451
+ runtime.timer = void 0;
2452
+ void this.flush(fp);
2453
+ }, delayMs);
2454
+ runtime.timer.unref();
2455
+ }
2456
+ /**
2457
+ * 턴 끝에 쓰는 전송. 이미 다른 전송이 돌고 있으면 flush() 는 그 전송(방금 쌓은 이벤트가 빠진)을 돌려주므로,
2458
+ * 끝난 뒤 남은 것이 있으면 다시 보낸다. 실패·인증 문제·다른 프로세스가 보내는 중이면 멈춘다.
2459
+ */
2460
+ async flushFinal(fp) {
2461
+ for (let i = 0; i < 3; i++) {
2462
+ const result = await this.flush(fp);
2463
+ if (!result || result.retryable || result.unauthorized || result.busy || !result.remaining) return;
2464
+ }
2465
+ }
2466
+ /** 같은 사람·해커톤·서버의 이전 등록에 남은 기록을 지금 목적지로 옮긴다. 옮긴 수를 돌려준다. */
2467
+ adoptForCredential(fp, credential) {
2468
+ writeDestinationMeta(fp, destinationKey(credential), destinationMetaOf(credential));
2469
+ const adopted = adoptPending(
2470
+ fp,
2471
+ destinationKey(credential),
2472
+ (meta) => meta.api_url === credential.api_url && meta.hackathon_id === credential.hackathon_id && !!meta.profile_id && meta.profile_id === credential.profile_id
2473
+ );
2474
+ if (adopted) process.stderr.write(`[jitda] \uC774\uC804 \uB4F1\uB85D\uC5D0 \uB0A8\uC740 \uAE30\uB85D ${adopted}\uAC74\uC744 \uC774\uC5B4\uBC1B\uC74C
2475
+ `);
2476
+ return adopted;
2477
+ }
2478
+ /** 쌓인 이벤트를 보낸다. 같은 폴더에 대해 동시에 한 번만 돈다. */
2479
+ flush(fp) {
2480
+ const runtime = this.runtime(fp);
2481
+ if (runtime.flushing) {
2482
+ runtime.rerun = true;
2483
+ return runtime.flushing;
2484
+ }
2485
+ runtime.flushing = (async () => {
2486
+ const credential = credentialFor(fp);
2487
+ if (!credential) return null;
2488
+ if (!stillRecording(fp, credential)) {
2489
+ process.stderr.write(`[jitda] ${credential.root} \uC758 ${MARKER_NAME} \uAC00 \uC5C6\uAC70\uB098 \uB2E4\uB978 \uD574\uCEE4\uD1A4\uC774\uB77C \uBCF4\uB0B4\uC9C0 \uC54A\uACE0 \uB0A8\uACA8 \uB460
2490
+ `);
2491
+ return null;
2492
+ }
2493
+ this.adoptForCredential(fp, credential);
2494
+ const result = await flushOutbox(fp, destinationKey(credential), this.apiFor(credential), credential.token, () => this.stopped);
2495
+ if (result.sent || result.dropped || result.error) runtime.last = { ...result, at: (/* @__PURE__ */ new Date()).toISOString() };
2496
+ if (result.unauthorized) {
2497
+ if (result.revoked && credentialFor(fp)?.token === credential.token) markMovedAway(fp);
2498
+ removeCredential(fp, credential.token);
2499
+ }
2500
+ if (result.retryable && result.remaining) {
2501
+ runtime.failures += 1;
2502
+ const delay = Math.min(6e4, this.retryBaseMs * 2 ** (runtime.failures - 1));
2503
+ runtime.retryAt = void 0;
2504
+ this.scheduleFlush(fp, delay);
2505
+ runtime.retryAt = Date.now() + delay;
2506
+ } else {
2507
+ runtime.failures = 0;
2508
+ runtime.retryAt = void 0;
2509
+ if (result.busy && result.remaining && !runtime.timer) this.scheduleFlush(fp, STALE_SENDING_MS + 1e3);
2510
+ }
2511
+ return result;
2512
+ })().finally(() => {
2513
+ runtime.flushing = void 0;
2514
+ const again = runtime.rerun;
2515
+ runtime.rerun = false;
2516
+ if (again && !runtime.timer) this.scheduleFlush(fp, 0);
2517
+ });
2518
+ return runtime.flushing;
2519
+ }
2520
+ apiFor(credential) {
2521
+ const url = (credential.api_url || this.api.baseUrl).replace(/\/+$/, "");
2522
+ if (url === this.api.baseUrl) return this.api;
2523
+ let api = this.apis.get(url);
2524
+ if (!api) {
2525
+ api = new JitdaApi(url, this.fetchImpl);
2526
+ this.apis.set(url, api);
2527
+ }
2528
+ return api;
2529
+ }
2530
+ // ── login ───────────────────────────────────────────
2531
+ /**
2532
+ * 일회용 코드로 로그인하고 이 폴더를 작업 폴더로 등록한다.
2533
+ * rails 에 로그인 요청(폴더 표시 ~/work/app, 폴더 지문, PC 이름)을 등록하고, 브라우저로 승인 화면을 연다.
2534
+ * 참가자가 웹에서 확인 코드와 폴더를 보고 승인해야만 rails 가 등록하고, 그때만 .jitda 를 만든다.
2535
+ * 대화창에서 AI 가 물었는지에 기대지 않는다. 사람 토큰은 PC 로 오지 않는다.
2536
+ *
2537
+ * 처음 부르면 확인 코드를 바로 돌려준다(사용자가 브라우저에서 승인하기 전에 에이전트 화면의 코드를 봐야
2538
+ * 같은 코드인지 견줄 수 있다). 기다리는 중에 다시 부르면 결과를 기다린다(브라우저는 reopenBrowser 일 때만 다시 연다).
2539
+ */
2540
+ async login(cwd, agent = "claude", ticket, moveFolder = false, reopenBrowser = false) {
2541
+ const fragment = ticket ? ticketFragment(ticket) : null;
2542
+ if (ticket && !fragment) {
2543
+ return "\uC785\uC7A5\uAD8C \uC8FC\uC18C\uB97C \uC77D\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. \uC9D3\uB2E4\uC5D0\uC11C \uBC1B\uC740 \uC785\uC7A5\uAD8C \uB9C1\uD06C(\u2026/ticket#name=\u2026&code=\u2026)\uB97C \uADF8\uB300\uB85C \uBD99\uC5EC \uB123\uAC70\uB098, \uC785\uC7A5\uAD8C \uC5C6\uC774 \uB85C\uADF8\uC778\uD558\uC138\uC694.";
2544
+ }
2545
+ const marker = findMarker(cwd);
2546
+ const root = marker?.root ?? path7.resolve(cwd);
2547
+ if (!marker && !canHoldMarker(root)) {
2548
+ return `\uC774 \uD3F4\uB354(${root})\uB294 \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354\uB85C \uC4F8 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uD648 \uD3F4\uB354 \uC544\uB798\uC758 \uD504\uB85C\uC81D\uD2B8 \uD3F4\uB354\uC5D0\uC11C \uB2E4\uC2DC \uC2DC\uB3C4\uD558\uC138\uC694.`;
2549
+ }
2550
+ if (!marker && fs7.existsSync(path7.join(root, MARKER_NAME))) {
2551
+ return `\uB85C\uADF8\uC778\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${unreadableMarkerMessage(root)}`;
2552
+ }
2553
+ if (this.abandoned) return ABANDONED_MESSAGE;
2554
+ const fp = fingerprint(root);
2555
+ const waitMs = this.loginWaitMs ?? (agent === "codex" ? CODEX_LOGIN_WAIT_MS : CLAUDE_LOGIN_WAIT_MS);
2556
+ let heldMove = this.pendingMoves.get(fp);
2557
+ if (heldMove && fragment && fragment !== heldMove.ticket) {
2558
+ this.dropHeldMove(fp);
2559
+ heldMove = void 0;
2560
+ }
2561
+ if (moveFolder && heldMove && Date.now() - heldMove.at < HOLD_MOVE_MS) {
2562
+ this.pendingMoves.delete(fp);
2563
+ this.markLoginReported(fp);
2564
+ let info;
2565
+ const moving = { deviceCode: heldMove.deviceCode };
2566
+ this.movingLogins.set(fp, moving);
2567
+ try {
2568
+ info = await pollLogin({
2569
+ api: this.api,
2570
+ deviceCode: heldMove.deviceCode,
2571
+ replace: true,
2572
+ approvalCode: () => heldMove.approvalCode,
2573
+ intervalMs: heldMove.intervalMs,
2574
+ deadline: Math.min(heldMove.at + HOLD_MOVE_MS, Date.now() + waitMs),
2575
+ minPollMs: this.minPollMs
2576
+ });
2577
+ } catch (error) {
2578
+ if (this.movingLogins.get(fp) === moving) this.movingLogins.delete(fp);
2579
+ if (this.abandoned) return ABANDONED_MESSAGE;
2580
+ if (error instanceof AnotherFolderActiveError) {
2581
+ const question = moveQuestion(root, error.meta);
2582
+ this.holdMove(fp, { ...heldMove, at: Date.now(), question });
2583
+ return question;
2584
+ }
2585
+ this.cancelRequest(heldMove.deviceCode);
2586
+ return `\uB85C\uADF8\uC778\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${loginErrorMessage(error)}`;
2587
+ }
2588
+ if (this.movingLogins.get(fp) === moving) this.movingLogins.delete(fp);
2589
+ try {
2590
+ return showAsIs(await this.finishLogin(root, fp, info, findMarker(cwd)?.hackathon ?? null));
2591
+ } catch (error) {
2592
+ return `\uB85C\uADF8\uC778\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${loginErrorMessage(error)}`;
2593
+ }
2594
+ }
2595
+ if (!moveFolder && heldMove && Date.now() - heldMove.at < HOLD_MOVE_MS && (!fragment || fragment === heldMove.ticket)) {
2596
+ this.markLoginReported(fp);
2597
+ return heldMove.question;
2598
+ }
2599
+ let pending = this.logins.get(fp);
2600
+ if (pending?.settled && !pending.reported && !takeLoginOutcome(fp)) pending.reported = true;
2601
+ if (pending && (pending.settled && pending.reported || fragment && fragment !== pending.ticket)) {
2602
+ if (pending.settled && !pending.reported) takeLoginOutcome(fp);
2603
+ pending.controller.abort();
2604
+ if (!pending.settled) this.cancelLogin(pending);
2605
+ this.logins.delete(fp);
2606
+ pending = void 0;
2607
+ }
2608
+ if (pending) {
2609
+ return this.awaitLogin(fp, pending, waitMs, reopenBrowser && !pending.settled ? pending.reopen() : pending.opened, false);
2610
+ }
2611
+ const folder = consentLabel(root);
2612
+ const hackathon = marker?.hackathon ?? null;
2613
+ const generation = (this.loginGenerations.get(fp) ?? 0) + 1;
2614
+ this.loginGenerations.set(fp, generation);
2615
+ const callback = await this.startCallback().catch(() => null);
2616
+ let request;
2617
+ try {
2618
+ request = await this.api.createLoginRequest({
2619
+ agent: AGENT_PARAMS[agent] ?? "claude-code",
2620
+ folderLabel: folder,
2621
+ cwdFingerprint: fp,
2622
+ machineLabel: os5.hostname().slice(0, 255),
2623
+ // .jitda 가 있으면 그 해커톤으로만 승인되게 한다(웹이 다른 해커톤으로 승인하면 rails 가 거절한다).
2624
+ // 입장권에서 오는 값이 아니다(입장권은 웹 입장에만 쓴다)
2625
+ hackathonId: hackathon,
2626
+ loopbackPort: callback?.port ?? null
2627
+ });
2628
+ } catch (error) {
2629
+ callback?.close();
2630
+ return `\uB85C\uADF8\uC778\uC744 \uC2DC\uC791\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${startErrorMessage(error)}`;
2631
+ }
2632
+ if (this.abandoned) {
2633
+ callback?.close();
2634
+ this.cancelRequest(request.device_code);
2635
+ return ABANDONED_MESSAGE;
2636
+ }
2637
+ if (this.loginGenerations.get(fp) !== generation) {
2638
+ callback?.close();
2639
+ this.cancelRequest(request.device_code);
2640
+ return SUPERSEDED_MESSAGE;
2641
+ }
2642
+ callback?.setReturnUrl(doneUrl(this.webUrl, request.user_code));
2643
+ const expiresAt = Date.parse(request.expires_at ?? "");
2644
+ const deadline = Math.min(
2645
+ (Number.isFinite(expiresAt) ? expiresAt : Date.now() + DEFAULT_LOGIN_TTL_MS) + LOGIN_GRACE_MS,
2646
+ Date.now() + MAX_LOGIN_TTL_MS
2647
+ );
2648
+ const intervalMs = (request.interval ?? DEFAULT_POLL_SECONDS) * 1e3;
2649
+ const target = connectUrl(this.webUrl, request.user_code, fragment);
2650
+ const openNow = () => {
2651
+ try {
2652
+ return Promise.resolve(this.openUrl(target)).then((value) => value !== false).catch(() => false);
2653
+ } catch {
2654
+ return Promise.resolve(false);
2655
+ }
2656
+ };
2657
+ const deviceCode = request.device_code;
2658
+ const entry = {
2659
+ userCode: request.user_code,
2660
+ // 안내용 주소에는 입장권 조각(참여 코드)을 넣지 않는다(대화에 남는다)
2661
+ url: connectUrl(this.webUrl, request.user_code),
2662
+ folder,
2663
+ markerExists: !!marker,
2664
+ ticket: fragment,
2665
+ expiresAt: Number.isFinite(expiresAt) ? expiresAt : deadline,
2666
+ opened: openNow(),
2667
+ reopen: openNow,
2668
+ controller: new AbortController(),
2669
+ deviceCode,
2670
+ callback,
2671
+ done: Promise.resolve("")
2672
+ };
2673
+ this.logins.set(fp, entry);
2674
+ entry.done = pollLogin({
2675
+ api: this.api,
2676
+ deviceCode,
2677
+ intervalMs,
2678
+ deadline,
2679
+ signal: entry.controller.signal,
2680
+ minPollMs: this.minPollMs,
2681
+ approvalCode: () => callback?.approvalCode() ?? null,
2682
+ nextCode: callback ? () => callback.nextCode() : void 0
2683
+ }).catch((error) => {
2684
+ if (!(error instanceof AnotherFolderActiveError)) this.cancelLogin(entry);
2685
+ throw error;
2686
+ }).then((info) => this.logins.get(fp) === entry ? this.finishLogin(root, fp, info, hackathon) : Promise.reject(new Error(CANCELLED_MESSAGE))).catch((error) => {
2687
+ if (error instanceof AnotherFolderActiveError) {
2688
+ if (this.logins.get(fp) !== entry) {
2689
+ this.cancelLogin(entry);
2690
+ throw new Error(CANCELLED_MESSAGE);
2691
+ }
2692
+ const question = moveQuestion(root, error.meta);
2693
+ this.holdMove(fp, { deviceCode, intervalMs, at: Date.now(), question, ticket: fragment, approvalCode: callback?.approvalCode() ?? null });
2694
+ throw new MoveRequiredError(question);
2695
+ }
2696
+ throw error instanceof MoveRequiredError ? error : new Error(loginErrorMessage(error));
2697
+ });
2698
+ const forget = () => setTimeout(() => {
2699
+ if (this.logins.get(fp) === entry) this.logins.delete(fp);
2700
+ }, HOLD_MOVE_MS).unref();
2701
+ entry.done.then(
2702
+ (text) => {
2703
+ entry.settled = true;
2704
+ callback?.close();
2705
+ if (!entry.reported) saveLoginOutcome(fp, { ok: true, message: text, at: (/* @__PURE__ */ new Date()).toISOString() });
2706
+ forget();
2707
+ },
2708
+ (error) => {
2709
+ entry.settled = true;
2710
+ callback?.close();
2711
+ entry.error = error.message;
2712
+ const kept = error instanceof MoveRequiredError ? "" : keptLoginNote(this.currentLogin(fp));
2713
+ if (!entry.reported && this.logins.get(fp) === entry) saveLoginOutcome(fp, { ok: false, message: `${entry.error}${kept}`, at: (/* @__PURE__ */ new Date()).toISOString() });
2714
+ forget();
2715
+ }
2716
+ );
2717
+ return this.awaitLogin(fp, entry, this.codeWaitMs, entry.opened, true);
2718
+ }
2719
+ /** 로그인 결과를 waitMs 까지 기다린다. 그 안에 안 끝나면 확인 코드와 함께 기다리는 중이라고 알린다 */
2720
+ /** 끝난 로그인의 결과를 이 도구 응답으로 알린 것으로 친다(다음 프롬프트 알림에 남은 결과도 지운다) */
2721
+ markLoginReported(fp) {
2722
+ const entry = this.logins.get(fp);
2723
+ if (entry?.settled) entry.reported = true;
2724
+ takeLoginOutcome(fp);
2725
+ }
2726
+ /** 이 폴더에 지금 쓰고 있는 로그인(기록 중)이 있으면 "해커톤 · 팀 · 이름 님" */
2727
+ currentLogin(fp) {
2728
+ const credential = credentialFor(fp);
2729
+ if (!credential || movedAway(fp)) return null;
2730
+ return who(credential.hackathon_name ?? null, credential.team_name ?? null, credential.profile_name ?? null);
2731
+ }
2732
+ async awaitLogin(fp, entry, waitMs, opened, first) {
2733
+ const outcome = await Promise.race([
2734
+ entry.done.then((text) => ({ text }), (error) => ({ error })),
2735
+ sleep3(waitMs).then(() => null)
2736
+ ]);
2737
+ if (outcome === null) return waitingText(entry, await opened, first, this.currentLogin(fp));
2738
+ entry.reported = true;
2739
+ takeLoginOutcome(fp);
2740
+ if ("error" in outcome) {
2741
+ if (outcome.error instanceof MoveRequiredError) return outcome.error.message;
2742
+ return `\uB85C\uADF8\uC778\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${outcome.error.message}${keptLoginNote(this.currentLogin(fp))}`;
2743
+ }
2744
+ return showAsIs(outcome.text);
2745
+ }
2746
+ async finishLogin(root, fp, info, markerHackathon) {
2747
+ if (!info.token) throw new Error("\uC11C\uBC84\uAC00 \uC791\uC5C5 \uD3F4\uB354 \uD1A0\uD070\uC744 \uC8FC\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4");
2748
+ const hackathonId = info.hackathon_id ? String(info.hackathon_id) : null;
2749
+ if (!hackathonId) throw new Error("\uC11C\uBC84\uAC00 \uB4F1\uB85D\uD55C \uD574\uCEE4\uD1A4\uC744 \uC54C\uB824 \uC8FC\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4");
2750
+ if (markerHackathon && markerHackathon !== hackathonId) {
2751
+ throw new Error(`\uC774 \uD3F4\uB354\uC758 ${MARKER_NAME} \uB294 \uB2E4\uB978 \uD574\uCEE4\uD1A4(${markerHackathon})\uC6A9\uC785\uB2C8\uB2E4. \uB85C\uADF8\uC778\uD55C \uD574\uCEE4\uD1A4\uC740 ${hackathonId} \uC785\uB2C8\uB2E4.`);
2752
+ }
2753
+ if (!markerHackathon && fs7.existsSync(path7.join(root, MARKER_NAME))) {
2754
+ throw new Error(unreadableMarkerMessage(root));
2755
+ }
2756
+ let created = null;
2757
+ if (!markerHackathon) {
2758
+ try {
2759
+ created = writeMarker(root, hackathonId);
2760
+ } catch (error) {
2761
+ if (error.code !== "EEXIST") throw error;
2762
+ if (findMarker(root)?.hackathon !== hackathonId) throw new Error(unreadableMarkerMessage(root));
2763
+ }
2764
+ }
2765
+ this.dropHeldMove(fp);
2766
+ clearMovedAway(fp);
2767
+ saveCredential(fp, {
2768
+ token: info.token,
2769
+ workspace_id: info.workspace_id,
2770
+ hackathon_id: hackathonId,
2771
+ hackathon_name: info.hackathon_name,
2772
+ profile_name: info.profile_name,
2773
+ team_name: info.team_name,
2774
+ profile_id: info.profile_id,
2775
+ root,
2776
+ api_url: this.api.baseUrl,
2777
+ saved_at: (/* @__PURE__ */ new Date()).toISOString()
2778
+ });
2779
+ await this.resumeWaitingSessions(fp);
2780
+ const flushed = await this.flush(fp);
2781
+ return [
2782
+ `\uB85C\uADF8\uC778\uD588\uC2B5\uB2C8\uB2E4: ${who(info.hackathon_name, info.team_name, info.profile_name)}`,
2783
+ `\uB300\uD68C \uC791\uC5C5 \uD3F4\uB354: ${root}${created ? ` (${MARKER_NAME} \uB97C \uB9CC\uB4E4\uC5C8\uC2B5\uB2C8\uB2E4)` : ""}`,
2784
+ "\uC774 \uD3F4\uB354\uC5D0\uC11C \uC5F0 \uC138\uC158\uC758 \uB300\uD654\uC640 \uB3C4\uAD6C \uC0AC\uC6A9\uC774 \uC2EC\uC0AC\uC6A9\uC73C\uB85C \uC9D3\uB2E4\uC5D0 \uAE30\uB85D\uB429\uB2C8\uB2E4.",
2785
+ flushed && flushed.sent ? `\uBC00\uB824 \uC788\uB358 \uAE30\uB85D ${flushed.sent}\uAC74\uC744 \uBCF4\uB0C8\uC2B5\uB2C8\uB2E4.` : ""
2786
+ ].filter(Boolean).join("\n");
2787
+ }
2788
+ /**
2789
+ * "옮길까요?" 답을 기다리는 승인된 요청을 들고 있는다. 다른 요청이 이 자리를 대신하면 이전 것은 취소하고,
2790
+ * 들고 있는 시간(HOLD_MOVE_MS)이 지나도록 답이 없으면 취소한다.
2791
+ */
2792
+ holdMove(fp, hold) {
2793
+ if (this.abandoned) {
2794
+ this.cancelRequest(hold.deviceCode);
2795
+ return;
2796
+ }
2797
+ const previous = this.pendingMoves.get(fp);
2798
+ if (previous && previous.deviceCode !== hold.deviceCode) this.cancelRequest(previous.deviceCode);
2799
+ this.pendingMoves.set(fp, hold);
2800
+ setTimeout(() => {
2801
+ if (this.pendingMoves.get(fp) !== hold) return;
2802
+ this.pendingMoves.delete(fp);
2803
+ discardLoginOutcome(fp, hold.question);
2804
+ this.cancelRequest(hold.deviceCode);
2805
+ }, HOLD_MOVE_MS).unref();
2806
+ }
2807
+ /**
2808
+ * 들고 있던 "옮길까요?" 요청을 버리고 서버에서도 취소한다. 다음 프롬프트에 띄우려고 남겨 둔 그 질문도 지운다
2809
+ * (요청이 없어져 move_folder 로 답해도 브라우저를 다시 열지 않고는 옮길 수 없다. 재시작 뒤에도 남는 파일이다)
2810
+ */
2811
+ dropHeldMove(fp) {
2812
+ const held = this.pendingMoves.get(fp);
2813
+ if (!held) return;
2814
+ this.pendingMoves.delete(fp);
2815
+ discardLoginOutcome(fp, held.question);
2816
+ this.cancelRequest(held.deviceCode);
2817
+ }
2818
+ /** 기다리던 로그인 요청을 서버에서 한 번만 취소한다 */
2819
+ cancelLogin(entry) {
2820
+ if (entry.cancelled) return;
2821
+ entry.cancelled = true;
2822
+ this.cancelRequest(entry.deviceCode);
2823
+ }
2824
+ /** 더 쓰지 않을 로그인 요청을 서버에서 취소한다. 기다리지 않고, 실패해도 무시한다 */
2825
+ cancelRequest(deviceCode) {
2826
+ void Promise.resolve().then(() => this.api.cancelLoginRequest(deviceCode)).catch(() => {
2827
+ });
2828
+ }
2829
+ /**
2830
+ * 프로세스를 끝낼 때(에이전트가 연결을 끊음) 기다리던 로그인과 들고 있던 "옮길까요?" 요청을 서버에서 취소한다.
2831
+ * device_code 는 메모리에만 있어 프로세스가 끝나면 더 쓸 수 없다. 최선만 다한다
2832
+ */
2833
+ abandonLogins() {
2834
+ this.abandoned = true;
2835
+ for (const [fp, entry] of this.logins) {
2836
+ this.logins.delete(fp);
2837
+ if (!entry.settled) {
2838
+ entry.controller.abort();
2839
+ this.cancelLogin(entry);
2840
+ }
2841
+ entry.callback?.close();
2842
+ }
2843
+ for (const fp of [...this.pendingMoves.keys()]) this.dropHeldMove(fp);
2844
+ for (const [fp, moving] of this.movingLogins) {
2845
+ this.movingLogins.delete(fp);
2846
+ this.cancelRequest(moving.deviceCode);
2847
+ }
2848
+ }
2849
+ // ── status ──────────────────────────────────────────
2850
+ status(cwd) {
2851
+ const marker = findMarker(cwd);
2852
+ if (!marker) {
2853
+ return `\uC774 \uD3F4\uB354(${path7.resolve(cwd)})\uB294 \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354\uAC00 \uC544\uB2D9\uB2C8\uB2E4(${MARKER_NAME} \uD30C\uC77C \uC5C6\uC74C). \uC774 \uD3F4\uB354\uC758 \uC138\uC158\uC740 \uAE30\uB85D\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.`;
2854
+ }
2855
+ const fp = fingerprint(marker.root);
2856
+ const credential = credentialFor(fp);
2857
+ const runtime = this.folders.get(fp);
2858
+ const login = this.logins.get(fp);
2859
+ const lines = [`\uB300\uD68C \uC791\uC5C5 \uD3F4\uB354: ${marker.root} (\uD574\uCEE4\uD1A4 ${marker.hackathon})`];
2860
+ if (credential && credential.hackathon_id === marker.hackathon) {
2861
+ lines.push(`\uB85C\uADF8\uC778: ${who(credential.hackathon_name, credential.team_name ?? null, credential.profile_name)} (\uC11C\uBC84 ${credential.api_url})`);
2862
+ } else if (login && !login.settled) {
2863
+ lines.push(
2864
+ `\uB85C\uADF8\uC778: \uBE0C\uB77C\uC6B0\uC800 \uC2B9\uC778\uC744 \uAE30\uB2E4\uB9AC\uB294 \uC911 \u2014 \uD655\uC778 \uCF54\uB4DC ${login.userCode} (\uBE0C\uB77C\uC6B0\uC800 \uD654\uBA74\uC758 \uCF54\uB4DC\uC640 \uAC19\uC744 \uB54C\uB9CC \uC2B9\uC778\uD558\uC138\uC694. \uCC3D\uC774 \uC548 \uBCF4\uC774\uBA74 reopen_browser: true \uB85C login \uC744 \uBD80\uB974\uC138\uC694)`
2865
+ );
2866
+ } else {
2867
+ lines.push(`\uB85C\uADF8\uC778: \uC548 \uB428${login?.error ? ` (${login.error})` : ""}. \uAE30\uB85D\uC774 \uBA48\uCDB0 \uC788\uC2B5\uB2C8\uB2E4. login \uB3C4\uAD6C\uB85C \uB85C\uADF8\uC778\uD558\uC138\uC694.`);
2868
+ }
2869
+ lines.push(`\uBCF4\uB0B4\uC9C0 \uBABB\uD55C \uAE30\uB85D: ${pendingCount(fp)}\uAC74`);
2870
+ if (runtime?.last) {
2871
+ const last = runtime.last;
2872
+ lines.push(`\uB9C8\uC9C0\uB9C9 \uC804\uC1A1(${last.at}): \uBCF4\uB0C4 ${last.sent}\uAC74${last.dropped ? `, \uBC84\uB9BC ${last.dropped}\uAC74` : ""}${last.error ? `, \uC624\uB958 ${last.error}` : ""}`);
2873
+ }
2874
+ return lines.join("\n");
2875
+ }
2876
+ };
2877
+ var MoveRequiredError = class extends Error {
2878
+ };
2879
+ function waitingText(entry, opened, first, current = null) {
2880
+ const minutes = Math.max(1, Math.round((entry.expiresAt - Date.now()) / 6e4));
2881
+ const where = opened ? "\uBE0C\uB77C\uC6B0\uC800 \uCC3D\uC774 \uC548 \uBCF4\uC774\uBA74 reopen_browser: true \uB85C login \uC744 \uB2E4\uC2DC \uBD80\uB974\uC138\uC694. \uAC19\uC740 \uC2B9\uC778 \uD654\uBA74\uC744 \uB2E4\uC2DC \uC5FD\uB2C8\uB2E4." : `\uBE0C\uB77C\uC6B0\uC800\uB97C \uC5F4\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. \uC0AC\uC6A9\uC790\uAC00 \uC774 \uC8FC\uC18C\uB97C \uC9C1\uC811 \uBE0C\uB77C\uC6B0\uC800\uC5D0 \uBD99\uC5EC \uB123\uAC8C \uD558\uC138\uC694(\uB2E4\uB978 \uACF3\uC5D0 \uC4F0\uAC70\uB098 \uB300\uC2E0 \uC5F4\uC9C0 \uB9C8\uC138\uC694): ${entry.url}`;
2882
+ return [
2883
+ "[\uB2E4\uB978 \uC124\uBA85\uBCF4\uB2E4 \uBA3C\uC800, \uC544\uB798 \uD655\uC778 \uCF54\uB4DC\uB97C \uC0AC\uC6A9\uC790\uC5D0\uAC8C \uADF8\uB300\uB85C \uBCF4\uC5EC \uC8FC\uACE0, \uBE0C\uB77C\uC6B0\uC800 \uD654\uBA74\uC5D0 \uAC19\uC740 \uCF54\uB4DC\uAC00 \uBCF4\uC77C \uB54C\uB9CC \uC2B9\uC778\uD558\uB77C\uACE0 \uC54C\uB9AC\uC138\uC694.]",
2884
+ `\uD655\uC778 \uCF54\uB4DC: ${entry.userCode}`,
2885
+ entry.callback ? `\uBE0C\uB77C\uC6B0\uC800\uC758 \uC9D3\uB2E4 \uD654\uBA74\uC5D0 \uC774 \uD655\uC778 \uCF54\uB4DC(${entry.userCode})\uC640 \uD3F4\uB354(${entry.folder})\uAC00 \uB611\uAC19\uC774 \uBCF4\uC77C \uB54C\uB9CC [\uC2B9\uC778]\uC744 \uB204\uB974\uC138\uC694. \uCF54\uB4DC\uAC00 \uB2E4\uB974\uAC70\uB098 \uC9C1\uC811 \uC2DC\uC791\uD55C \uB85C\uADF8\uC778\uC774 \uC544\uB2C8\uBA74 \uC2B9\uC778\uD558\uC9C0 \uB9D0\uACE0 \uCC3D\uC744 \uB2EB\uC73C\uC138\uC694. \uBE0C\uB77C\uC6B0\uC800\uAC00 \uC774 PC \uAC00 \uC544\uB2CC \uB2E4\uB978 PC \uC5D0 \uC788\uC73C\uBA74 \uD654\uBA74\uC758 "\uCF54\uB4DC \uC9C1\uC811 \uC785\uB825"\uC744 \uB20C\uB7EC \uC774 \uCF54\uB4DC\uB97C \uC785\uB825\uD558\uC138\uC694.` : `\uBE0C\uB77C\uC6B0\uC800\uC758 \uC9D3\uB2E4 \uD654\uBA74\uC5D0 \uC774 \uD655\uC778 \uCF54\uB4DC(${entry.userCode})\uB97C \uC9C1\uC811 \uC785\uB825\uD574\uC57C \uC2B9\uC778\uB429\uB2C8\uB2E4. \uD3F4\uB354(${entry.folder})\uAC00 \uB9DE\uC744 \uB54C\uB9CC \uC2B9\uC778\uD558\uC138\uC694. \uC9C1\uC811 \uC2DC\uC791\uD55C \uB85C\uADF8\uC778\uC774 \uC544\uB2C8\uBA74 \uC2B9\uC778\uD558\uC9C0 \uB9D0\uACE0 \uCC3D\uC744 \uB2EB\uC73C\uC138\uC694.`,
2886
+ "",
2887
+ ...current ? [
2888
+ `\uC774 \uD3F4\uB354\uB294 \uC774\uBBF8 ${current}${current.endsWith("\uB2D8") ? "\uC73C\uB85C" : "\uB85C"} \uB85C\uADF8\uC778\uB3FC \uAE30\uB85D\uB418\uACE0 \uC788\uC2B5\uB2C8\uB2E4. \uC0C8 \uB85C\uADF8\uC778\uC740 \uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C \uC2B9\uC778\uC744 \uAE30\uB2E4\uB9AC\uACE0 \uC788\uC2B5\uB2C8\uB2E4.`,
2889
+ "\uC2B9\uC778\uD558\uBA74 \uC0C8 \uB85C\uADF8\uC778\uC73C\uB85C \uBC14\uB01D\uB2C8\uB2E4. \uC2B9\uC778\uD558\uC9C0 \uC54A\uC73C\uBA74 \uC9C0\uAE08 \uB85C\uADF8\uC778\uC774 \uADF8\uB300\uB85C \uC720\uC9C0\uB429\uB2C8\uB2E4."
2890
+ ] : [
2891
+ "\uC544\uC9C1 \uB85C\uADF8\uC778 \uC804\uC785\uB2C8\uB2E4. \uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C \uC2B9\uC778\uC744 \uAE30\uB2E4\uB9AC\uACE0 \uC788\uC2B5\uB2C8\uB2E4.",
2892
+ entry.markerExists ? "\uC2B9\uC778\uD574\uC57C \uC774 \uD3F4\uB354\uAC00 \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354\uB85C \uB4F1\uB85D\uB429\uB2C8\uB2E4. \uC9C0\uAE08\uC740 \uB4F1\uB85D\uB418\uC9C0 \uC54A\uC558\uACE0 \uAE30\uB85D\uB3C4 \uBA48\uCDB0 \uC788\uC2B5\uB2C8\uB2E4." : `\uC2B9\uC778\uD574\uC57C \uC774 \uD3F4\uB354\uAC00 \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354\uB85C \uB4F1\uB85D\uB418\uACE0 ${MARKER_NAME} \uD30C\uC77C\uC774 \uB9CC\uB4E4\uC5B4\uC9D1\uB2C8\uB2E4. \uC9C0\uAE08\uC740 \uB4F1\uB85D\uB418\uC9C0 \uC54A\uC558\uACE0 \uAE30\uB85D\uB3C4 \uBA48\uCDB0 \uC788\uC2B5\uB2C8\uB2E4.`
2893
+ ],
2894
+ where,
2895
+ ...first ? ["[\uD655\uC778 \uCF54\uB4DC\uB97C \uC0AC\uC6A9\uC790\uC5D0\uAC8C \uBCF4\uC5EC \uC900 \uB2E4\uC74C login \uC744 \uB2E4\uC2DC \uBD80\uB974\uBA74(\uAC19\uC740 cwd\xB7ticket) \uC2B9\uC778 \uACB0\uACFC\uB97C \uAE30\uB2E4\uB824 \uC54C\uB824 \uC90D\uB2C8\uB2E4. \uBE0C\uB77C\uC6B0\uC800\uB294 \uB2E4\uC2DC \uC5F4\uB9AC\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.]"] : [],
2896
+ `\uC2B9\uC778\uD558\uBA74 \uC0AC\uC6A9\uC790\uAC00 \uB2E4\uC74C\uC5D0 \uBB34\uC5B8\uAC00 \uC785\uB825\uD560 \uB54C\uB3C4 \uACB0\uACFC\uB97C \uC54C\uB824 \uB4DC\uB9BD\uB2C8\uB2E4(\uD655\uC778 \uCF54\uB4DC\uB294 \uC55E\uC73C\uB85C \uC57D ${minutes}\uBD84 \uB3D9\uC548 \uC720\uD6A8\uD569\uB2C8\uB2E4).`
2897
+ ].join("\n");
2898
+ }
2899
+ function keptLoginNote(current) {
2900
+ return current ? ` (\uC774\uC804 \uB85C\uADF8\uC778 ${current}${current.endsWith("\uB2D8") ? "\uC740" : "\uB294"} \uADF8\uB300\uB85C \uC720\uC9C0\uB3FC \uAE30\uB85D\uB418\uACE0 \uC788\uC2B5\uB2C8\uB2E4.)` : "";
2901
+ }
2902
+ function startErrorMessage(error) {
2903
+ if (error instanceof ApiError) {
2904
+ if (error.status === 429) return "\uB85C\uADF8\uC778 \uC694\uCCAD\uC774 \uB108\uBB34 \uB9CE\uC2B5\uB2C8\uB2E4. \uC774 \uB124\uD2B8\uC6CC\uD06C\uC5D0\uC11C \uC5EC\uB7EC \uC0AC\uB78C\uC774 \uD55C\uAEBC\uBC88\uC5D0 \uB85C\uADF8\uC778\uD558\uACE0 \uC788\uC2B5\uB2C8\uB2E4. \uC7A0\uC2DC \uB4A4 \uB2E4\uC2DC \uC2DC\uB3C4\uD558\uC138\uC694.";
2905
+ return `${error.detail ?? error.message}${error.title ? ` (${error.title})` : ""}`;
2906
+ }
2907
+ return `\uC9D3\uB2E4 \uC11C\uBC84\uC5D0 \uC5F0\uACB0\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4(${error instanceof Error ? error.message : String(error)}). \uC778\uD130\uB137 \uC5F0\uACB0\uC744 \uD655\uC778\uD558\uACE0 \uB2E4\uC2DC \uC2DC\uB3C4\uD558\uC138\uC694.`;
2908
+ }
2909
+ function loginErrorMessage(error) {
2910
+ if (error instanceof ApiError && (error.title || error.detail)) return registerErrorMessage(error);
2911
+ return error instanceof Error ? error.message : String(error);
2912
+ }
2913
+ function moveQuestion(root, meta) {
2914
+ const where = typeof meta?.machine_label === "string" && meta.machine_label ? `${meta.machine_label} \uC758 ` : "";
2915
+ const since = typeof meta?.registered_at === "string" ? ` (${new Date(meta.registered_at).toLocaleString("ko-KR")} \uB4F1\uB85D)` : "";
2916
+ return [
2917
+ "[\uB2E4\uB978 \uC124\uBA85\uBCF4\uB2E4 \uBA3C\uC800, \uC544\uB798 \uC9C8\uBB38\uC744 \uC0AC\uC6A9\uC790\uC5D0\uAC8C \uADF8\uB300\uB85C \uD558\uC138\uC694.]",
2918
+ `\uC774\uBBF8 ${where}\uB2E4\uB978 \uD3F4\uB354\uB97C \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354\uB85C \uC4F0\uACE0 \uC788\uC2B5\uB2C8\uB2E4${since}. \uC774 \uD3F4\uB354(${root})\uB85C \uC62E\uAE38\uAE4C\uC694?`,
2919
+ "\uC62E\uAE30\uBA74 \uC774\uC804 \uD3F4\uB354\uB294 \uB354\uB294 \uAE30\uB85D\uB418\uC9C0 \uC54A\uACE0, \uC9C0\uAE08\uAE4C\uC9C0 \uB0A8\uAE34 \uAE30\uB85D\uC740 \uADF8\uB300\uB85C \uB0A8\uC2B5\uB2C8\uB2E4. \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354\uB294 \uD55C \uC0AC\uB78C\uB2F9 \uD558\uB098\uC785\uB2C8\uB2E4.",
2920
+ "",
2921
+ "[\uC0AC\uC6A9\uC790\uAC00 \uC62E\uAE30\uACA0\uB2E4\uACE0 \uD558\uBA74 move_folder: true \uB85C login \uC744 \uB2E4\uC2DC \uBD80\uB974\uC138\uC694(ticket \uB3C4 \uC55E\uC5D0\uC11C\uCC98\uB7FC \uB123\uC2B5\uB2C8\uB2E4). \uBE0C\uB77C\uC6B0\uC800\uB294 \uB2E4\uC2DC \uC5F4\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. \uB2F5\uD558\uAE30 \uC804\uC5D0\uB294 \uBD80\uB974\uC9C0 \uB9C8\uC138\uC694.]"
2922
+ ].join("\n");
2923
+ }
2924
+ function showAsIs(text) {
2925
+ return `[\uC544\uB798 "\uB85C\uADF8\uC778\uD588\uC2B5\uB2C8\uB2E4: \uD574\uCEE4\uD1A4 \xB7 \uD300 \xB7 \uC774\uB984" \uC904\uC740 \uBC14\uAFB8\uAC70\uB098 \uC904\uC774\uC9C0 \uB9D0\uACE0 \uADF8\uB300\uB85C \uC0AC\uC6A9\uC790\uC5D0\uAC8C \uBCF4\uC5EC \uC8FC\uC138\uC694.]
2926
+ ${text}`;
2927
+ }
2928
+ function unreadableMarkerMessage(root) {
2929
+ return `\uC774 \uD3F4\uB354(${root})\uC758 ${MARKER_NAME} \uB97C \uC77D\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4(\uD3F4\uB354\uC774\uAC70\uB098 \uD574\uCEE4\uD1A4 \uAC12\uC774 \uC5C6\uAC70\uB098 \uB2E4\uB978 \uD574\uCEE4\uD1A4\uC6A9). \uC9C0\uC6B0\uAC70\uB098 \uACE0\uCE5C \uB4A4 \uB2E4\uC2DC \uB85C\uADF8\uC778\uD558\uC138\uC694. \uC9C0\uAE08\uC740 \uAE30\uB85D\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.`;
2930
+ }
2931
+ function stillRecording(fp, credential) {
2932
+ const marker = findMarker(credential.root);
2933
+ return !!marker && fingerprint(marker.root) === fp && marker.hackathon === credential.hackathon_id;
2934
+ }
2935
+ function destinationMetaOf(credential) {
2936
+ return { api_url: credential.api_url, hackathon_id: credential.hackathon_id, profile_id: credential.profile_id ?? null };
2937
+ }
2938
+ function who(hackathon, team, name) {
2939
+ return [hackathon, team, name ? `${name} \uB2D8` : "\uCC38\uAC00\uC790"].filter(Boolean).join(" \xB7 ");
2940
+ }
2941
+ function registerErrorMessage(error) {
2942
+ switch (error.title) {
2943
+ case "RuntimeNotLocalAgent":
2944
+ return "\uC774 \uD574\uCEE4\uD1A4\uC740 Claude Code\xB7Codex \uAC19\uC740 \uC678\uBD80 \uC5D0\uC774\uC804\uD2B8\uB85C \uCC38\uC5EC\uD558\uB294 \uAC83\uC744 \uC9C0\uC6D0\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. \uB300\uD68C \uC6B4\uC601\uC9C4\uC5D0\uAC8C \uBA3C\uC800 \uBB38\uC758\uD558\uC138\uC694(\uD574\uCEE4\uD1A4 \uC124\uC815\uC774 \uC798\uBABB\uB410\uC744 \uC218 \uC788\uC2B5\uB2C8\uB2E4). \uC6B4\uC601\uC9C4\uC774 \uC9D3\uB2E4 \uC6F9\uC5D0\uC11C \uC791\uC5C5\uD558\uB77C\uACE0 \uD558\uBA74 \uADF8\uB807\uAC8C \uD558\uC138\uC694.";
2945
+ case "NotParticipant":
2946
+ return "\uB85C\uADF8\uC778\uD55C \uACC4\uC815\uC774 \uC774 \uD574\uCEE4\uD1A4\uC758 \uCC38\uAC00\uC790\uAC00 \uC544\uB2D9\uB2C8\uB2E4. \uCC38\uC5EC \uCF54\uB4DC\uB97C \uD655\uC778\uD558\uC138\uC694.";
2947
+ case "HackathonNotFound":
2948
+ return "\uD574\uCEE4\uD1A4\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uCC38\uC5EC \uCF54\uB4DC\uB97C \uD655\uC778\uD558\uC138\uC694.";
2949
+ default:
2950
+ return `\uC791\uC5C5 \uD3F4\uB354\uB97C \uB4F1\uB85D\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${error.detail ?? error.message}${error.title ? ` (${error.title})` : ""}`;
2951
+ }
2952
+ }
2953
+ function sleep3(ms) {
2954
+ return new Promise((resolve) => setTimeout(resolve, ms).unref());
2955
+ }
2956
+ function hasUnread(state) {
2957
+ try {
2958
+ return !!state.transcript_path && fs7.statSync(state.transcript_path).size !== state.offset;
2959
+ } catch {
2960
+ return false;
2961
+ }
2962
+ }
2963
+ function mapStrings(value, fn, depth = 0) {
2964
+ if (typeof value === "string") return fn(value);
2965
+ if (depth > 12 || !value || typeof value !== "object") return value;
2966
+ if (Array.isArray(value)) return value.map((item) => mapStrings(item, fn, depth + 1));
2967
+ const out = {};
2968
+ for (const [key, item] of Object.entries(value)) out[key] = mapStrings(item, fn, depth + 1);
2969
+ return out;
2970
+ }
2971
+ function mergeByTime(streams) {
2972
+ const at = (event) => Date.parse(event.occurred_at);
2973
+ const heads = streams.map(() => 0);
2974
+ const out = [];
2975
+ for (; ; ) {
2976
+ let pick = -1;
2977
+ for (let i = 0; i < streams.length; i++) {
2978
+ if (heads[i] >= streams[i].length) continue;
2979
+ if (pick < 0) {
2980
+ pick = i;
2981
+ continue;
2982
+ }
2983
+ const a = at(streams[i][heads[i]]);
2984
+ const b = at(streams[pick][heads[pick]]);
2985
+ if (Number.isFinite(a) && Number.isFinite(b) && a < b) pick = i;
2986
+ }
2987
+ if (pick < 0) return out;
2988
+ out.push(streams[pick][heads[pick]++]);
2989
+ }
577
2990
  }
578
2991
 
579
2992
  // src/install.ts
@@ -591,7 +3004,7 @@ var PLUGIN_FILES = [
591
3004
  "package.json"
592
3005
  ];
593
3006
  function parseArgs(argv) {
594
- const options = { command: "install", dev: false, only: [] };
3007
+ const options = { command: "install", dev: false, only: [], keepData: false };
595
3008
  for (let i = 0; i < argv.length; i++) {
596
3009
  const arg = argv[i];
597
3010
  if (arg === "uninstall" || arg === "remove") options.command = "uninstall";
@@ -600,17 +3013,21 @@ function parseArgs(argv) {
600
3013
  else if (arg === "--dev") options.dev = true;
601
3014
  else if (arg === "--claude") options.only.push("claude");
602
3015
  else if (arg === "--codex") options.only.push("codex");
603
- else if (arg === "--api-url") options.apiUrl = argv[++i];
604
- else if (arg === "--web-url") options.webUrl = argv[++i];
605
- else throw new Error(`\uC54C \uC218 \uC5C6\uB294 \uC635\uC158: ${arg}`);
3016
+ else if (arg === "--keep-data") options.keepData = true;
3017
+ else if (arg === "--api-url" || arg === "--web-url") {
3018
+ const value = argv[++i];
3019
+ if (!value || value.startsWith("-")) throw new Error(`${arg} \uB4A4\uC5D0 \uC8FC\uC18C\uB97C \uB123\uC73C\uC138\uC694`);
3020
+ if (arg === "--api-url") options.apiUrl = value;
3021
+ else options.webUrl = value;
3022
+ } else throw new Error(`\uC54C \uC218 \uC5C6\uB294 \uC635\uC158: ${arg}`);
606
3023
  }
607
3024
  return options;
608
3025
  }
609
3026
  function agentHome() {
610
- return process.env.JITDA_AGENT_HOME || path2.join(os2.homedir(), ".jitda", "agent");
3027
+ return process.env.JITDA_AGENT_HOME || path8.join(os6.homedir(), ".jitda", "agent");
611
3028
  }
612
3029
  function packageRoot() {
613
- return path2.resolve(path2.dirname(fileURLToPath(import.meta.url)), "..");
3030
+ return path8.resolve(path8.dirname(fileURLToPath(import.meta.url)), "..");
614
3031
  }
615
3032
  function run(cmd, args) {
616
3033
  const result = import_cross_spawn.default.sync(cmd, args, { encoding: "utf8", env: process.env });
@@ -620,56 +3037,154 @@ function run(cmd, args) {
620
3037
  function available(cmd) {
621
3038
  return run(cmd, ["--version"]).ok;
622
3039
  }
3040
+ function isRemovableJitdaDir(dir, name) {
3041
+ if (!path8.isAbsolute(dir)) return false;
3042
+ const real = (p) => {
3043
+ try {
3044
+ return fs8.realpathSync(p);
3045
+ } catch {
3046
+ return path8.resolve(p);
3047
+ }
3048
+ };
3049
+ const target = real(dir);
3050
+ if (path8.basename(target) !== name) return false;
3051
+ const same = (a, b) => a.toLowerCase() === b.toLowerCase();
3052
+ let cwd = "";
3053
+ try {
3054
+ cwd = process.cwd();
3055
+ } catch {
3056
+ }
3057
+ return ![os6.homedir(), path8.parse(target).root, cwd].filter(Boolean).some((other) => same(real(other), target));
3058
+ }
3059
+ function looksLikeOurPlugin(dir) {
3060
+ if (!fs8.existsSync(dir)) return true;
3061
+ if (fs8.readdirSync(dir).every((name) => name.startsWith("."))) return !fs8.existsSync(path8.join(dir, ".git"));
3062
+ try {
3063
+ return JSON.parse(fs8.readFileSync(path8.join(dir, "package.json"), "utf8")).name === "jitda-agent";
3064
+ } catch {
3065
+ return false;
3066
+ }
3067
+ }
623
3068
  function copyPlugin(from, to) {
3069
+ if (!isRemovableJitdaDir(to, "agent") || !looksLikeOurPlugin(to)) {
3070
+ throw new Error(`\uC124\uCE58 \uC704\uCE58(${to})\uAC00 \uC9D3\uB2E4 \uD50C\uB7EC\uADF8\uC778 \uD3F4\uB354(\u2026/agent)\uB85C \uBCF4\uC774\uC9C0 \uC54A\uC544 \uB36E\uC5B4\uC4F0\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4. JITDA_AGENT_HOME \uC124\uC815\uC744 \uD655\uC778\uD558\uC138\uC694.`);
3071
+ }
624
3072
  const staging = `${to}.new-${process.pid}`;
625
- fs2.rmSync(staging, { recursive: true, force: true });
3073
+ fs8.rmSync(staging, { recursive: true, force: true });
626
3074
  for (const item of PLUGIN_FILES) {
627
- const source = path2.join(from, item);
628
- if (!fs2.existsSync(source)) throw new Error(`\uD328\uD0A4\uC9C0\uC5D0 ${item} \uC774 \uC5C6\uC2B5\uB2C8\uB2E4. \uD328\uD0A4\uC9C0\uAC00 \uAE68\uC84C\uC744 \uC218 \uC788\uC2B5\uB2C8\uB2E4.`);
629
- const target = path2.join(staging, item);
630
- fs2.mkdirSync(path2.dirname(target), { recursive: true });
631
- fs2.cpSync(source, target, { recursive: true });
3075
+ const source = path8.join(from, item);
3076
+ if (!fs8.existsSync(source)) throw new Error(`\uD328\uD0A4\uC9C0\uC5D0 ${item} \uC774 \uC5C6\uC2B5\uB2C8\uB2E4. \uD328\uD0A4\uC9C0\uAC00 \uAE68\uC84C\uC744 \uC218 \uC788\uC2B5\uB2C8\uB2E4.`);
3077
+ const target = path8.join(staging, item);
3078
+ fs8.mkdirSync(path8.dirname(target), { recursive: true });
3079
+ fs8.cpSync(source, target, { recursive: true });
632
3080
  }
633
- fs2.rmSync(to, { recursive: true, force: true });
634
- fs2.mkdirSync(path2.dirname(to), { recursive: true });
635
- fs2.renameSync(staging, to);
3081
+ fs8.rmSync(to, { recursive: true, force: true });
3082
+ fs8.mkdirSync(path8.dirname(to), { recursive: true });
3083
+ fs8.renameSync(staging, to);
636
3084
  }
3085
+ var ALREADY_GONE = /not found|not (?:configured|installed)/i;
637
3086
  function installClaude(dir) {
638
- if (!available("claude")) return { agent: "Claude Code", ok: false, message: "claude \uBA85\uB839\uC744 \uCC3E\uC9C0 \uBABB\uD574 \uAC74\uB108\uB701\uB2C8\uB2E4." };
3087
+ if (!available("claude")) return { agent: "Claude Code", status: "skipped", message: "claude \uBA85\uB839\uC744 \uCC3E\uC9C0 \uBABB\uD574 \uAC74\uB108\uB701\uB2C8\uB2E4." };
639
3088
  const market = run("claude", ["plugin", "marketplace", "add", dir]);
640
- if (!market.ok) return { agent: "Claude Code", ok: false, message: `\uB9C8\uCF13\uD50C\uB808\uC774\uC2A4 \uB4F1\uB85D \uC2E4\uD328: ${market.output}` };
3089
+ if (!market.ok) return { agent: "Claude Code", status: "failed", message: `\uB9C8\uCF13\uD50C\uB808\uC774\uC2A4 \uB4F1\uB85D \uC2E4\uD328: ${market.output}` };
641
3090
  const refresh = run("claude", ["plugin", "marketplace", "update", MARKETPLACE]);
642
- if (!refresh.ok) return { agent: "Claude Code", ok: false, message: `\uB9C8\uCF13\uD50C\uB808\uC774\uC2A4 \uAC31\uC2E0 \uC2E4\uD328: ${refresh.output}` };
3091
+ if (!refresh.ok) return { agent: "Claude Code", status: "failed", message: `\uB9C8\uCF13\uD50C\uB808\uC774\uC2A4 \uAC31\uC2E0 \uC2E4\uD328: ${refresh.output}` };
643
3092
  const install = run("claude", ["plugin", "install", PLUGIN]);
644
- if (!install.ok) return { agent: "Claude Code", ok: false, message: `\uD50C\uB7EC\uADF8\uC778 \uC124\uCE58 \uC2E4\uD328: ${install.output}` };
3093
+ if (!install.ok) return { agent: "Claude Code", status: "failed", message: `\uD50C\uB7EC\uADF8\uC778 \uC124\uCE58 \uC2E4\uD328: ${install.output}` };
645
3094
  const update = run("claude", ["plugin", "update", PLUGIN]);
646
- if (!update.ok) return { agent: "Claude Code", ok: false, message: `\uD50C\uB7EC\uADF8\uC778 \uC5C5\uB370\uC774\uD2B8 \uC2E4\uD328: ${update.output}` };
647
- return { agent: "Claude Code", ok: true, message: "\uC124\uCE58\uD588\uC2B5\uB2C8\uB2E4. \uC774\uBBF8 \uC5F4\uB824 \uC788\uB294 Claude Code \uB294 \uB2E4\uC2DC \uC2DC\uC791\uD574\uC57C \uBC18\uC601\uB429\uB2C8\uB2E4." };
3095
+ if (!update.ok) return { agent: "Claude Code", status: "failed", message: `\uD50C\uB7EC\uADF8\uC778 \uC5C5\uB370\uC774\uD2B8 \uC2E4\uD328: ${update.output}` };
3096
+ return { agent: "Claude Code", status: "ok", message: "\uC124\uCE58\uD588\uC2B5\uB2C8\uB2E4. \uC5F4\uB824 \uC788\uB294 Claude Code \uC5D0\uB3C4 \uBC14\uB85C \uBC18\uC601\uB429\uB2C8\uB2E4(\uC9D3\uB2E4 \uB3C4\uAD6C\uAC00 \uBCF4\uC774\uC9C0 \uC54A\uC73C\uBA74 Claude Code \uB97C \uB2E4\uC2DC \uC2DC\uC791\uD558\uC138\uC694)." };
648
3097
  }
649
3098
  function installCodex(dir) {
650
- if (!available("codex")) return { agent: "Codex", ok: false, message: "codex \uBA85\uB839\uC744 \uCC3E\uC9C0 \uBABB\uD574 \uAC74\uB108\uB701\uB2C8\uB2E4." };
651
- run("codex", ["plugin", "remove", PLUGIN]);
3099
+ if (!available("codex")) return { agent: "Codex", status: "skipped", message: "codex \uBA85\uB839\uC744 \uCC3E\uC9C0 \uBABB\uD574 \uAC74\uB108\uB701\uB2C8\uB2E4." };
652
3100
  const market = run("codex", ["plugin", "marketplace", "add", dir]);
653
- if (!market.ok) return { agent: "Codex", ok: false, message: `\uB9C8\uCF13\uD50C\uB808\uC774\uC2A4 \uB4F1\uB85D \uC2E4\uD328: ${market.output}` };
654
- const add = run("codex", ["plugin", "add", PLUGIN]);
655
- if (!add.ok) return { agent: "Codex", ok: false, message: `\uD50C\uB7EC\uADF8\uC778 \uC124\uCE58 \uC2E4\uD328: ${add.output}` };
3101
+ if (!market.ok) return { agent: "Codex", status: "failed", message: `\uB9C8\uCF13\uD50C\uB808\uC774\uC2A4 \uB4F1\uB85D \uC2E4\uD328(\uAE30\uC874 \uC124\uCE58\uB294 \uADF8\uB300\uB85C \uB460): ${market.output}` };
3102
+ run("codex", ["plugin", "remove", PLUGIN]);
3103
+ let add = run("codex", ["plugin", "add", PLUGIN]);
3104
+ if (!add.ok) add = run("codex", ["plugin", "add", PLUGIN]);
3105
+ if (!add.ok) {
3106
+ return {
3107
+ agent: "Codex",
3108
+ status: "failed",
3109
+ message: `\uD50C\uB7EC\uADF8\uC778 \uC124\uCE58 \uC2E4\uD328: ${add.output}
3110
+ Codex \uC5D0\uB294 \uC9C0\uAE08 \uC9D3\uB2E4 \uD50C\uB7EC\uADF8\uC778\uC774 \uC5C6\uC5B4 \uAE30\uB85D\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. \uAC19\uC740 \uBA85\uB839\uC73C\uB85C \uB2E4\uC2DC \uC124\uCE58\uD558\uC138\uC694.`
3111
+ };
3112
+ }
656
3113
  return {
657
3114
  agent: "Codex",
658
- ok: true,
659
- message: "\uC124\uCE58\uD588\uC2B5\uB2C8\uB2E4. Codex \uB97C \uC5F0 \uB4A4 /hooks \uC5D0\uC11C jitda \uD6C5\uC744 \uAC80\uD1A0\uD558\uACE0 \uC2E0\uB8B0\uD574\uC57C \uAE30\uB85D\uB429\uB2C8\uB2E4(\uC5C5\uB370\uC774\uD2B8\uD560 \uB54C\uB9C8\uB2E4 \uB2E4\uC2DC)."
3115
+ status: "ok",
3116
+ message: "\uC124\uCE58\uD588\uC2B5\uB2C8\uB2E4. \uC774\uBBF8 \uC5F4\uB824 \uC788\uB294 Codex \uC5D0\uC11C\uB294 /new \uB85C \uC0C8 \uB300\uD654\uB97C \uC5F4\uC5B4\uC57C \uC9D3\uB2E4 \uB3C4\uAD6C\uAC00 \uBCF4\uC785\uB2C8\uB2E4(\uC9C0\uAE08 \uB300\uD654\uC5D0\uB294 \uBD99\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4). (/hooks \uC5D0\uC11C jitda \uD6C5\uC744 \uC2E0\uB8B0\uD558\uBA74 \uD134\uC774 \uB05D\uB0A0 \uB54C \uBC14\uB85C \uBCF4\uB0B4\uACE0 \uB85C\uADF8\uC778 \uC54C\uB9BC\uB3C4 \uBC1B\uC2B5\uB2C8\uB2E4)"
660
3117
  };
661
3118
  }
3119
+ function uninstallWith(agent, cmd, commands) {
3120
+ if (!available(cmd)) return { agent, status: "skipped", message: `${cmd} \uBA85\uB839\uC744 \uCC3E\uC9C0 \uBABB\uD574 \uAC74\uB108\uB701\uB2C8\uB2E4.` };
3121
+ for (const args of commands) {
3122
+ const result = run(cmd, args);
3123
+ if (!result.ok && !ALREADY_GONE.test(result.output)) {
3124
+ return { agent, status: "failed", message: `\uC81C\uAC70 \uC2E4\uD328(${args.join(" ")}): ${result.output}
3125
+ ${agent} \uC5D0\uB294 \uC544\uC9C1 \uC9D3\uB2E4 \uD50C\uB7EC\uADF8\uC778\uC774 \uB0A8\uC544 \uAE30\uB85D\uB420 \uC218 \uC788\uC2B5\uB2C8\uB2E4. \uB2E4\uC2DC \uC2E4\uD589\uD558\uC138\uC694.` };
3126
+ }
3127
+ }
3128
+ return { agent, status: "ok", message: "\uC81C\uAC70\uD588\uC2B5\uB2C8\uB2E4." };
3129
+ }
662
3130
  function uninstallClaude() {
663
- if (!available("claude")) return { agent: "Claude Code", ok: false, message: "claude \uBA85\uB839\uC744 \uCC3E\uC9C0 \uBABB\uD574 \uAC74\uB108\uB701\uB2C8\uB2E4." };
664
- run("claude", ["plugin", "uninstall", PLUGIN]);
665
- run("claude", ["plugin", "marketplace", "remove", MARKETPLACE]);
666
- return { agent: "Claude Code", ok: true, message: "\uC81C\uAC70\uD588\uC2B5\uB2C8\uB2E4." };
3131
+ return uninstallWith("Claude Code", "claude", [
3132
+ ["plugin", "uninstall", PLUGIN],
3133
+ ["plugin", "marketplace", "remove", MARKETPLACE]
3134
+ ]);
667
3135
  }
668
3136
  function uninstallCodex() {
669
- if (!available("codex")) return { agent: "Codex", ok: false, message: "codex \uBA85\uB839\uC744 \uCC3E\uC9C0 \uBABB\uD574 \uAC74\uB108\uB701\uB2C8\uB2E4." };
670
- run("codex", ["plugin", "remove", PLUGIN]);
671
- run("codex", ["plugin", "marketplace", "remove", MARKETPLACE]);
672
- return { agent: "Codex", ok: true, message: "\uC81C\uAC70\uD588\uC2B5\uB2C8\uB2E4." };
3137
+ return uninstallWith("Codex", "codex", [
3138
+ ["plugin", "remove", PLUGIN],
3139
+ ["plugin", "marketplace", "remove", MARKETPLACE]
3140
+ ]);
3141
+ }
3142
+ var OWN_ENTRY = /^(?:folders|credentials|config\.json|watch-state\.json|watch-pending|watch-pending\.json)(?:\.\d+\.tmp)?$/;
3143
+ function listDir2(dir) {
3144
+ try {
3145
+ return fs8.readdirSync(dir);
3146
+ } catch {
3147
+ return [];
3148
+ }
3149
+ }
3150
+ var FINAL_SEND_MS = 15e3;
3151
+ async function removeData(log) {
3152
+ const home = stateHome();
3153
+ const resolved = path8.resolve(home);
3154
+ if (!isRemovableJitdaDir(home, "mcp")) {
3155
+ log(`\uB85C\uADF8\uC778 \uC815\uBCF4\xB7\uAE30\uB85D \uC704\uCE58(${home})\uAC00 \uC774\uC0C1\uD574 \uC9C0\uC6B0\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4. JITDA_MCP_HOME \uC124\uC815\uC744 \uD655\uC778\uD558\uC138\uC694.`);
3156
+ return;
3157
+ }
3158
+ const folders = Object.keys(readCredentials()).filter((fp) => pendingCount(fp) > 0);
3159
+ if (folders.length) {
3160
+ const recorder = new Recorder();
3161
+ const sending = Promise.all(folders.map((fp) => recorder.flush(fp).catch(() => null)));
3162
+ await Promise.race([sending, new Promise((resolve) => setTimeout(resolve, FINAL_SEND_MS).unref())]);
3163
+ recorder.stopSending();
3164
+ await sending;
3165
+ }
3166
+ const lost = Object.keys(readCredentials()).reduce((sum, fp) => sum + pendingCount(fp), 0);
3167
+ if (lost) log(`\uBCF4\uB0B4\uC9C0 \uBABB\uD55C \uAE30\uB85D ${lost}\uAC74\uC740 \uBCF4\uB0B4\uC9C0 \uBABB\uD55C \uCC44 \uC9C0\uC6C1\uB2C8\uB2E4(\uC11C\uBC84\uC5D0 \uC5F0\uACB0\uD560 \uC218 \uC5C6\uC5C8\uAC70\uB098 \uB300\uD68C \uD3F4\uB354 \uD45C\uC2DC\uAC00 \uBC14\uB00C\uC5C8\uC2B5\uB2C8\uB2E4).`);
3168
+ const others = [];
3169
+ for (const name of listDir2(resolved)) {
3170
+ if (OWN_ENTRY.test(name)) fs8.rmSync(path8.join(resolved, name), { recursive: true, force: true });
3171
+ else others.push(name);
3172
+ }
3173
+ if (others.length) log(`${home} \uC548\uC758 \uD50C\uB7EC\uADF8\uC778 \uAC83\uC774 \uC544\uB2CC \uD30C\uC77C(${others.slice(0, 5).join(", ")}${others.length > 5 ? " \u2026" : ""})\uC740 \uB0A8\uACA8 \uB450\uC5C8\uC2B5\uB2C8\uB2E4.`);
3174
+ else {
3175
+ try {
3176
+ fs8.rmdirSync(resolved);
3177
+ } catch {
3178
+ }
3179
+ }
3180
+ const parent = path8.dirname(resolved);
3181
+ if (path8.basename(parent) === ".jitda") {
3182
+ try {
3183
+ if (!fs8.readdirSync(parent).length) fs8.rmdirSync(parent);
3184
+ } catch {
3185
+ }
3186
+ }
3187
+ log(others.length ? `\uB85C\uADF8\uC778 \uC815\uBCF4\xB7\uAE30\uB85D(${home} \uC548\uC758 \uC9D3\uB2E4 \uD30C\uC77C)\uC744 \uC9C0\uC6E0\uC2B5\uB2C8\uB2E4.` : `\uB85C\uADF8\uC778 \uC815\uBCF4\xB7\uAE30\uB85D(${home})\uC744 \uC9C0\uC6E0\uC2B5\uB2C8\uB2E4.`);
673
3188
  }
674
3189
  var HELP = `\uC9D3\uB2E4 \uC5D0\uC774\uC804\uD2B8 \uD50C\uB7EC\uADF8\uC778 \uC124\uCE58\uAE30
675
3190
 
@@ -677,10 +3192,11 @@ var HELP = `\uC9D3\uB2E4 \uC5D0\uC774\uC804\uD2B8 \uD50C\uB7EC\uADF8\uC778 \uC12
677
3192
  npx jitda-agent Claude Code\xB7Codex \uC5D0 \uC9D3\uB2E4 \uD50C\uB7EC\uADF8\uC778\uC744 \uC124\uCE58\uD558\uAC70\uB098 \uC5C5\uB370\uC774\uD2B8\uD569\uB2C8\uB2E4
678
3193
  npx jitda-agent --claude Claude Code \uC5D0\uB9CC \uC124\uCE58\uD569\uB2C8\uB2E4(--codex \uB3C4 \uAC19\uB2E4)
679
3194
  npx jitda-agent --dev \uAC1C\uBC1C \uC11C\uBC84(dev.jitda.io)\uB97C \uBC14\uB77C\uBCF4\uAC8C \uC124\uCE58\uD569\uB2C8\uB2E4
680
- npx jitda-agent uninstall \uD50C\uB7EC\uADF8\uC778\uC744 \uC81C\uAC70\uD569\uB2C8\uB2E4(\uB300\uD654 \uAE30\uB85D\xB7\uB85C\uADF8\uC778 \uC815\uBCF4\uB294 \uB0A8\uC2B5\uB2C8\uB2E4)
3195
+ npx jitda-agent uninstall \uD50C\uB7EC\uADF8\uC778\uC744 \uC81C\uAC70\uD558\uACE0 \uB85C\uADF8\uC778 \uC815\uBCF4\xB7\uAE30\uB85D(~/.jitda)\uB3C4 \uC9C0\uC6C1\uB2C8\uB2E4
3196
+ (\uBABB \uBCF4\uB0B8 \uAE30\uB85D\uC740 \uBA3C\uC800 \uBCF4\uB0B4 \uBD05\uB2C8\uB2E4. \uB0A8\uAE30\uB824\uBA74 --keep-data)
681
3197
 
682
- \uC124\uCE58\uD55C \uB4A4 \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354\uC5D0\uC11C Claude Code \uB098 Codex \uB97C \uC5F4\uACE0 "\uC9D3\uB2E4 \uB85C\uADF8\uC778\uD574 \uC918"\uB77C\uACE0 \uD558\uC138\uC694.`;
683
- function main(argv, log = console.log) {
3198
+ \uC124\uCE58\uD55C \uB4A4 \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354\uC758 Claude Code \uB098 Codex \uC5D0\uC11C "\uC9D3\uB2E4 \uB85C\uADF8\uC778\uD574 \uC918"\uB77C\uACE0 \uD558\uC138\uC694.`;
3199
+ async function main(argv, log = console.log) {
684
3200
  let options;
685
3201
  try {
686
3202
  options = parseArgs(argv);
@@ -696,9 +3212,23 @@ function main(argv, log = console.log) {
696
3212
  const dir = agentHome();
697
3213
  if (options.command === "uninstall") {
698
3214
  const steps2 = [uninstallClaude(), uninstallCodex()];
699
- fs2.rmSync(dir, { recursive: true, force: true });
700
3215
  for (const step of steps2) log(`- ${step.agent}: ${step.message}`);
701
- log(`\uD50C\uB7EC\uADF8\uC778 \uD30C\uC77C(${dir})\uC744 \uC9C0\uC6E0\uC2B5\uB2C8\uB2E4. \uB300\uD654 \uAE30\uB85D\xB7\uB85C\uADF8\uC778 \uC815\uBCF4(~/.jitda/mcp)\uB294 \uB0A8\uACA8 \uB450\uC5C8\uC2B5\uB2C8\uB2E4.`);
3216
+ if (steps2.some((step) => step.status === "failed")) {
3217
+ log(`\uC81C\uAC70\uD558\uC9C0 \uBABB\uD55C \uC5D0\uC774\uC804\uD2B8\uAC00 \uC788\uC5B4 \uD50C\uB7EC\uADF8\uC778 \uD30C\uC77C(${dir})\uC740 \uB0A8\uACA8 \uB450\uC5C8\uC2B5\uB2C8\uB2E4.`);
3218
+ return 1;
3219
+ }
3220
+ if (isRemovableJitdaDir(dir, "agent") && looksLikeOurPlugin(dir)) {
3221
+ fs8.rmSync(dir, { recursive: true, force: true });
3222
+ log(`\uD50C\uB7EC\uADF8\uC778 \uD30C\uC77C(${dir})\uC744 \uC9C0\uC6E0\uC2B5\uB2C8\uB2E4.`);
3223
+ } else {
3224
+ log(`\uD50C\uB7EC\uADF8\uC778 \uD30C\uC77C \uC704\uCE58(${dir})\uAC00 \uC9D3\uB2E4 \uD50C\uB7EC\uADF8\uC778 \uD3F4\uB354\uB85C \uBCF4\uC774\uC9C0 \uC54A\uC544 \uC9C0\uC6B0\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4. JITDA_AGENT_HOME \uC124\uC815\uC744 \uD655\uC778\uD558\uC138\uC694.`);
3225
+ }
3226
+ if (options.keepData) {
3227
+ log(`\uB85C\uADF8\uC778 \uC815\uBCF4\xB7\uAE30\uB85D(${stateHome()})\uC740 \uB0A8\uACA8 \uB450\uC5C8\uC2B5\uB2C8\uB2E4(--keep-data). \uB2E4\uC2DC \uC124\uCE58\uD558\uBA74 \uC774\uC5B4\uC11C \uAE30\uB85D\uD569\uB2C8\uB2E4.`);
3228
+ } else {
3229
+ await removeData(log);
3230
+ }
3231
+ log("\uB300\uD68C \uD3F4\uB354\uC758 .jitda \uD30C\uC77C\uC740 \uB0A8\uC544 \uC788\uC2B5\uB2C8\uB2E4. \uB354\uB294 \uAE30\uB85D\uD558\uC9C0 \uC54A\uC73C\uB824\uBA74 \uC9C0\uC6CC\uB3C4 \uB429\uB2C8\uB2E4(\uD574\uCEE4\uD1A4 \uBC88\uD638\uB9CC \uC801\uD78C \uD45C\uC2DC \uD30C\uC77C\uC785\uB2C8\uB2E4).");
702
3232
  return 0;
703
3233
  }
704
3234
  try {
@@ -719,14 +3249,18 @@ function main(argv, log = console.log) {
719
3249
  log(`- \uC11C\uBC84: ${"api_url" in server ? `${server.api_url} (\uAC1C\uBC1C\uC6A9)` : "\uC6B4\uC601(hackathon.jitda.io)"}`);
720
3250
  if (before.api_url && !("api_url" in server)) log(` (\uC774\uC804\uC5D0 \uC4F0\uB358 ${before.api_url} \uC124\uC815\uC740 \uC9C0\uC6E0\uC2B5\uB2C8\uB2E4)`);
721
3251
  for (const step of steps) log(`- ${step.agent}: ${step.message}`);
722
- if (!steps.some((step) => step.ok)) {
3252
+ const installed = steps.filter((step) => step.status === "ok").map((step) => step.agent);
3253
+ if (!installed.length && !steps.some((step) => step.status === "failed")) {
723
3254
  log("Claude Code \uC640 Codex \uB97C \uD558\uB098\uB3C4 \uCC3E\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. \uB458 \uC911 \uD558\uB098\uB97C \uC124\uCE58\uD55C \uB4A4 \uB2E4\uC2DC \uC2E4\uD589\uD558\uC138\uC694.");
724
3255
  return 1;
725
3256
  }
726
- log("");
727
- log('\uC774\uC81C \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354\uC5D0\uC11C Claude Code \uB098 Codex \uB97C \uC5F4\uACE0 "\uC9D3\uB2E4 \uB85C\uADF8\uC778\uD574 \uC918"\uB77C\uACE0 \uD558\uC138\uC694.');
728
- return 0;
3257
+ if (installed.length) {
3258
+ log("");
3259
+ const codex = installed.includes("Codex") ? " Codex \uB294 /new \uB85C \uC0C8 \uB300\uD654\uB97C \uC5F0 \uB4A4 \uB9D0\uD558\uC138\uC694." : "";
3260
+ log(`\uC774\uC81C \uB300\uD68C \uC791\uC5C5 \uD3F4\uB354\uC758 ${installed.join(" \uB098 ")} \uC5D0\uC11C "\uC9D3\uB2E4 \uB85C\uADF8\uC778\uD574 \uC918"\uB77C\uACE0 \uD558\uC138\uC694.${codex}`);
3261
+ }
3262
+ return steps.some((step) => step.status === "failed") ? 1 : 0;
729
3263
  }
730
3264
 
731
3265
  // src/install-cli.ts
732
- process.exitCode = main(process.argv.slice(2));
3266
+ process.exitCode = await main(process.argv.slice(2));