hinacode 0.2.0-alpha.2 → 0.2.0-alpha.3

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.
@@ -10328,12 +10328,12 @@ const parseIpv6Segments = (input) => {
10328
10328
  }
10329
10329
  const halves = input.split("::");
10330
10330
  if (halves.length > 2) return addressError(input, "only one compression marker is allowed");
10331
- const head = halves[0] === "" ? [] : halves[0].split(":");
10331
+ const head2 = halves[0] === "" ? [] : halves[0].split(":");
10332
10332
  const tail2 = halves.length === 2 && halves[1] !== "" ? halves[1].split(":") : [];
10333
- if (head.some((part) => part === "") || tail2.some((part) => part === "")) {
10333
+ if (head2.some((part) => part === "") || tail2.some((part) => part === "")) {
10334
10334
  return addressError(input, "empty segments are only valid in the compression marker");
10335
10335
  }
10336
- const trailing = tail2.length > 0 ? tail2[tail2.length - 1] : head.length > 0 ? head[head.length - 1] : "";
10336
+ const trailing = tail2.length > 0 ? tail2[tail2.length - 1] : head2.length > 0 ? head2[head2.length - 1] : "";
10337
10337
  let embedded;
10338
10338
  if (trailing.includes(".")) {
10339
10339
  if (halves.length === 2 && tail2.length === 0) {
@@ -10346,14 +10346,14 @@ const parseIpv6Segments = (input) => {
10346
10346
  if (isFailure$1(parsed)) return parsed;
10347
10347
  embedded = parsed.success;
10348
10348
  if (tail2.length > 0) tail2.pop();
10349
- else head.pop();
10349
+ else head2.pop();
10350
10350
  }
10351
- const explicit = head.length + tail2.length + (embedded ? 2 : 0);
10351
+ const explicit = head2.length + tail2.length + (embedded ? 2 : 0);
10352
10352
  if (halves.length === 1 ? explicit !== 8 : explicit >= 8) {
10353
10353
  return addressError(input, halves.length === 1 ? "expected eight segments" : "compression must replace at least one segment");
10354
10354
  }
10355
10355
  const parse2 = (part) => /^[0-9a-fA-F]{1,4}$/.test(part) ? Number.parseInt(part, 16) : void 0;
10356
- const parsedHead = head.map(parse2);
10356
+ const parsedHead = head2.map(parse2);
10357
10357
  const parsedTail = tail2.map(parse2);
10358
10358
  if (parsedHead.some((part) => part === void 0) || parsedTail.some((part) => part === void 0)) {
10359
10359
  return addressError(input, "segments must contain one through four hexadecimal digits");
@@ -10398,9 +10398,9 @@ const formatIp = (self) => {
10398
10398
  }
10399
10399
  }
10400
10400
  if (bestLength < 2) return segments.map((segment) => segment.toString(16)).join(":");
10401
- const head = segments.slice(0, bestStart).map((segment) => segment.toString(16)).join(":");
10401
+ const head2 = segments.slice(0, bestStart).map((segment) => segment.toString(16)).join(":");
10402
10402
  const tail2 = segments.slice(bestStart + bestLength).map((segment) => segment.toString(16)).join(":");
10403
- return `${head}::${tail2}`;
10403
+ return `${head2}::${tail2}`;
10404
10404
  };
10405
10405
  const isIpv4Mapped = (self) => {
10406
10406
  const {
@@ -11813,6 +11813,9 @@ const checkCapacity = (self) => {
11813
11813
  if (diff === 0) return;
11814
11814
  }
11815
11815
  };
11816
+ const invalidate = /* @__PURE__ */ dual(2, (self, key2) => sync$1(() => {
11817
+ remove$3(self.map, key2);
11818
+ }));
11816
11819
  const await_ = fiberAwait;
11817
11820
  const join$1 = fiberJoin;
11818
11821
  const interrupt = fiberInterrupt;
@@ -11850,10 +11853,10 @@ const make$1o = () => ({
11850
11853
  length: 0
11851
11854
  });
11852
11855
  const compactHead = (self) => {
11853
- const head = self.head;
11854
- if (head.offset >= 1024 && head === self.tail && head.mutable && (head.array.length - head.offset) * 8 <= head.offset) {
11856
+ const head2 = self.head;
11857
+ if (head2.offset >= 1024 && head2 === self.tail && head2.mutable && (head2.array.length - head2.offset) * 8 <= head2.offset) {
11855
11858
  self.head = self.tail = {
11856
- array: head.array.slice(head.offset),
11859
+ array: head2.array.slice(head2.offset),
11857
11860
  mutable: true,
11858
11861
  offset: 0,
11859
11862
  next: void 0
@@ -14489,7 +14492,7 @@ const make$1b = /* @__PURE__ */ sync(() => {
14489
14492
  set2.forEach((run2) => run2());
14490
14493
  });
14491
14494
  };
14492
- const invalidate = (keys2) => contextWith((services) => {
14495
+ const invalidate2 = (keys2) => contextWith((services) => {
14493
14496
  const pending = getOrUndefined(services, PendingInvalidation);
14494
14497
  if (pending) {
14495
14498
  keysToHashes(keys2, (hash2) => {
@@ -14500,7 +14503,7 @@ const make$1b = /* @__PURE__ */ sync(() => {
14500
14503
  }
14501
14504
  return void_$1;
14502
14505
  });
14503
- const mutation = (keys2, effect2) => tap$2(effect2, invalidate(keys2));
14506
+ const mutation = (keys2, effect2) => tap$2(effect2, invalidate2(keys2));
14504
14507
  const registerUnsafe = (keys2, handler) => {
14505
14508
  const resolvedKeys = [];
14506
14509
  keysToHashes(keys2, (hash2) => {
@@ -14573,7 +14576,7 @@ const make$1b = /* @__PURE__ */ sync(() => {
14573
14576
  query: query2,
14574
14577
  stream: stream2,
14575
14578
  invalidateUnsafe,
14576
- invalidate,
14579
+ invalidate: invalidate2,
14577
14580
  registerUnsafe,
14578
14581
  withBatch
14579
14582
  });
@@ -15548,12 +15551,12 @@ const extractPrimitive = (value2, onCustom, placeholder, withoutTransform) => {
15548
15551
  if (value2 === void 0) {
15549
15552
  return null;
15550
15553
  } else if (isFragment(value2)) {
15551
- const head = value2.segments[0];
15552
- if (head._tag === "Custom") {
15553
- const compiled = onCustom(head, placeholder, withoutTransform);
15554
+ const head2 = value2.segments[0];
15555
+ if (head2._tag === "Custom") {
15556
+ const compiled = onCustom(head2, placeholder, withoutTransform);
15554
15557
  return compiled[1][0] ?? null;
15555
- } else if (head._tag === "Parameter") {
15556
- return head.value;
15558
+ } else if (head2._tag === "Parameter") {
15559
+ return head2.value;
15557
15560
  }
15558
15561
  return null;
15559
15562
  }
@@ -15984,6 +15987,15 @@ const Compaction = Union2([
15984
15987
  /** `message` is null when the turn ended before the compaction reported back. */
15985
15988
  Struct({ status: Literal2("failed"), message: NullOr(String$1) })
15986
15989
  ]);
15990
+ const ForkPoint = Struct({
15991
+ sessionId: String$1,
15992
+ checkpoint: String$1,
15993
+ /**
15994
+ * The agent and account whose home holds the session, stamped by HinaCode once the turn ends. Points saved
15995
+ * before it was recorded leave it out, and belong to the thread's own agent and account.
15996
+ */
15997
+ owner: optional$7(Struct({ provider: ProviderId, accountId: NullOr(String$1) }))
15998
+ });
15987
15999
  const AgentEvent = Union2([
15988
16000
  Struct({ type: Literal2("session_bound"), providerSessionId: String$1 }),
15989
16001
  Struct({ type: Literal2("text_delta"), text: String$1 }),
@@ -16019,7 +16031,12 @@ const AgentEvent = Union2([
16019
16031
  /** Raised by the built-in MCP server, not the provider, while a turn runs. */
16020
16032
  Struct({ type: Literal2("secret_requested"), request: SecretRequest }),
16021
16033
  Struct({ type: Literal2("secret_resolved"), requestId: String$1 }),
16022
- Struct({ type: Literal2("turn_completed"), usage: optional$7(TokenUsage) }),
16034
+ /** `forkPoint` is left out by an agent that cannot fork its session there. */
16035
+ Struct({
16036
+ type: Literal2("turn_completed"),
16037
+ usage: optional$7(TokenUsage),
16038
+ forkPoint: optional$7(ForkPoint)
16039
+ }),
16023
16040
  Struct({ type: Literal2("turn_failed"), message: String$1 }),
16024
16041
  Struct({ type: Literal2("turn_limited"), limit: UsageLimit })
16025
16042
  ]);
@@ -16166,6 +16183,14 @@ const GitHubAuth = Union2([
16166
16183
  Struct({ type: Literal2("signedOut") }),
16167
16184
  Struct({ type: Literal2("signedIn"), host: String$1, login: String$1 })
16168
16185
  ]);
16186
+ const GitHubRateLimit = Struct({
16187
+ resource: String$1,
16188
+ limit: Number$1,
16189
+ remaining: Number$1,
16190
+ used: Number$1,
16191
+ /** Epoch milliseconds. */
16192
+ resetsAt: Number$1
16193
+ });
16169
16194
  const UpdateState = Union2([
16170
16195
  Struct({ type: Literal2("unsupported") }),
16171
16196
  Struct({ type: Literal2("idle") }),
@@ -16361,6 +16386,8 @@ const Thread = Struct({
16361
16386
  accountId: NullOr(String$1),
16362
16387
  /** Claude session_id or Codex thread id, used to resume. */
16363
16388
  providerSessionId: NullOr(String$1),
16389
+ /** Set on a fork until its first turn binds `providerSessionId`, which starts the session from there. */
16390
+ forkedFrom: NullOr(ForkPoint).pipe(withDecodingDefaultKey(succeed$3(null))),
16364
16391
  status: ThreadStatus,
16365
16392
  usageLimit: NullOr(UsageLimit),
16366
16393
  sortIndex: Number$1,
@@ -16398,7 +16425,9 @@ const MessagePart = Union2([
16398
16425
  Struct({ type: Literal2("attachment"), attachment: Attachment }),
16399
16426
  /** Questions the agent posted without waiting; `text` is how they read once answered. */
16400
16427
  Struct({ type: Literal2("questions"), text: String$1, questions: ArraySchema(Question) }),
16401
- Struct({ type: Literal2("compaction"), compaction: Compaction })
16428
+ Struct({ type: Literal2("compaction"), compaction: Compaction }),
16429
+ /** The thread moved to another agent. The turn after it starts a new session that gets the transcript above. */
16430
+ Struct({ type: Literal2("agent_switch"), from: ProviderId, to: ProviderId })
16402
16431
  ]);
16403
16432
  const MessageRole = Literals(["user", "assistant"]);
16404
16433
  const Message = Struct({
@@ -16408,7 +16437,9 @@ const Message = Struct({
16408
16437
  parts: ArraySchema(MessagePart),
16409
16438
  createdAt: Timestamp,
16410
16439
  completedAt: NullOr(Timestamp),
16411
- usage: NullOr(TokenUsage)
16440
+ usage: NullOr(TokenUsage),
16441
+ /** Set on the message that ended a turn, when the agent can fork its session there. */
16442
+ forkPoint: NullOr(ForkPoint).pipe(withDecodingDefaultKey(succeed$3(null)))
16412
16443
  });
16413
16444
  const Locale = Literals(["en", "zh-TW", "ja"]);
16414
16445
  const ThemeId = Literals([
@@ -16978,6 +17009,8 @@ const rpc = (request, response) => ({ request, response });
16978
17009
  const RpcMethods = {
16979
17010
  "app.ready": rpc(Void2, Void2),
16980
17011
  "app.focus": rpc(Void2, Void2),
17012
+ /** The number on the Dock icon. Zero clears it. */
17013
+ "app.setBadgeCount": rpc(Struct({ count: Int.check(isGreaterThanOrEqualTo$1(0)) }), Void2),
16981
17014
  /** The appearance of native UI (glass, menus, dialogs), which follows the app theme rather than the system. */
16982
17015
  "app.setColorScheme": rpc(Literals(["dark", "light", "system"]), Void2),
16983
17016
  "browser.open": rpc(
@@ -17089,6 +17122,8 @@ const RpcMethods = {
17089
17122
  /** Null when the scope has no base: the thread has no live worktree, or no turn started in a git checkout. */
17090
17123
  "threads.changes": rpc(Struct({ threadId: String$1, scope: ChangesScope }), NullOr(Changes)),
17091
17124
  /** Archives the thread, removing its worktree when `Settings.archive.removeWorktree` is on. */
17125
+ /** A new thread that goes on from the turn `messageId` ended, in the same workspace. */
17126
+ "threads.fork": rpc(Struct({ threadId: String$1, messageId: String$1 }), Thread),
17092
17127
  "threads.archive": rpc(Struct({ threadId: String$1 }), Thread),
17093
17128
  /** Brings an archived thread back as idle. A removed worktree stays removed. */
17094
17129
  "threads.unarchive": rpc(Struct({ threadId: String$1 }), Thread),
@@ -17483,6 +17518,7 @@ const methodKind = {
17483
17518
  "browser.close": "mutation",
17484
17519
  "app.ready": "mutation",
17485
17520
  "app.focus": "mutation",
17521
+ "app.setBadgeCount": "mutation",
17486
17522
  "app.setColorScheme": "mutation",
17487
17523
  "projects.list": "read",
17488
17524
  "projects.create": "mutation",
@@ -17503,6 +17539,7 @@ const methodKind = {
17503
17539
  "worktrees.stopSetup": "mutation",
17504
17540
  "worktrees.pullRequest": "read",
17505
17541
  "threads.changes": "read",
17542
+ "threads.fork": "mutation",
17506
17543
  "threads.archive": "mutation",
17507
17544
  "threads.unarchive": "mutation",
17508
17545
  "projects.currentBranch": "read",
@@ -17641,6 +17678,7 @@ const mutations = new Set(
17641
17678
  const desktopOnlyMethods = /* @__PURE__ */ new Set([
17642
17679
  "app.ready",
17643
17680
  "app.focus",
17681
+ "app.setBadgeCount",
17644
17682
  "app.setColorScheme",
17645
17683
  "dialog.pickFolder",
17646
17684
  "dialog.pickFiles",
@@ -17704,6 +17742,12 @@ const PushEvent = Union2([
17704
17742
  links: ArraySchema(PullRequestLink)
17705
17743
  }),
17706
17744
  Struct({ type: Literal2("pullRequest.guide"), url: String$1, state: PullRequestGuideState }),
17745
+ /** The GitHub budget dropped below a fifth (`low`) or ran out (`exhausted`). Sent once per level per window. */
17746
+ Struct({
17747
+ type: Literal2("github.rateLimit"),
17748
+ level: Literals(["low", "exhausted"]),
17749
+ rateLimit: GitHubRateLimit
17750
+ }),
17707
17751
  /** Every sub-agent of the thread, newest first, sent whenever one of them changes. */
17708
17752
  Struct({
17709
17753
  type: Literal2("thread.subagents"),
@@ -19588,7 +19632,7 @@ class PersistenceError extends TaggedError()("PersistenceError", {
19588
19632
  }
19589
19633
  }
19590
19634
  class NotFoundError extends TaggedError()("NotFoundError", {
19591
- entity: Literals(["project", "thread", "worktree", "automation", "terminal", "account"]),
19635
+ entity: Literals(["project", "thread", "worktree", "automation", "terminal", "account", "fork point"]),
19592
19636
  id: String$1
19593
19637
  }) {
19594
19638
  get message() {
@@ -20705,6 +20749,8 @@ const layer$I = effect(
20705
20749
  if (session.turn === null) return;
20706
20750
  if ((event.type === "turn_failed" || event.type === "turn_limited") && session.interrupted)
20707
20751
  event = { type: "turn_failed", message: "Interrupted" };
20752
+ if (event.type === "turn_completed" && session.sessionId !== null && session.lastAssistantUuid !== null)
20753
+ event = { ...event, forkPoint: { sessionId: session.sessionId, checkpoint: session.lastAssistantUuid } };
20708
20754
  offerUnsafe(session.turn, event);
20709
20755
  if (isTerminal(event)) {
20710
20756
  endUnsafe(session.turn);
@@ -20839,6 +20885,7 @@ const layer$I = effect(
20839
20885
  return;
20840
20886
  }
20841
20887
  } else if (stale) return;
20888
+ if (message.type === "assistant" && message.parent_tool_use_id === null) session.lastAssistantUuid = message.uuid;
20842
20889
  if (message.type === "system" && message.subtype === "init") {
20843
20890
  session.sessionId = message.session_id;
20844
20891
  resumable.set(session.threadId, {
@@ -20911,6 +20958,7 @@ const layer$I = effect(
20911
20958
  ...hidden !== null && { skillOverrides: hidden }
20912
20959
  },
20913
20960
  ...resume === void 0 ? {} : { resume },
20961
+ ...input.forkAt !== null && { forkSession: true, resumeSessionAt: input.forkAt },
20914
20962
  includePartialMessages: true,
20915
20963
  settingSources: ["user", "project", "local"],
20916
20964
  systemPrompt: { type: "preset", preset: "claude_code", append: input.instructions },
@@ -20958,6 +21006,7 @@ const layer$I = effect(
20958
21006
  subagents: /* @__PURE__ */ new Map(),
20959
21007
  lastRequest: null,
20960
21008
  sessionId: resume ?? null,
21009
+ lastAssistantUuid: null,
20961
21010
  turn: null,
20962
21011
  interrupted: false,
20963
21012
  turnPrompts: /* @__PURE__ */ new Set(),
@@ -21012,12 +21061,15 @@ const layer$I = effect(
21012
21061
  session.turnPrompts.clear();
21013
21062
  }).pipe(andThen(interruptQuery(session))) : void_$1;
21014
21063
  const wake = (session) => gen(function* () {
21064
+ const { sessionId } = session;
21065
+ if (sessionId === null) return;
21015
21066
  const turn = yield* unbounded();
21016
21067
  session.reportsState = true;
21017
21068
  openTurn(session, turn);
21018
21069
  const events = fromQueue(turn).pipe(ensuring(suspend$2(() => abandon(session, turn))));
21019
21070
  yield* offer(wakes, {
21020
21071
  threadId: session.threadId,
21072
+ sessionId,
21021
21073
  events,
21022
21074
  discard: suspend$2(() => abandon(session, turn))
21023
21075
  });
@@ -21158,6 +21210,11 @@ const layer$I = effect(
21158
21210
  const session = sessions.get(threadId);
21159
21211
  return session === void 0 ? void_$1 : interruptQuery(session);
21160
21212
  },
21213
+ closeSession: (threadId) => sync(() => {
21214
+ resumable.delete(threadId);
21215
+ const session = sessions.get(threadId);
21216
+ if (session !== void 0) closeSessionUnsafe(session);
21217
+ }),
21161
21218
  contextBreakdown: (threadId) => suspend$2(() => {
21162
21219
  const session = sessions.get(threadId);
21163
21220
  if (session === void 0) return succeed$3(null);
@@ -21558,6 +21615,14 @@ const usageLimitLayer = (scenario = "usage-limit", resetAfterMs = 6e4) => effect
21558
21615
  });
21559
21616
  })
21560
21617
  );
21618
+ const COMPACT_COMMAND = {
21619
+ trigger: "/",
21620
+ name: "compact",
21621
+ description: "Free up context by summarizing the conversation so far",
21622
+ argumentHint: "",
21623
+ builtin: true
21624
+ };
21625
+ const isCompactCommand = (prompt) => prompt.trim() === "/compact";
21561
21626
  const approvalPolicies = {
21562
21627
  supervised: "untrusted",
21563
21628
  auto: "on-request",
@@ -22113,6 +22178,34 @@ const make$_ = gen(function* () {
22113
22178
  };
22114
22179
  return terminals.client.request("thread/backgroundTerminals/terminate", params2).pipe(andThen(refreshTerminals(threadId, terminals)), asVoid);
22115
22180
  });
22181
+ const stopSubagents = (threadId, home) => gen(function* () {
22182
+ const subagents = subagentsByThread.get(threadId);
22183
+ if (subagents === void 0) return;
22184
+ subagentsByThread.delete(threadId);
22185
+ const client2 = clients.get(JSON.stringify(home))?.client;
22186
+ for (const [childThreadId, subagent] of subagents) {
22187
+ const turnId = subagentTurns.get(childThreadId);
22188
+ subagentTurns.delete(childThreadId);
22189
+ if (client2 === void 0 || turnId === void 0 || subagent.status !== "running") continue;
22190
+ yield* interruptTurn$1(client2, { threadId: childThreadId, turnId }).pipe(ignore$1);
22191
+ }
22192
+ });
22193
+ const closeSession = (threadId, home) => gen(function* () {
22194
+ yield* stopSubagents(threadId, home);
22195
+ const terminals = terminalsByThread.get(threadId);
22196
+ if (terminals === void 0) return;
22197
+ if (terminals.poll) yield* interrupt(terminals.poll);
22198
+ const listed = yield* listTerminals(terminals).pipe(orElseSucceed(() => []));
22199
+ yield* forEach$1(
22200
+ listed,
22201
+ ({ processId }) => {
22202
+ const params2 = { threadId: terminals.codexThreadId, processId };
22203
+ return terminals.client.request("thread/backgroundTerminals/terminate", params2).pipe(ignore$1);
22204
+ },
22205
+ { discard: true }
22206
+ );
22207
+ yield* refreshTerminals(threadId, terminals);
22208
+ });
22116
22209
  const listModels = gen(function* () {
22117
22210
  const client2 = yield* getClient(null);
22118
22211
  const models = [];
@@ -22169,8 +22262,9 @@ const make$_ = gen(function* () {
22169
22262
  return response.data.flatMap((entry) => entry.skills);
22170
22263
  });
22171
22264
  const listCommands = ({ cwd, home }) => listSkills2(cwd, home).pipe(
22172
- map$3(
22173
- (skills) => skills.filter((skill) => skill.enabled).map((skill) => {
22265
+ map$3((skills) => [
22266
+ COMPACT_COMMAND,
22267
+ ...skills.filter((skill) => skill.enabled).map((skill) => {
22174
22268
  const scope2 = commandScopes[skill.scope];
22175
22269
  return {
22176
22270
  trigger: "$",
@@ -22180,7 +22274,7 @@ const make$_ = gen(function* () {
22180
22274
  ...scope2 && { scope: scope2 }
22181
22275
  };
22182
22276
  })
22183
- )
22277
+ ])
22184
22278
  );
22185
22279
  const runTurn = (input) => callback(
22186
22280
  (out) => gen(function* () {
@@ -22219,24 +22313,44 @@ const make$_ = gen(function* () {
22219
22313
  if (resumed !== null && loadedLimit !== void 0 && loadedLimit !== input.autoCompactTokens) {
22220
22314
  yield* client2.request("thread/unsubscribe", { threadId: resumed });
22221
22315
  }
22222
- const { thread: thread2, sandbox } = input.resumeSessionId ? yield* client2.request("thread/resume", {
22316
+ const { thread: thread2, sandbox } = input.resumeSessionId === null ? yield* client2.request("thread/start", overrides) : input.forkAt === null ? yield* client2.request("thread/resume", {
22317
+ ...overrides,
22318
+ threadId: input.resumeSessionId,
22319
+ excludeTurns: true
22320
+ }) : yield* client2.request("thread/fork", {
22223
22321
  ...overrides,
22224
22322
  threadId: input.resumeSessionId,
22323
+ lastTurnId: input.forkAt,
22225
22324
  excludeTurns: true
22226
- }) : yield* client2.request("thread/start", overrides);
22325
+ });
22227
22326
  loadedCompactLimits.set(thread2.id, input.autoCompactTokens);
22228
22327
  yield* emit({ type: "session_bound", providerSessionId: thread2.id });
22229
- const skills = input.prompt.includes("$") ? (yield* listSkills2(input.cwd, input.home)).filter((skill) => input.userSkills || skill.scope !== "user") : [];
22230
- const turnStart = {
22231
- threadId: thread2.id,
22232
- input: [...userInput$1(input.prompt, input.attachments), ...skillInputs(input.prompt, skills)],
22233
- cwd: input.cwd,
22234
- ...input.effort === null ? {} : { effort: input.effort },
22235
- serviceTier: input.fastMode ? FAST_SERVICE_TIER : null,
22236
- ...turnAccess(input.accessMode, sandbox)
22237
- };
22238
- run2.turnStart = yield* client2.request("turn/start", turnStart).pipe(
22239
- map$3(({ turn: turn2 }) => ({ threadId: thread2.id, turnId: turn2.id })),
22328
+ const compacting = isCompactCommand(input.prompt);
22329
+ const startTurn = gen(function* () {
22330
+ const skills = input.prompt.includes("$") ? (yield* listSkills2(input.cwd, input.home)).filter((skill) => input.userSkills || skill.scope !== "user") : [];
22331
+ const turnStart = {
22332
+ threadId: thread2.id,
22333
+ input: [...userInput$1(input.prompt, input.attachments), ...skillInputs(input.prompt, skills)],
22334
+ cwd: input.cwd,
22335
+ ...input.effort === null ? {} : { effort: input.effort },
22336
+ serviceTier: input.fastMode ? FAST_SERVICE_TIER : null,
22337
+ ...turnAccess(input.accessMode, sandbox)
22338
+ };
22339
+ const { turn: turn2 } = yield* client2.request("turn/start", turnStart);
22340
+ return turn2.id;
22341
+ });
22342
+ const startCompaction = gen(function* () {
22343
+ yield* client2.request("thread/compact/start", { threadId: thread2.id });
22344
+ while (true) {
22345
+ const message = yield* take(inbox);
22346
+ if (message.kind === "exit") return yield* fail$2(message.error);
22347
+ if (message.kind !== "notification" || message.method !== "turn/started") continue;
22348
+ const params2 = message.params;
22349
+ if (params2.threadId === thread2.id) return params2.turn.id;
22350
+ }
22351
+ });
22352
+ run2.turnStart = yield* (compacting ? startCompaction : startTurn).pipe(
22353
+ map$3((turnId) => ({ threadId: thread2.id, turnId })),
22240
22354
  forkIn(providerScope)
22241
22355
  );
22242
22356
  const turn = yield* join$1(run2.turnStart);
@@ -22461,8 +22575,13 @@ const make$_ = gen(function* () {
22461
22575
  if (params2.item.type === "contextCompaction") {
22462
22576
  yield* emit({
22463
22577
  type: "compaction_updated",
22464
- // Codex starts compaction only by itself, and its item carries no token counts.
22465
- compaction: { status: "done", trigger: "auto", preTokens: null, postTokens: null }
22578
+ // Codex's item carries no token counts.
22579
+ compaction: {
22580
+ status: "done",
22581
+ trigger: compacting ? "manual" : "auto",
22582
+ preTokens: null,
22583
+ postTokens: null
22584
+ }
22466
22585
  });
22467
22586
  }
22468
22587
  yield* finishTool(params2.item);
@@ -22515,7 +22634,7 @@ const make$_ = gen(function* () {
22515
22634
  }
22516
22635
  openTools.clear();
22517
22636
  yield* emit(
22518
- status === "completed" ? { type: "turn_completed", usage } : { type: "turn_failed", message: error?.message ?? lastError ?? `Turn ${status}` }
22637
+ status === "completed" ? { type: "turn_completed", usage, forkPoint: { sessionId: thread2.id, checkpoint: turn.turnId } } : { type: "turn_failed", message: error?.message ?? lastError ?? `Turn ${status}` }
22519
22638
  );
22520
22639
  return true;
22521
22640
  }
@@ -22599,6 +22718,7 @@ const make$_ = gen(function* () {
22599
22718
  backgroundTasks: { changes: fromQueue(backgroundTaskChanges), stop: stopBackgroundTask },
22600
22719
  steer,
22601
22720
  interrupt: interrupt$12,
22721
+ closeSession,
22602
22722
  stopSubagent,
22603
22723
  respondApproval,
22604
22724
  respondQuestion,
@@ -22886,6 +23006,12 @@ const toPlanLimits = ({ window: window2, weekly, observedAtMs }) => ({
22886
23006
  ],
22887
23007
  readAt: iso(observedAtMs)
22888
23008
  });
23009
+ const SessionLeaveAck = Struct({ commandId: String$1 });
23010
+ const SessionLeaveCompleted = Struct({
23011
+ commandId: String$1,
23012
+ outcome: String$1,
23013
+ reason: optional$7(String$1)
23014
+ });
22889
23015
  const AccountState = Struct({
22890
23016
  /** `accountLogin` for a Meta login, `apiKey` or `envKey` for a key, `loggedOut`. Open for new lanes. */
22891
23017
  state: String$1,
@@ -23168,6 +23294,31 @@ const latestUsedTokens = (host, sessionId) => gen(function* () {
23168
23294
  const interruptTurn = (host, sessionId, turnId) => suspend$2(
23169
23295
  () => host.isAlive() ? host.command("turn/interrupt", { sessionId, turnId }).pipe(mapError(toAgentError)) : void_$1
23170
23296
  );
23297
+ const decodeLeaveCompleted = decodeUnknownOption(SessionLeaveCompleted);
23298
+ const leaveSession = (host, sessionId) => gen(function* () {
23299
+ const inbox = yield* unbounded();
23300
+ yield* host.subscribe((message) => offerUnsafe(inbox, message));
23301
+ const ack = yield* host.command("session/leave", { sessionId, stop: true }).pipe(mapError(toAgentError));
23302
+ const { commandId } = yield* decodeUnknownEffect(SessionLeaveAck)(ack).pipe(
23303
+ mapError(() => museError("session/leave: invalid response"))
23304
+ );
23305
+ while (true) {
23306
+ const message = yield* take(inbox);
23307
+ if (message.kind === "exit") return;
23308
+ if (message.kind !== "notification" || message.method !== "session/leaveCompleted") continue;
23309
+ const completed = decodeLeaveCompleted(message.params);
23310
+ if (isNone(completed) || completed.value.commandId !== commandId) continue;
23311
+ const { outcome, reason } = completed.value;
23312
+ if (outcome === "released") return;
23313
+ return yield* museError(`session/leave: ${outcome}${reason === void 0 ? "" : ` (${reason})`}`);
23314
+ }
23315
+ }).pipe(
23316
+ timeoutOrElse({
23317
+ duration: REQUEST_TIMEOUT,
23318
+ orElse: () => fail$2(museError(`session/leave did not complete within ${format(REQUEST_TIMEOUT)}`))
23319
+ }),
23320
+ scoped
23321
+ );
23171
23322
  const make$Z = gen(function* () {
23172
23323
  const providerScope = yield* scope;
23173
23324
  const hostLock = yield* make$1l(1);
@@ -23283,6 +23434,7 @@ const make$Z = gen(function* () {
23283
23434
  );
23284
23435
  offerUnsafe(wakes, {
23285
23436
  threadId,
23437
+ sessionId,
23286
23438
  events: events.pipe(ensuring(release2)),
23287
23439
  discard: release2.pipe(andThen(interruptTurn(entry.host, sessionId, turnId)), ignore$1)
23288
23440
  });
@@ -23360,7 +23512,7 @@ const make$Z = gen(function* () {
23360
23512
  const inWorkspace = [...entry.sessions.entries()].find(([, session]) => session.cwd === cwd)?.[0];
23361
23513
  const sessionId = own !== void 0 && entry.sessions.has(own) ? own : inWorkspace ?? (yield* probeSession(entry, cwd));
23362
23514
  const skills = yield* listSkills(entry.host, sessionId);
23363
- return skills.map(toCommand);
23515
+ return [COMPACT_COMMAND, ...skills.map(toCommand)];
23364
23516
  });
23365
23517
  const openSession = (entry, input) => gen(function* () {
23366
23518
  const { host, sessions } = entry;
@@ -23432,7 +23584,7 @@ const make$Z = gen(function* () {
23432
23584
  const openTools = /* @__PURE__ */ new Set();
23433
23585
  const backgroundedTools = /* @__PURE__ */ new Set();
23434
23586
  let context2;
23435
- const requestedCompaction = { running: false };
23587
+ const requestedCompaction = { trigger: null };
23436
23588
  let rateLimited = false;
23437
23589
  const decide = (approval, decision) => gen(function* () {
23438
23590
  const stage2 = approval.params.currentRequirementId.sourceIndex;
@@ -23626,8 +23778,8 @@ const make$Z = gen(function* () {
23626
23778
  }
23627
23779
  };
23628
23780
  const finishCompaction = (item) => {
23629
- const trigger = requestedCompaction.running || item.trigger !== "manual" ? "auto" : "manual";
23630
- requestedCompaction.running = false;
23781
+ const trigger = requestedCompaction.trigger ?? (item.trigger === "manual" ? "manual" : "auto");
23782
+ requestedCompaction.trigger = null;
23631
23783
  const compaction = item.outcome === "compacted" || item.outcome === "noop" ? {
23632
23784
  status: "done",
23633
23785
  trigger,
@@ -23767,24 +23919,35 @@ const make$Z = gen(function* () {
23767
23919
  run2.sessionId = sessionId;
23768
23920
  yield* emit({ type: "session_bound", providerSessionId: sessionId });
23769
23921
  const { handle, requestedCompaction } = yield* followTurn(input.threadId, run2, entry, sessionId, emit);
23922
+ const compacting = isCompactCommand(input.prompt);
23770
23923
  const loaded = entry.sessions.get(sessionId);
23771
23924
  const usedTokens = loaded?.usedTokens ?? null;
23772
23925
  if (loaded?.compacting) {
23773
- requestedCompaction.running = true;
23926
+ requestedCompaction.trigger = "auto";
23774
23927
  yield* emit({ type: "compaction_updated", compaction: { status: "running" } });
23928
+ } else if (compacting) {
23929
+ const ack = yield* host.command("session/compact", { sessionId }).pipe(mapError(toAgentError));
23930
+ if (ack.status === "accepted") requestedCompaction.trigger = "manual";
23931
+ else {
23932
+ yield* emit({
23933
+ type: "compaction_updated",
23934
+ compaction: { status: "done", trigger: "manual", preTokens: null, postTokens: null }
23935
+ });
23936
+ }
23775
23937
  } else if (input.autoCompactTokens !== null && usedTokens !== null && usedTokens >= input.autoCompactTokens) {
23776
23938
  const ack = yield* host.command("session/compact", { sessionId }).pipe(
23777
23939
  map$3((result2) => result2.status),
23778
23940
  catch_$2((error) => logWarning("session/compact failed", error.message).pipe(as(null)))
23779
23941
  );
23780
- requestedCompaction.running = ack === "accepted";
23942
+ if (ack === "accepted") requestedCompaction.trigger = "auto";
23781
23943
  }
23782
- if (requestedCompaction.running) {
23944
+ if (requestedCompaction.trigger !== null) {
23783
23945
  yield* take(inbox).pipe(
23784
23946
  flatMap$1(handle),
23785
- repeat({ while: () => requestedCompaction.running })
23947
+ repeat({ while: () => requestedCompaction.trigger !== null })
23786
23948
  );
23787
23949
  }
23950
+ if (compacting) return yield* emit({ type: "turn_completed" });
23788
23951
  const prompt = yield* promptParts(host, sessionId, input.prompt, input.attachments, input.instructions);
23789
23952
  run2.turnStart = yield* host.command("turn/start", {
23790
23953
  sessionId,
@@ -23809,6 +23972,18 @@ const make$Z = gen(function* () {
23809
23972
  const stop = succeed$5(run2.stop, void 0);
23810
23973
  return run2.turnId && run2.entry && run2.sessionId ? interruptTurn(run2.entry.host, run2.sessionId, run2.turnId).pipe(catch_$2(() => stop)) : stop;
23811
23974
  }).pipe(asVoid);
23975
+ const closeSession = (threadId) => gen(function* () {
23976
+ const sessionId = threadSessions.get(threadId);
23977
+ if (sessionId === void 0) return;
23978
+ const entry = current;
23979
+ if (entry?.host.isAlive()) yield* leaveSession(entry.host, sessionId);
23980
+ if (entry !== void 0) {
23981
+ setBackgroundTasks(entry, sessionId, []);
23982
+ entry.sessions.delete(sessionId);
23983
+ }
23984
+ threadSessions.delete(threadId);
23985
+ grants.delete(threadId);
23986
+ });
23812
23987
  const steer = (threadId, text2, attachments) => gen(function* () {
23813
23988
  const run2 = runs.get(threadId);
23814
23989
  const { entry, sessionId, turnId } = run2 ?? {};
@@ -23864,6 +24039,7 @@ const make$Z = gen(function* () {
23864
24039
  steer,
23865
24040
  wakes: fromQueue(wakes),
23866
24041
  interrupt: interrupt2,
24042
+ closeSession,
23867
24043
  backgroundTasks: { changes: fromQueue(backgroundTaskChanges), stop: stopBackgroundTask },
23868
24044
  stopSubagent,
23869
24045
  respondApproval,
@@ -24351,6 +24527,11 @@ const threadSnooze = gen(function* () {
24351
24527
  const sql = yield* SqlClient;
24352
24528
  yield* sql`ALTER TABLE thread ADD COLUMN snoozed_until TEXT`;
24353
24529
  });
24530
+ const fork = gen(function* () {
24531
+ const sql = yield* SqlClient;
24532
+ yield* sql`ALTER TABLE thread ADD COLUMN forked_from TEXT`;
24533
+ yield* sql`ALTER TABLE message ADD COLUMN fork_point TEXT`;
24534
+ });
24354
24535
  const archiveSharedChats = gen(function* () {
24355
24536
  const sql = yield* SqlClient;
24356
24537
  yield* sql`
@@ -24384,7 +24565,8 @@ const runMigrations = run({
24384
24565
  "22_environment_relay": environmentRelay,
24385
24566
  "23_environment_source": environmentSource,
24386
24567
  "25_thread_snooze": threadSnooze,
24387
- "24_archive_shared_chats": archiveSharedChats
24568
+ "24_archive_shared_chats": archiveSharedChats,
24569
+ "26_fork": fork
24388
24570
  })
24389
24571
  }).pipe(
24390
24572
  tap$2(
@@ -24421,6 +24603,7 @@ const routes = {
24421
24603
  "browser.close": thread,
24422
24604
  "app.ready": client,
24423
24605
  "app.focus": client,
24606
+ "app.setBadgeCount": client,
24424
24607
  "app.setColorScheme": client,
24425
24608
  "dialog.pickFolder": client,
24426
24609
  "dialog.pickFiles": client,
@@ -24508,6 +24691,7 @@ const routes = {
24508
24691
  "threads.resumeAtReset": owner("thread", "id"),
24509
24692
  "threads.switchAccount": owner("thread", "id"),
24510
24693
  "threads.changes": thread,
24694
+ "threads.fork": thread,
24511
24695
  "threads.archive": thread,
24512
24696
  "threads.unarchive": thread,
24513
24697
  "threads.transcript": thread,
@@ -24873,7 +25057,13 @@ function foldEvent(message, event, now2) {
24873
25057
  };
24874
25058
  }
24875
25059
  case "turn_completed":
24876
- return { ...message, parts: failRunningParts(message.parts), completedAt: now2, usage: event.usage ?? null };
25060
+ return {
25061
+ ...message,
25062
+ parts: failRunningParts(message.parts),
25063
+ completedAt: now2,
25064
+ usage: event.usage ?? null,
25065
+ forkPoint: event.forkPoint ?? null
25066
+ };
24877
25067
  case "turn_failed":
24878
25068
  return {
24879
25069
  ...message,
@@ -24923,6 +25113,112 @@ function appendText(parts2, type, text2) {
24923
25113
  if (last?.type === type) return [...parts2.slice(0, -1), { type, text: last.text + text2 }];
24924
25114
  return [...parts2, { type, text: text2 }];
24925
25115
  }
25116
+ const HANDOFF_TOKENS = 16e3;
25117
+ const TOOL_INPUT_LIMIT = 200;
25118
+ const agentName = { claude: "Claude Code", codex: "Codex", muse: "Muse Code" };
25119
+ const estimateTokens = (text2) => Math.ceil(Buffer.byteLength(text2) / 3);
25120
+ const tail$1 = (text2, tokens) => Buffer.from(text2).subarray(-Math.floor(tokens * 3)).toString().replace(/^\uFFFD+/, "");
25121
+ const head = (text2, tokens) => Buffer.from(text2).subarray(0, Math.floor(tokens * 3)).toString().replace(/\uFFFD+$/, "");
25122
+ const clip = (text2, limit) => text2.length <= limit ? text2 : `${text2.slice(0, limit)}…`;
25123
+ const toolSubject = (input) => {
25124
+ if (typeof input === "object" && input !== null) {
25125
+ for (const key2 of ["command", "file_path", "notebook_path", "pattern", "path", "url", "query", "description"]) {
25126
+ const value2 = Reflect.get(input, key2);
25127
+ if (typeof value2 === "string") return value2;
25128
+ }
25129
+ }
25130
+ return JSON.stringify(input) ?? "";
25131
+ };
25132
+ const renderSaid = (part) => {
25133
+ switch (part.type) {
25134
+ case "text":
25135
+ case "questions":
25136
+ return part.text;
25137
+ case "attachment":
25138
+ return `[attachment ${part.attachment.name} at ${part.attachment.path}]`;
25139
+ case "agent_switch":
25140
+ return `[the conversation moved from ${agentName[part.from]} to ${agentName[part.to]} here]`;
25141
+ default:
25142
+ return null;
25143
+ }
25144
+ };
25145
+ const renderActivity = (part) => {
25146
+ switch (part.type) {
25147
+ case "tool_call":
25148
+ return part.parentCallId === void 0 ? `[tool ${part.name}: ${part.status}] ${clip(toolSubject(part.input), TOOL_INPUT_LIMIT)}` : null;
25149
+ case "file_change":
25150
+ return `[edited ${part.path}]`;
25151
+ case "compaction":
25152
+ return part.compaction.status === "done" ? "[the agent compacted its context here]" : null;
25153
+ default:
25154
+ return null;
25155
+ }
25156
+ };
25157
+ const renderMessage$1 = (message, room) => {
25158
+ const lines = [];
25159
+ let activityTokens = 0;
25160
+ let dropped = 0;
25161
+ for (const part of message.parts.toReversed()) {
25162
+ const said = renderSaid(part);
25163
+ if (said !== null) {
25164
+ lines.unshift(said);
25165
+ continue;
25166
+ }
25167
+ const activity = renderActivity(part);
25168
+ if (activity === null) continue;
25169
+ const tokens = estimateTokens(activity);
25170
+ if (dropped === 0 && activityTokens + tokens <= room) {
25171
+ lines.unshift(activity);
25172
+ activityTokens += tokens;
25173
+ } else dropped++;
25174
+ }
25175
+ if (dropped > 0) lines.unshift(`[${dropped} earlier tool calls and edits left out]`);
25176
+ return lines.length === 0 ? null : { text: [`## ${message.role}`, ...lines].join("\n"), activityTokens };
25177
+ };
25178
+ function handoffPrompt(input) {
25179
+ const budget = input.budget ?? HANDOFF_TOKENS;
25180
+ const opening = input.messages.find((message) => message.role === "user");
25181
+ const openingText = opening === void 0 ? null : renderMessage$1(opening, 0)?.text ?? null;
25182
+ const openingKept = openingText === null || estimateTokens(openingText) <= budget / 8 ? openingText : `${head(openingText, budget / 8)}…`;
25183
+ const kept = [];
25184
+ let used = openingKept === null ? 0 : estimateTokens(openingKept);
25185
+ let activityUsed = 0;
25186
+ let omitted = 0;
25187
+ for (const message of input.messages.toReversed()) {
25188
+ if (message === opening) continue;
25189
+ const rendered = renderMessage$1(message, budget / 4 - activityUsed);
25190
+ if (rendered === null) continue;
25191
+ const tokens = estimateTokens(rendered.text);
25192
+ if (omitted > 0 || used + tokens > budget) {
25193
+ if (kept.length === 0 && omitted === 0) {
25194
+ kept.push(`…${tail$1(rendered.text, budget - used)}`);
25195
+ used = budget;
25196
+ } else omitted++;
25197
+ continue;
25198
+ }
25199
+ kept.unshift(rendered.text);
25200
+ used += tokens;
25201
+ activityUsed += rendered.activityTokens;
25202
+ }
25203
+ const origin = input.from === input.to ? `This conversation ran in an earlier ${agentName[input.to]} session that you cannot resume.` : `This conversation started with ${agentName[input.from]} and continues with you. Tool names below are ${agentName[input.from]}'s and may differ from yours.`;
25204
+ const transcript = [
25205
+ ...openingKept === null ? [] : [openingKept],
25206
+ ...omitted > 0 ? [`[${omitted} messages left out here to fit]`] : [],
25207
+ ...kept
25208
+ ];
25209
+ return [
25210
+ "<conversation_handoff>",
25211
+ [
25212
+ origin,
25213
+ "Here is the transcript so far, oldest first. It is context, not a new request. Tool output is left out, so read files again before you rely on them."
25214
+ ].join(" "),
25215
+ "",
25216
+ transcript.join("\n\n"),
25217
+ "</conversation_handoff>",
25218
+ "",
25219
+ input.prompt
25220
+ ].join("\n");
25221
+ }
24926
25222
  const threadMention = (threadId) => `@thread:${threadId}`;
24927
25223
  const AGENT_INSTRUCTIONS = `<hinacode>
24928
25224
  You are running inside HinaCode, which shows the pull requests linked to each thread next to it.
@@ -25181,7 +25477,8 @@ const layer$B = effect(Git, make$U);
25181
25477
  const MessageRow = Struct({
25182
25478
  ...Message.fields,
25183
25479
  parts: fromJsonString(ArraySchema(MessagePart)),
25184
- usage: NullOr(fromJsonString(TokenUsage))
25480
+ usage: NullOr(fromJsonString(TokenUsage)),
25481
+ forkPoint: NullOr(fromJsonString(ForkPoint))
25185
25482
  });
25186
25483
  class Messages extends Service$1()("hinacode/Messages") {
25187
25484
  }
@@ -25210,7 +25507,8 @@ const make$T = gen(function* () {
25210
25507
  const update2 = (message) => encodeRow(message).pipe(
25211
25508
  flatMap$1(
25212
25509
  (row) => sql`
25213
- UPDATE message SET parts = ${row.parts}, completed_at = ${row.completedAt}, usage = ${row.usage}
25510
+ UPDATE message
25511
+ SET parts = ${row.parts}, completed_at = ${row.completedAt}, usage = ${row.usage}, fork_point = ${row.forkPoint}
25214
25512
  WHERE id = ${row.id}
25215
25513
  `
25216
25514
  ),
@@ -25470,6 +25768,18 @@ class GitHubSignedOutError extends TaggedError()("GitHubSignedOutError", {}) {
25470
25768
  return "gh is not signed in. Run gh auth login in a terminal.";
25471
25769
  }
25472
25770
  }
25771
+ class GitHubRateLimitedError extends TaggedError()("GitHubRateLimitedError", {
25772
+ resetsAt: Number$1
25773
+ }) {
25774
+ get message() {
25775
+ return `GitHub's API rate limit is used up. HinaCode asks again after ${new Date(this.resetsAt).toISOString()}.`;
25776
+ }
25777
+ }
25778
+ class GitHubApiError extends TaggedError()("GitHubApiError", { detail: String$1 }) {
25779
+ get message() {
25780
+ return this.detail;
25781
+ }
25782
+ }
25473
25783
  class PullRequestUrlInvalidError extends TaggedError()(
25474
25784
  "PullRequestUrlInvalidError",
25475
25785
  { url: String$1 }
@@ -25532,15 +25842,91 @@ const PullRequestFields = Struct({
25532
25842
  deletions: Number$1
25533
25843
  });
25534
25844
  const PullRequestJson = fromJsonString(PullRequestFields);
25535
- const PULL_REQUEST_DETAIL_FIELDS = `${PULL_REQUEST_FIELDS},body,headRefOid,changedFiles`;
25536
- const PullRequestDetailJson = fromJsonString(
25845
+ const PullRequestDetailFields = Struct({
25846
+ ...PullRequestFields.fields,
25847
+ body: String$1,
25848
+ headRefOid: String$1,
25849
+ changedFiles: Number$1
25850
+ });
25851
+ const PULL_REQUEST_QUERY = `query PullRequest($owner: String!, $name: String!, $number: Int!) {
25852
+ repository(owner: $owner, name: $name) {
25853
+ pullRequest(number: $number) {
25854
+ url number title state isDraft reviewDecision mergeable
25855
+ author { login }
25856
+ headRefName baseRefName headRefOid additions deletions changedFiles body
25857
+ commits(last: 1) { nodes { commit { statusCheckRollup { contexts(first: 100) { nodes {
25858
+ ... on CheckRun { __typename name status conclusion detailsUrl checkSuite { workflowRun { workflow { name } } } }
25859
+ ... on StatusContext { __typename context state targetUrl }
25860
+ } } } } } }
25861
+ }
25862
+ }
25863
+ }`;
25864
+ const GraphQLCheck = Union2([
25865
+ Struct({
25866
+ __typename: Literal2("CheckRun"),
25867
+ name: String$1,
25868
+ status: String$1,
25869
+ conclusion: NullOr(String$1),
25870
+ detailsUrl: NullOr(String$1),
25871
+ checkSuite: NullOr(
25872
+ Struct({
25873
+ workflowRun: NullOr(Struct({ workflow: Struct({ name: String$1 }) }))
25874
+ })
25875
+ )
25876
+ }),
25537
25877
  Struct({
25538
- ...PullRequestFields.fields,
25539
- body: String$1,
25540
- headRefOid: String$1,
25541
- changedFiles: Number$1
25878
+ __typename: Literal2("StatusContext"),
25879
+ context: String$1,
25880
+ state: String$1,
25881
+ targetUrl: NullOr(String$1)
25882
+ })
25883
+ ]);
25884
+ const GraphQLPullRequest = Struct({
25885
+ ...PullRequestDetailFields.mapFields(omit(["reviewDecision", "author", "statusCheckRollup"])).fields,
25886
+ reviewDecision: NullOr(String$1),
25887
+ // Null for a deleted account, which GitHub shows as ghost.
25888
+ author: NullOr(Struct({ login: String$1 })),
25889
+ commits: Struct({
25890
+ nodes: ArraySchema(
25891
+ Struct({
25892
+ commit: Struct({
25893
+ statusCheckRollup: NullOr(
25894
+ Struct({ contexts: Struct({ nodes: ArraySchema(GraphQLCheck) }) })
25895
+ )
25896
+ })
25897
+ })
25898
+ )
25542
25899
  })
25900
+ });
25901
+ const decodePullRequestResponse = decodeUnknownEffect(
25902
+ fromJsonString(
25903
+ Struct({ data: Struct({ repository: Struct({ pullRequest: GraphQLPullRequest }) }) })
25904
+ )
25543
25905
  );
25906
+ const toRollupEntry = (check) => {
25907
+ if (check.__typename === "StatusContext") {
25908
+ return { context: check.context, state: check.state, ...check.targetUrl ? { targetUrl: check.targetUrl } : {} };
25909
+ }
25910
+ const workflowName = check.checkSuite?.workflowRun?.workflow.name;
25911
+ return {
25912
+ name: check.name,
25913
+ status: check.status,
25914
+ ...check.conclusion ? { conclusion: check.conclusion } : {},
25915
+ ...workflowName ? { workflowName } : {},
25916
+ ...check.detailsUrl ? { detailsUrl: check.detailsUrl } : {}
25917
+ };
25918
+ };
25919
+ const fromGraphQL = ({
25920
+ commits,
25921
+ reviewDecision,
25922
+ author,
25923
+ ...fields
25924
+ }) => ({
25925
+ ...fields,
25926
+ reviewDecision: reviewDecision ?? "",
25927
+ author: author ?? { login: "ghost" },
25928
+ statusCheckRollup: (commits.nodes[0]?.commit.statusCheckRollup?.contexts.nodes ?? []).map(toRollupEntry)
25929
+ });
25544
25930
  const FAILED = /* @__PURE__ */ new Set(["FAILURE", "ERROR", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE"]);
25545
25931
  const checkOutcome = (entry) => {
25546
25932
  if (entry.status !== void 0 && entry.status !== "COMPLETED") return "pending";
@@ -25617,9 +26003,57 @@ const pullRequestFiles = (diff) => forEach$1(
25617
26003
  )
25618
26004
  )
25619
26005
  ).pipe(map$3((files) => files.flat()));
26006
+ const RateLimitBucket = Struct({
26007
+ limit: Number$1,
26008
+ remaining: Number$1,
26009
+ used: Number$1,
26010
+ reset: Number$1
26011
+ });
26012
+ const decodeRateLimit = decodeUnknownEffect(
26013
+ fromJsonString(
26014
+ Struct({ resources: Struct({ core: RateLimitBucket, graphql: RateLimitBucket }) })
26015
+ )
26016
+ );
26017
+ const fromBucket = (resource, { limit, remaining, used, reset }) => ({
26018
+ resource,
26019
+ limit,
26020
+ remaining,
26021
+ used,
26022
+ resetsAt: reset * 1e3
26023
+ });
26024
+ const parseApiResponse = (stdout) => {
26025
+ const blank = /\r?\n\r?\n/.exec(stdout);
26026
+ const head2 = blank ? stdout.slice(0, blank.index) : stdout;
26027
+ const [statusLine = "", ...lines] = head2.split(/\r?\n/);
26028
+ const headers = new Map(
26029
+ lines.map((line) => {
26030
+ const colon = line.indexOf(":");
26031
+ return [line.slice(0, colon).trim().toLowerCase(), line.slice(colon + 1).trim()];
26032
+ })
26033
+ );
26034
+ return {
26035
+ status: Number(statusLine.split(" ")[1]),
26036
+ headers,
26037
+ body: blank ? stdout.slice(blank.index + blank[0].length) : ""
26038
+ };
26039
+ };
26040
+ const rateLimitOf = (headers) => {
26041
+ const header2 = (name) => Number(headers.get(`x-ratelimit-${name}`) ?? Number.NaN);
26042
+ const [limit, remaining, used, reset] = [header2("limit"), header2("remaining"), header2("used"), header2("reset")];
26043
+ if (![limit, remaining, used, reset].every(Number.isFinite)) return null;
26044
+ return { resource: headers.get("x-ratelimit-resource") ?? "", limit, remaining, used, resetsAt: reset * 1e3 };
26045
+ };
26046
+ const LOW_BUDGET_SHARE = 0.2;
26047
+ const budgetLevel = ({ limit, remaining }) => remaining === 0 ? "exhausted" : remaining < limit * LOW_BUDGET_SHARE ? "low" : "ok";
26048
+ const ApiErrorBody = Struct({
26049
+ message: optionalKey(String$1),
26050
+ errors: optionalKey(
26051
+ ArraySchema(Struct({ type: optionalKey(String$1), message: String$1 }))
26052
+ )
26053
+ });
26054
+ const decodeApiErrorBody = decodeUnknownOption(fromJsonString(ApiErrorBody));
25620
26055
  const decodeAuthStatus = decodeUnknownEffect(AuthStatusJson);
25621
26056
  const decodePullRequest = decodeUnknownEffect(PullRequestJson);
25622
- const decodePullRequestDetail = decodeUnknownEffect(PullRequestDetailJson);
25623
26057
  const PullRequestHead = Struct({
25624
26058
  url: String$1,
25625
26059
  number: Int,
@@ -25657,15 +26091,106 @@ const decodePullRequestMatches = decodeUnknownEffect(
25657
26091
  class GitHub extends Service$1()("hinacode/GitHub") {
25658
26092
  }
25659
26093
  const SIGNED_OUT_EXIT_CODE = 4;
26094
+ const RATE_LIMITED = /rate limit/i;
26095
+ const SECONDARY_PAUSE_MS = 6e4;
26096
+ const MAX_SECONDARY_PAUSE_MS = 15 * 6e4;
26097
+ const OPEN_PULL_REQUEST_TTL = "30 seconds";
26098
+ const LOW_BUDGET_PULL_REQUEST_TTL = "5 minutes";
26099
+ const FINISHED_PULL_REQUEST_TTL = "10 minutes";
25660
26100
  const make$S = gen(function* () {
25661
26101
  const exec2 = makeExec(yield* ChildProcessSpawner);
25662
- const gh = (cwd, args2) => exec2("gh", args2, cwd, { env: { GH_PROMPT_DISABLED: "1", NO_COLOR: "1" } }).pipe(
26102
+ const events = yield* Events;
26103
+ const ghUnpaused = (cwd, args2, options) => exec2("gh", args2, cwd, { ...options, env: { GH_PROMPT_DISABLED: "1", NO_COLOR: "1" } }).pipe(
25663
26104
  mapError((error) => {
25664
26105
  if (error.exitCode === -1) return new GitHubCliMissingError();
25665
26106
  if (error.exitCode === SIGNED_OUT_EXIT_CODE) return new GitHubSignedOutError();
25666
26107
  return error;
25667
26108
  })
25668
26109
  );
26110
+ let pausedUntil = 0;
26111
+ let secondaryHits = 0;
26112
+ let graphqlBudget = "ok";
26113
+ let warned = null;
26114
+ const pausing = makeUnsafe$4(1);
26115
+ const pauseFor = (now2, retryAfterSeconds) => {
26116
+ if (retryAfterSeconds !== void 0) {
26117
+ pausedUntil = Math.max(pausedUntil, now2 + retryAfterSeconds * 1e3);
26118
+ } else {
26119
+ pausedUntil = Math.max(
26120
+ pausedUntil,
26121
+ now2 + Math.min(SECONDARY_PAUSE_MS * 2 ** secondaryHits, MAX_SECONDARY_PAUSE_MS)
26122
+ );
26123
+ secondaryHits += 1;
26124
+ }
26125
+ return pausedUntil;
26126
+ };
26127
+ const observe = (rateLimit) => gen(function* () {
26128
+ const level = budgetLevel(rateLimit);
26129
+ if (rateLimit.resource === "graphql") graphqlBudget = level;
26130
+ if (level === "exhausted") pausedUntil = Math.max(pausedUntil, rateLimit.resetsAt);
26131
+ if (level === "ok") return;
26132
+ const now2 = yield* currentTimeMillis;
26133
+ const repeat2 = warned !== null && now2 < warned.until && (warned.level === level || level === "low");
26134
+ if (repeat2) return;
26135
+ warned = { level, until: rateLimit.resetsAt };
26136
+ yield* events.publish({ type: "github.rateLimit", level, rateLimit });
26137
+ });
26138
+ const pause = withPermit(
26139
+ pausing,
26140
+ gen(function* () {
26141
+ const now2 = yield* currentTimeMillis;
26142
+ if (now2 < pausedUntil) return pausedUntil;
26143
+ const limits = yield* ghUnpaused(homedir(), ["api", "rate_limit"]).pipe(
26144
+ flatMap$1(decodeRateLimit),
26145
+ option
26146
+ );
26147
+ if (limits._tag === "Some") {
26148
+ yield* observe(fromBucket("core", limits.value.resources.core));
26149
+ yield* observe(fromBucket("graphql", limits.value.resources.graphql));
26150
+ }
26151
+ return now2 < pausedUntil ? pausedUntil : pauseFor(now2);
26152
+ })
26153
+ );
26154
+ const failIfPaused = flatMap$1(
26155
+ currentTimeMillis,
26156
+ (now2) => now2 < pausedUntil ? fail$2(new GitHubRateLimitedError({ resetsAt: pausedUntil })) : void_$1
26157
+ );
26158
+ const gh = (cwd, args2) => gen(function* () {
26159
+ yield* failIfPaused;
26160
+ const stdout = yield* ghUnpaused(cwd, args2).pipe(
26161
+ catchIf(
26162
+ (error) => error._tag === "CommandError" && RATE_LIMITED.test(error.stderr),
26163
+ () => flatMap$1(pause, (resetsAt) => fail$2(new GitHubRateLimitedError({ resetsAt })))
26164
+ )
26165
+ );
26166
+ secondaryHits = 0;
26167
+ return stdout;
26168
+ });
26169
+ const ghApi = (args2) => gen(function* () {
26170
+ yield* failIfPaused;
26171
+ const response = parseApiResponse(
26172
+ yield* ghUnpaused(homedir(), ["api", ...args2, "--include"], { okExitCodes: [1] })
26173
+ );
26174
+ const rateLimit = rateLimitOf(response.headers);
26175
+ if (rateLimit !== null) yield* observe(rateLimit);
26176
+ const error = decodeApiErrorBody(response.body);
26177
+ const errors2 = error._tag === "Some" ? error.value.errors ?? [] : [];
26178
+ const message = error._tag === "Some" ? error.value.message ?? "" : "";
26179
+ const limited = response.status === 429 || response.status === 403 && (rateLimit?.remaining === 0 || RATE_LIMITED.test(message)) || errors2.some((entry) => entry.type === "RATE_LIMITED");
26180
+ if (limited) {
26181
+ const retryAfter = Number(response.headers.get("retry-after") ?? Number.NaN);
26182
+ const now2 = yield* currentTimeMillis;
26183
+ const resetsAt = now2 < pausedUntil ? pausedUntil : pauseFor(now2, Number.isFinite(retryAfter) ? retryAfter : void 0);
26184
+ return yield* new GitHubRateLimitedError({ resetsAt });
26185
+ }
26186
+ if (response.status >= 400 || errors2.length > 0) {
26187
+ return yield* new GitHubApiError({
26188
+ detail: errors2.map((entry) => entry.message).join("\n") || message || `HTTP ${response.status}`
26189
+ });
26190
+ }
26191
+ secondaryHits = 0;
26192
+ return response.body;
26193
+ });
25669
26194
  const auth = gh(homedir(), ["auth", "status", "--json", "hosts"]).pipe(
25670
26195
  flatMap$1(decodeAuthStatus),
25671
26196
  map$3(parseAuthStatus),
@@ -25684,39 +26209,82 @@ const make$S = gen(function* () {
25684
26209
  () => succeed$3(null)
25685
26210
  )
25686
26211
  );
25687
- const createPullRequest = (cwd, { head, base }) => gh(cwd, ["pr", "create", "--head", head, "--base", base, "--fill"]).pipe(
26212
+ const createPullRequest = (cwd, { head: head2, base }) => gh(cwd, ["pr", "create", "--head", head2, "--base", base, "--fill"]).pipe(
25688
26213
  map$3((stdout) => stdout.trim().split("\n").at(-1) ?? "")
25689
26214
  );
25690
26215
  const clone2 = ({ owner: owner2, name }, dest) => {
25691
26216
  const url = `https://github.com/${owner2}/${name}.git`;
25692
26217
  const gitClone = () => exec2("git", [...REMOTE_GIT_ARGS, "clone", url, dest], dirname(dest), { env: REMOTE_GIT_ENV });
25693
26218
  return gh(dirname(dest), ["repo", "clone", url, dest]).pipe(
25694
- catchTags({ GitHubCliMissingError: gitClone, GitHubSignedOutError: gitClone }),
26219
+ catchTags({
26220
+ GitHubCliMissingError: gitClone,
26221
+ GitHubSignedOutError: gitClone,
26222
+ GitHubRateLimitedError: gitClone
26223
+ }),
25695
26224
  asVoid
25696
26225
  );
25697
26226
  };
25698
26227
  const ghByUrl = (raw2, args2) => flatMap$1(requirePullRequestUrl(raw2), (url) => gh(homedir(), args2(url)));
26228
+ const lastRead = /* @__PURE__ */ new Map();
26229
+ const fetchPullRequest = (url) => {
26230
+ const [owner2 = "", name = "", , number2 = ""] = new URL(url).pathname.slice(1).split("/");
26231
+ return ghApi([
26232
+ "graphql",
26233
+ "-f",
26234
+ `query=${PULL_REQUEST_QUERY}`,
26235
+ "-f",
26236
+ `owner=${owner2}`,
26237
+ "-f",
26238
+ `name=${name}`,
26239
+ "-F",
26240
+ `number=${number2}`
26241
+ ]).pipe(
26242
+ flatMap$1(decodePullRequestResponse),
26243
+ map$3(({ data }) => fromGraphQL(data.repository.pullRequest))
26244
+ );
26245
+ };
26246
+ const reads = yield* makeWith(
26247
+ (url) => fetchPullRequest(url).pipe(
26248
+ tap$2((json2) => sync(() => lastRead.set(url, json2))),
26249
+ catchTag("GitHubRateLimitedError", (error) => {
26250
+ const last = lastRead.get(url);
26251
+ return last === void 0 ? fail$2(error) : succeed$3(last);
26252
+ })
26253
+ ),
26254
+ {
26255
+ capacity: 1e3,
26256
+ timeToLive: (exit2) => {
26257
+ if (isFailure(exit2)) return 0;
26258
+ if (exit2.value.state !== "OPEN") return FINISHED_PULL_REQUEST_TTL;
26259
+ return graphqlBudget === "ok" ? OPEN_PULL_REQUEST_TTL : LOW_BUDGET_PULL_REQUEST_TTL;
26260
+ }
26261
+ }
26262
+ );
26263
+ const read2 = (raw2) => flatMap$1(requirePullRequestUrl(raw2), (url) => get$5(reads, url));
26264
+ const ghWrite = (raw2, args2) => flatMap$1(
26265
+ requirePullRequestUrl(raw2),
26266
+ (url) => gh(homedir(), args2(url)).pipe(andThen(invalidate(reads, url)), asVoid)
26267
+ );
25699
26268
  const repository = (cwd) => exec2("git", ["-C", cwd, "remote", "get-url", "origin"], cwd).pipe(
25700
26269
  map$3(parseGitHubRepository),
25701
26270
  orElseSucceed(() => null)
25702
26271
  );
25703
26272
  return GitHub.of({
25704
26273
  auth,
25705
- token: gh(homedir(), ["auth", "token", "--hostname", "github.com"]).pipe(map$3((stdout) => stdout.trim())),
25706
- run: gh,
25707
- pullRequest: (raw2) => flatMap$1(requirePullRequestUrl(raw2), (url) => view(homedir(), url)),
25708
- pullRequestDetail: (raw2) => ghByUrl(raw2, (url) => ["pr", "view", url, "--json", PULL_REQUEST_DETAIL_FIELDS]).pipe(
25709
- flatMap$1(decodePullRequestDetail),
25710
- map$3(toPullRequestDetail)
26274
+ token: ghUnpaused(homedir(), ["auth", "token", "--hostname", "github.com"]).pipe(
26275
+ map$3((stdout) => stdout.trim())
25711
26276
  ),
26277
+ run: gh,
26278
+ pullRequest: (raw2) => map$3(read2(raw2), toPullRequest),
26279
+ pullRequestDetail: (raw2) => map$3(read2(raw2), toPullRequestDetail),
25712
26280
  pullRequestDiff: (raw2) => ghByUrl(raw2, (url) => ["pr", "diff", url, "--color=never"]).pipe(
25713
26281
  catchIf(
25714
26282
  (error) => error._tag === "CommandError" && error.stderr.includes("too_large"),
25715
26283
  () => fail$2(new PullRequestDiffTooLargeError())
25716
26284
  )
25717
26285
  ),
25718
- merge: (raw2, method) => ghByUrl(raw2, (url) => ["pr", "merge", url, `--${method}`]).pipe(asVoid),
25719
- close: (raw2) => ghByUrl(raw2, (url) => ["pr", "close", url]).pipe(asVoid),
26286
+ merge: (raw2, method) => ghWrite(raw2, (url) => ["pr", "merge", url, `--${method}`]),
26287
+ close: (raw2) => ghWrite(raw2, (url) => ["pr", "close", url]),
25720
26288
  branchPullRequest,
25721
26289
  pullRequestHead: (cwd, selector) => gh(cwd, ["pr", "view", selector, "--json", "url,number,headRefName,baseRefName,isCrossRepository"]).pipe(
25722
26290
  flatMap$1(decodePullRequestHead)
@@ -26324,15 +26892,15 @@ Setup script exited with code ${exitCode}
26324
26892
  setups.set(worktree.id, yield* forkDetach(setup2(worktree, project2)));
26325
26893
  return worktree;
26326
26894
  }).pipe(exclusive);
26327
- const fetchPullRequest = (rootPath, head) => gen(function* () {
26328
- const [branch, source, fetched] = head.isCrossRepository ? [forkPullRequestBranch(head.number), `refs/pull/${head.number}/head`, `refs/hinacode/pull/${head.number}`] : [head.headRefName, `refs/heads/${head.headRefName}`, `refs/remotes/origin/${head.headRefName}`];
26895
+ const fetchPullRequest = (rootPath, head2) => gen(function* () {
26896
+ const [branch, source, fetched] = head2.isCrossRepository ? [forkPullRequestBranch(head2.number), `refs/pull/${head2.number}/head`, `refs/hinacode/pull/${head2.number}`] : [head2.headRefName, `refs/heads/${head2.headRefName}`, `refs/remotes/origin/${head2.headRefName}`];
26329
26897
  yield* git2.remote(rootPath, ["fetch", "--quiet", "origin", `+${source}:${fetched}`]);
26330
26898
  return { branch, startPoint: fetched };
26331
26899
  });
26332
- const createFromPullRequest = (projectId, head) => gen(function* () {
26900
+ const createFromPullRequest = (projectId, head2) => gen(function* () {
26333
26901
  const { rootPath } = yield* projects.get(projectId);
26334
- const { branch, startPoint } = yield* fetchPullRequest(rootPath, head);
26335
- return yield* create({ projectId, branch, baseRef: head.baseRefName, startPoint });
26902
+ const { branch, startPoint } = yield* fetchPullRequest(rootPath, head2);
26903
+ return yield* create({ projectId, branch, baseRef: head2.baseRefName, startPoint });
26336
26904
  });
26337
26905
  const switchRoot = (projectId, rootPath, owner2, args2) => gen(function* () {
26338
26906
  const users = yield* findRootUsers(projectId).pipe(mapError(persistence("worktrees.checkout")));
@@ -26346,9 +26914,9 @@ Setup script exited with code ${exitCode}
26346
26914
  const remote = ref.startsWith("origin/") && (yield* git2.run(rootPath, ["rev-parse", "--verify", "--quiet", `refs/remotes/${ref}`], { okExitCodes: [1] }).pipe(map$3((output) => output.trim() !== "")));
26347
26915
  yield* switchRoot(projectId, rootPath, owner2, remote ? ["--track", ref] : [ref]);
26348
26916
  });
26349
- const checkoutPullRequest = (projectId, head, owner2) => gen(function* () {
26917
+ const checkoutPullRequest = (projectId, head2, owner2) => gen(function* () {
26350
26918
  const { rootPath } = yield* projects.get(projectId);
26351
- const { branch, startPoint } = yield* fetchPullRequest(rootPath, head);
26919
+ const { branch, startPoint } = yield* fetchPullRequest(rootPath, head2);
26352
26920
  const args2 = (yield* branchExists(rootPath, branch)) ? [branch] : ["-c", branch, startPoint];
26353
26921
  yield* switchRoot(projectId, rootPath, owner2, args2);
26354
26922
  });
@@ -26374,8 +26942,8 @@ Setup script exited with code ${exitCode}
26374
26942
  const mergedOnGitHub = (rootPath, branch) => gen(function* () {
26375
26943
  const pullRequest2 = yield* github.branchPullRequest(rootPath, branch);
26376
26944
  if (pullRequest2?.status !== "merged") return false;
26377
- const { head } = yield* github.pullRequestDetail(pullRequest2.url);
26378
- yield* git2.run(rootPath, ["merge-base", "--is-ancestor", `refs/heads/${branch}`, head]);
26945
+ const { head: head2 } = yield* github.pullRequestDetail(pullRequest2.url);
26946
+ yield* git2.run(rootPath, ["merge-base", "--is-ancestor", `refs/heads/${branch}`, head2]);
26379
26947
  return true;
26380
26948
  }).pipe(orElseSucceed(() => false));
26381
26949
  const deleteIfMerged = (rootPath, worktree) => gen(function* () {
@@ -26522,6 +27090,7 @@ const ThreadRow$1 = Struct({
26522
27090
  fastMode: BooleanFromBit,
26523
27091
  userSkills: BooleanFromBit,
26524
27092
  usageLimit: NullOr(fromJsonString(UsageLimit)),
27093
+ forkedFrom: NullOr(fromJsonString(ForkPoint)),
26525
27094
  queue: fromJsonString(ArraySchema(QueuedMessage))
26526
27095
  });
26527
27096
  const arranging = /* @__PURE__ */ new Set(["id", "sortIndex", "pinned", "snoozedUntil"]);
@@ -26556,6 +27125,11 @@ const make$O = gen(function* () {
26556
27125
  Result: Struct({ next: Number$1 }),
26557
27126
  execute: (projectId) => sql`SELECT COALESCE(MAX(sort_index) + 1, 0) AS next FROM thread WHERE project_id = ${projectId}`
26558
27127
  });
27128
+ const findForkPoint = findOneOption({
27129
+ Request: Struct({ threadId: String$1, messageId: String$1 }),
27130
+ Result: Struct({ forkPoint: fromJsonString(ForkPoint) }),
27131
+ execute: ({ threadId, messageId }) => sql`SELECT fork_point FROM message WHERE id = ${messageId} AND thread_id = ${threadId} AND fork_point IS NOT NULL`
27132
+ });
26559
27133
  const findTurnBase = findOneOption({
26560
27134
  Request: String$1,
26561
27135
  Result: Struct({ turnBaseTree: NullOr(String$1) }),
@@ -26607,6 +27181,7 @@ const make$O = gen(function* () {
26607
27181
  accessMode: defaultAccessMode,
26608
27182
  accountId: defaultAccount[input.provider],
26609
27183
  providerSessionId: null,
27184
+ forkedFrom: null,
26610
27185
  status: "idle",
26611
27186
  usageLimit: null,
26612
27187
  sortIndex: next,
@@ -26622,18 +27197,64 @@ const make$O = gen(function* () {
26622
27197
  yield* syncChatFolder(thread2, true);
26623
27198
  return thread2;
26624
27199
  });
27200
+ const fork2 = (threadId, messageId) => gen(function* () {
27201
+ const source = yield* get2(threadId);
27202
+ const found2 = yield* findForkPoint({ threadId, messageId }).pipe(mapError(persistence("threads.fork")));
27203
+ if (isNone(found2)) return yield* new NotFoundError({ entity: "fork point", id: messageId });
27204
+ const { owner: owner2, ...forkedFrom } = found2.value.forkPoint;
27205
+ const { provider, accountId } = owner2 ?? source;
27206
+ if (provider !== source.provider) return yield* new NotFoundError({ entity: "fork point", id: messageId });
27207
+ if (accountId !== null) yield* accounts.get(accountId);
27208
+ const { next } = yield* nextSortIndex(source.projectId).pipe(mapError(persistence("threads.fork")));
27209
+ const now2 = yield* nowIso;
27210
+ const thread2 = {
27211
+ ...source,
27212
+ id: randomUUID(),
27213
+ title: `${source.title} (fork)`,
27214
+ accountId,
27215
+ providerSessionId: null,
27216
+ forkedFrom,
27217
+ status: "idle",
27218
+ usageLimit: null,
27219
+ sortIndex: next,
27220
+ pinnedAt: null,
27221
+ snoozedUntil: null,
27222
+ queue: [],
27223
+ createdBy: "user",
27224
+ createdAt: now2,
27225
+ updatedAt: now2
27226
+ };
27227
+ const row = yield* encodeRow(thread2).pipe(mapError(persistence("threads.fork")));
27228
+ yield* sql.withTransaction(
27229
+ gen(function* () {
27230
+ yield* sql`INSERT INTO thread ${sql.insert(row)}`;
27231
+ yield* sql`
27232
+ INSERT INTO message (id, thread_id, role, parts, created_at, completed_at, usage, fork_point)
27233
+ SELECT lower(hex(randomblob(16))), ${thread2.id}, role, parts, created_at, completed_at, usage, fork_point
27234
+ FROM message
27235
+ WHERE thread_id = ${threadId}
27236
+ AND (created_at, rowid) <= (SELECT created_at, rowid FROM message WHERE id = ${messageId})
27237
+ ORDER BY created_at, rowid
27238
+ `;
27239
+ })
27240
+ ).pipe(mapError(persistence("threads.fork")));
27241
+ yield* syncChatFolder(thread2, true);
27242
+ return thread2;
27243
+ });
26625
27244
  const update2 = (input) => gen(function* () {
26626
27245
  const current = yield* get2(input.id);
26627
27246
  const switchesAgent = input.provider !== void 0 && input.provider !== current.provider;
26628
- if (switchesAgent && (yield* started(input.id))) {
26629
- return yield* new ThreadStartedError({ id: input.id });
26630
- }
26631
27247
  const provider = input.provider ?? current.provider;
26632
27248
  const accountId = input.accountId !== void 0 ? input.accountId : switchesAgent ? (yield* settings.get).defaultAccount[provider] : current.accountId;
26633
27249
  if (accountId !== current.accountId && accountId !== null && (yield* accounts.get(accountId)).provider !== provider) {
26634
27250
  return yield* new NotFoundError({ entity: "account", id: accountId });
26635
27251
  }
26636
- return yield* write(current, { ...input, accountId: accountId === current.accountId ? void 0 : accountId });
27252
+ return yield* write(current, {
27253
+ ...input,
27254
+ accountId: accountId === current.accountId ? void 0 : accountId,
27255
+ // The usage limit belonged to the agent the thread leaves.
27256
+ ...switchesAgent && current.status === "limited" && { status: "idle" }
27257
+ });
26637
27258
  });
26638
27259
  const write = (current, input) => gen(function* () {
26639
27260
  const now2 = yield* nowIso;
@@ -26653,7 +27274,9 @@ const make$O = gen(function* () {
26653
27274
  sortIndex: input.sortIndex ?? current.sortIndex,
26654
27275
  pinnedAt: input.pinned === void 0 ? current.pinnedAt : input.pinned ? current.pinnedAt ?? now2 : null,
26655
27276
  snoozedUntil: input.snoozedUntil !== void 0 ? input.snoozedUntil : arranges ? current.snoozedUntil : null,
26656
- providerSessionId: input.providerSessionId ?? current.providerSessionId,
27277
+ // A session id belongs to one agent.
27278
+ providerSessionId: input.provider !== void 0 && input.provider !== current.provider ? null : input.providerSessionId ?? current.providerSessionId,
27279
+ forkedFrom: input.providerSessionId !== void 0 || (input.provider ?? current.provider) !== current.provider ? null : current.forkedFrom,
26657
27280
  queue: input.queue ?? current.queue,
26658
27281
  updatedAt: arranges ? current.updatedAt : now2
26659
27282
  };
@@ -26664,6 +27287,7 @@ const make$O = gen(function* () {
26664
27287
  access_mode = ${next.accessMode}, status = ${next.status},
26665
27288
  sort_index = ${next.sortIndex}, pinned_at = ${next.pinnedAt}, snoozed_until = ${next.snoozedUntil},
26666
27289
  provider_session_id = ${next.providerSessionId},
27290
+ forked_from = ${next.forkedFrom === null ? null : JSON.stringify(next.forkedFrom)},
26667
27291
  updated_at = ${next.updatedAt}, usage_limit = ${next.usageLimit === null ? null : JSON.stringify(next.usageLimit)},
26668
27292
  queue = ${JSON.stringify(next.queue)}
26669
27293
  WHERE id = ${next.id}
@@ -26672,19 +27296,19 @@ const make$O = gen(function* () {
26672
27296
  });
26673
27297
  const resolvePullRequest = (projectId, selector) => gen(function* () {
26674
27298
  const { rootPath } = yield* projects.get(projectId);
26675
- const head = yield* github.pullRequestHead(rootPath, selector);
27299
+ const head2 = yield* github.pullRequestHead(rootPath, selector);
26676
27300
  const origin = yield* github.repository(rootPath);
26677
- const target = parseGitHubRepository(head.url);
27301
+ const target = parseGitHubRepository(head2.url);
26678
27302
  if (origin && target && `${origin.owner}/${origin.name}`.toLowerCase() !== `${target.owner}/${target.name}`.toLowerCase()) {
26679
- return yield* new PullRequestElsewhereError({ url: head.url, repository: `${origin.owner}/${origin.name}` });
27303
+ return yield* new PullRequestElsewhereError({ url: head2.url, repository: `${origin.owner}/${origin.name}` });
26680
27304
  }
26681
- return head;
27305
+ return head2;
26682
27306
  });
26683
27307
  const checkoutRoot = (thread2, target) => gen(function* () {
26684
27308
  if (target._tag === "pullRequest") {
26685
- const head = yield* resolvePullRequest(thread2.projectId, target.selector);
26686
- yield* worktrees.checkoutPullRequest(thread2.projectId, head, thread2.id);
26687
- return { thread: thread2, pullRequestUrl: head.url };
27309
+ const head2 = yield* resolvePullRequest(thread2.projectId, target.selector);
27310
+ yield* worktrees.checkoutPullRequest(thread2.projectId, head2, thread2.id);
27311
+ return { thread: thread2, pullRequestUrl: head2.url };
26688
27312
  }
26689
27313
  const ref = target.ref.trim();
26690
27314
  if (ref !== "" && ref !== (yield* worktrees.currentBranch(thread2.projectId))) {
@@ -26693,8 +27317,8 @@ const make$O = gen(function* () {
26693
27317
  return { thread: thread2, pullRequestUrl: null };
26694
27318
  });
26695
27319
  const pullRequestWorktree = (projectId, selector) => gen(function* () {
26696
- const head = yield* resolvePullRequest(projectId, selector);
26697
- return { worktree: yield* worktrees.createFromPullRequest(projectId, head), pullRequestUrl: head.url };
27320
+ const head2 = yield* resolvePullRequest(projectId, selector);
27321
+ return { worktree: yield* worktrees.createFromPullRequest(projectId, head2), pullRequestUrl: head2.url };
26698
27322
  });
26699
27323
  const attachWorktree = (thread2, target) => gen(function* () {
26700
27324
  const { worktree, pullRequestUrl } = target._tag === "pullRequest" ? yield* pullRequestWorktree(thread2.projectId, target.selector) : {
@@ -26773,6 +27397,7 @@ const make$O = gen(function* () {
26773
27397
  get: get2,
26774
27398
  create,
26775
27399
  update: update2,
27400
+ fork: fork2,
26776
27401
  started,
26777
27402
  prepareWorkspace,
26778
27403
  listFiles,
@@ -27094,7 +27719,8 @@ const userMessage = (threadId, text2, attachments, now2) => ({
27094
27719
  ],
27095
27720
  createdAt: now2,
27096
27721
  completedAt: now2,
27097
- usage: null
27722
+ usage: null,
27723
+ forkPoint: null
27098
27724
  });
27099
27725
  const openAssistantMessage = (threadId, now2) => ({
27100
27726
  id: randomUUID(),
@@ -27103,7 +27729,8 @@ const openAssistantMessage = (threadId, now2) => ({
27103
27729
  parts: [],
27104
27730
  createdAt: now2,
27105
27731
  completedAt: null,
27106
- usage: null
27732
+ usage: null,
27733
+ forkPoint: null
27107
27734
  });
27108
27735
  const withoutImageData = (value2) => {
27109
27736
  if (Array.isArray(value2)) return value2.map(withoutImageData);
@@ -27230,7 +27857,10 @@ const make$K = gen(function* () {
27230
27857
  turnMessages = next2;
27231
27858
  };
27232
27859
  const handle = (received) => gen(function* () {
27233
- const event = received.type === "tool_call_finished" ? { ...received, output: withoutImageData(received.output) } : received;
27860
+ const event = received.type === "tool_call_finished" ? { ...received, output: withoutImageData(received.output) } : received.type === "turn_completed" && received.forkPoint !== void 0 ? {
27861
+ ...received,
27862
+ forkPoint: { ...received.forkPoint, owner: { provider: provider.id, accountId: thread2.accountId } }
27863
+ } : received;
27234
27864
  if (event.type === "subagent_updated") return yield* updateSubagent2(thread2.id, event.subagent);
27235
27865
  yield* publishTranscript({ type: "thread.event", threadId: thread2.id, event });
27236
27866
  setTurnMessages(foldTranscript(turnMessages, event, yield* nowIso));
@@ -27331,7 +27961,8 @@ const make$K = gen(function* () {
27331
27961
  autoCompactTokens: autoCompactTokens[provider.id],
27332
27962
  userSkills: thread2.userSkills,
27333
27963
  accessMode: thread2.accessMode,
27334
- resumeSessionId: thread2.providerSessionId,
27964
+ resumeSessionId: thread2.providerSessionId ?? thread2.forkedFrom?.sessionId ?? null,
27965
+ forkAt: thread2.providerSessionId === null ? thread2.forkedFrom?.checkpoint ?? null : null,
27335
27966
  home,
27336
27967
  mcpServer,
27337
27968
  instructions: agentInstructions(experimental, environment)
@@ -27345,6 +27976,14 @@ const make$K = gen(function* () {
27345
27976
  });
27346
27977
  return { provider, steer, run: run2, follow, handle, interrupt: interrupt2, messages: () => turnMessages };
27347
27978
  };
27979
+ const promptForSession = (thread2, prompt) => gen(function* () {
27980
+ if (thread2.providerSessionId !== null || thread2.forkedFrom !== null) return prompt;
27981
+ const history = yield* messages.list(thread2.id);
27982
+ if (history.length === 0) return prompt;
27983
+ const lastSwitch = history.flatMap((message) => message.parts).findLast((part) => part.type === "agent_switch");
27984
+ const from = lastSwitch?.type === "agent_switch" ? lastSwitch.from : thread2.provider;
27985
+ return handoffPrompt({ messages: history, from, to: thread2.provider, prompt });
27986
+ });
27348
27987
  const nameThreadWithPullRequestScope = (thread2, prompt) => pullRequests.list(thread2.id).pipe(
27349
27988
  flatMap$1((links) => naming.nameFromPrompt(thread2, prompt, links.length === 0 ? "titleAndBranch" : "title")),
27350
27989
  catch_$2((error) => logWarning("thread naming failed", error))
@@ -27398,19 +28037,20 @@ const make$K = gen(function* () {
27398
28037
  yield* checkStopped;
27399
28038
  if (!(yield* when2)) return null;
27400
28039
  yield* threads.recordTurnBase({ threadId, tree });
28040
+ const agentPrompt2 = yield* promptForSession(thread2, prompt);
27401
28041
  const now2 = yield* nowIso;
27402
28042
  const assistant = openAssistantMessage(threadId, now2);
27403
28043
  yield* insertMessage(userMessage(threadId, prompt, attachments, now2));
27404
28044
  yield* insertMessage(assistant);
27405
28045
  yield* updateThread({ id: threadId, status: "running" });
27406
- return { thread: thread2, environment: environment2, turn: makeTurn(thread2, provider, cwd, home, assistant, stop) };
28046
+ return { thread: thread2, environment: environment2, agentPrompt: agentPrompt2, turn: makeTurn(thread2, provider, cwd, home, assistant, stop) };
27407
28047
  })
27408
28048
  );
27409
28049
  if (admitted === null) return false;
27410
- const { thread: currentThread, environment, turn } = admitted;
28050
+ const { thread: currentThread, environment, agentPrompt, turn } = admitted;
27411
28051
  activeTurns.set(threadId, turn);
27412
28052
  pendingSends.delete(threadId);
27413
- yield* run$1(turns, threadId, turn.run(prompt, attachments, environment));
28053
+ yield* run$1(turns, threadId, turn.run(agentPrompt, attachments, environment));
27414
28054
  if (pending.first && currentThread.createdBy === "user" && prompt.trim() !== "")
27415
28055
  yield* forkDetach(nameThreadWithPullRequestScope(currentThread, prompt));
27416
28056
  return true;
@@ -27512,11 +28152,12 @@ const make$K = gen(function* () {
27512
28152
  if (accountId !== null && (yield* accounts.get(accountId)).provider !== current.provider) {
27513
28153
  return yield* new NotFoundError({ entity: "account", id: accountId });
27514
28154
  }
27515
- if (current.providerSessionId !== null) {
28155
+ const sessionId = current.providerSessionId ?? current.forkedFrom?.sessionId ?? null;
28156
+ if (sessionId !== null) {
27516
28157
  const provider = providers[current.provider];
27517
28158
  if (provider.copySession === void 0) return yield* new ThreadStartedError({ id: threadId });
27518
28159
  yield* provider.copySession(
27519
- current.providerSessionId,
28160
+ sessionId,
27520
28161
  yield* accounts.home(current.accountId),
27521
28162
  yield* accounts.home(accountId)
27522
28163
  );
@@ -27531,12 +28172,37 @@ const make$K = gen(function* () {
27531
28172
  if (switched.prompt !== void 0) yield* resend(threadId, switched.prompt);
27532
28173
  return switched.thread;
27533
28174
  });
28175
+ const switchAgent = (input) => gen(function* () {
28176
+ if (busyThreads.has(input.id)) {
28177
+ return yield* new AgentError({ provider: "hinacode", message: "Wait for the turn to end to switch agents" });
28178
+ }
28179
+ const current = yield* threads.get(input.id);
28180
+ if (input.provider === current.provider) return yield* threads.update(input);
28181
+ const closeSession = providers[current.provider].closeSession;
28182
+ if (closeSession !== void 0) yield* closeSession(current.id, yield* accounts.home(current.accountId));
28183
+ const started = yield* threads.started(input.id);
28184
+ const thread2 = yield* threads.update(input);
28185
+ if (started) {
28186
+ const now2 = yield* nowIso;
28187
+ yield* insertMessage({
28188
+ id: randomUUID(),
28189
+ threadId: thread2.id,
28190
+ role: "assistant",
28191
+ parts: [{ type: "agent_switch", from: current.provider, to: thread2.provider }],
28192
+ createdAt: now2,
28193
+ completedAt: now2,
28194
+ usage: null,
28195
+ forkPoint: null
28196
+ });
28197
+ }
28198
+ return thread2;
28199
+ }).pipe(exclusive(input.id));
27534
28200
  yield* resumeDue.pipe(
27535
28201
  catch_$2((error) => logWarning("limit reset check failed", error)),
27536
28202
  repeat(spaced("1 second")),
27537
28203
  forkIn(scope$12)
27538
28204
  );
27539
- const startWake = ({ threadId, events, discard }) => suspend$2(() => {
28205
+ const startWake = (source, { threadId, sessionId, events, discard }) => suspend$2(() => {
27540
28206
  let claimed = false;
27541
28207
  let adopted = false;
27542
28208
  return gen(function* () {
@@ -27546,13 +28212,13 @@ const make$K = gen(function* () {
27546
28212
  const turn = yield* gen(function* () {
27547
28213
  const thread2 = yield* threads.get(threadId);
27548
28214
  if (thread2.status === "archived") return null;
27549
- const provider = yield* providerFor(thread2.provider);
28215
+ if (thread2.provider !== source.id || thread2.providerSessionId !== sessionId) return null;
27550
28216
  const home = yield* accounts.home(thread2.accountId);
27551
28217
  const { cwd } = yield* activeWorkspace(threadId);
27552
28218
  const assistant = openAssistantMessage(threadId, yield* nowIso);
27553
28219
  yield* insertMessage(assistant);
27554
28220
  yield* updateThread({ id: threadId, status: "running" });
27555
- return makeTurn(thread2, provider, cwd, home, assistant, makeUnsafe$9());
28221
+ return makeTurn(thread2, source, cwd, home, assistant, makeUnsafe$9());
27556
28222
  }).pipe(worktrees.exclusive, exclusive(threadId));
27557
28223
  if (turn === null) return;
27558
28224
  activeTurns.set(threadId, turn);
@@ -27574,7 +28240,9 @@ const make$K = gen(function* () {
27574
28240
  runForEach(
27575
28241
  provider.wakes,
27576
28242
  (wake) => forkIn(
27577
- startWake(wake).pipe(catch_$2((error) => logWarning("agent-started turn did not open", error))),
28243
+ startWake(provider, wake).pipe(
28244
+ catch_$2((error) => logWarning("agent-started turn did not open", error))
28245
+ ),
27578
28246
  scope$12
27579
28247
  )
27580
28248
  ),
@@ -27626,6 +28294,7 @@ const make$K = gen(function* () {
27626
28294
  unqueue,
27627
28295
  resumeAtReset,
27628
28296
  switchAccount,
28297
+ switchAgent,
27629
28298
  steer: (threadId, text2, attachments) => steerWhen({ threadId, text: text2, attachments, when: succeed$3(true) }).pipe(asVoid),
27630
28299
  steerWhen,
27631
28300
  interrupt: (threadId) => suspend$2(() => {
@@ -27774,6 +28443,15 @@ const projectFileRequest = (url) => {
27774
28443
  return null;
27775
28444
  }
27776
28445
  };
28446
+ const attachmentRequest = (url) => {
28447
+ const parsed = URL.parse(url);
28448
+ if (parsed?.protocol !== `${ATTACHMENT_PROTOCOL}:` || parsed.host !== "file") return null;
28449
+ try {
28450
+ return { path: decodeURIComponent(parsed.pathname.slice(1)), environment: parsed.searchParams.get("environment") };
28451
+ } catch {
28452
+ return null;
28453
+ }
28454
+ };
27777
28455
  const MAX_BYTES = 20 * 1024 * 1024;
27778
28456
  const MIME_BY_EXTENSION = {
27779
28457
  ".png": "image/png",
@@ -33157,7 +33835,7 @@ const makeUpgradeHandler = (lazyWss, httpEffect, options) => {
33157
33835
  const handledApp = toHandled(httpEffect, handleResponse, options.middleware);
33158
33836
  return withFiber((parent) => {
33159
33837
  const services = parent.context;
33160
- return succeed$3(function handler(nodeRequest, socket, head) {
33838
+ return succeed$3(function handler(nodeRequest, socket, head2) {
33161
33839
  let nodeResponse_ = void 0;
33162
33840
  const nodeResponse = () => {
33163
33841
  if (nodeResponse_ === void 0) {
@@ -33182,7 +33860,7 @@ const makeUpgradeHandler = (lazyWss, httpEffect, options) => {
33182
33860
  })));
33183
33861
  if (socket.destroyed) return onClose();
33184
33862
  socket.once("close", onClose);
33185
- wss.handleUpgrade(nodeRequest, socket, head, (ws) => {
33863
+ wss.handleUpgrade(nodeRequest, socket, head2, (ws) => {
33186
33864
  socket.off("close", onClose);
33187
33865
  request.upgraded = true;
33188
33866
  resume(succeed$3(ws));
@@ -43006,8 +43684,8 @@ const encodeAction = (action, screen) => {
43006
43684
  }
43007
43685
  }
43008
43686
  };
43009
- const makeReader = (socket, head) => {
43010
- let buffer2 = Buffer.from(head);
43687
+ const makeReader = (socket, head2) => {
43688
+ let buffer2 = Buffer.from(head2);
43011
43689
  let wake;
43012
43690
  let ended = false;
43013
43691
  const onData = (chunk) => {
@@ -43037,9 +43715,9 @@ const makeReader = (socket, head) => {
43037
43715
  };
43038
43716
  const PROTOCOL_VERSION = "RFB 003.008\n";
43039
43717
  const SECURITY_NONE = 1;
43040
- const handshake = (socket, head) => tryPromise({
43718
+ const handshake = (socket, head2) => tryPromise({
43041
43719
  try: async () => {
43042
- const reader = makeReader(socket, head);
43720
+ const reader = makeReader(socket, head2);
43043
43721
  try {
43044
43722
  const version = (await reader.read(12)).toString();
43045
43723
  if (!version.startsWith("RFB ")) throw new Error(`unexpected greeting ${JSON.stringify(version)}`);
@@ -43877,11 +44555,11 @@ ${output}` : ""}`
43877
44555
  threadId,
43878
44556
  (sbx, sandboxId) => scoped(
43879
44557
  gen(function* () {
43880
- const { socket, head } = yield* acquireRelease(
44558
+ const { socket, head: head2 } = yield* acquireRelease(
43881
44559
  sbx.tunnel(sandboxId, VNC_PORT),
43882
44560
  (tunnel) => sync(() => tunnel.socket.destroy())
43883
44561
  );
43884
- const screen = yield* handshake(socket, head);
44562
+ const screen = yield* handshake(socket, head2);
43885
44563
  const steps = yield* try_({
43886
44564
  try: () => actions.flatMap((action) => encodeAction(action, screen)),
43887
44565
  catch: (cause) => cause instanceof VmInputError ? cause : new VmError({ message: String(cause) })
@@ -44049,7 +44727,7 @@ ${output}` : ""}`
44049
44727
  if (vm.status !== "running") return yield* new VmError({ message: "The VM is not running." });
44050
44728
  openingScreens.add(streamId);
44051
44729
  const sbx = yield* client2;
44052
- const { socket, head } = yield* sbx.tunnel(vm.sandboxId, VNC_PORT, { passive: true }).pipe(
44730
+ const { socket, head: head2 } = yield* sbx.tunnel(vm.sandboxId, VNC_PORT, { passive: true }).pipe(
44053
44731
  catchTag(
44054
44732
  "SandboxGoneError",
44055
44733
  (error) => andThen(forget(threadId, vm.sandboxId), fail$2(error))
@@ -44059,7 +44737,7 @@ ${output}` : ""}`
44059
44737
  const screen = { threadId, socket, pending: [], pendingSize: 0, timer: void 0 };
44060
44738
  screens.set(streamId, screen);
44061
44739
  own(owner2, streamId);
44062
- buffer2(streamId, screen, head);
44740
+ buffer2(streamId, screen, head2);
44063
44741
  socket.on("data", (data) => buffer2(streamId, screen, data));
44064
44742
  socket.on("error", () => {
44065
44743
  });
@@ -44543,6 +45221,8 @@ const renderPart = (part) => {
44543
45221
  return `[attachment ${part.attachment.name}]`;
44544
45222
  case "compaction":
44545
45223
  return `[context compaction: ${part.compaction.status}]`;
45224
+ case "agent_switch":
45225
+ return `[agent switched: ${part.from} → ${part.to}]`;
44546
45226
  }
44547
45227
  };
44548
45228
  const renderMessage = (message) => [`## ${message.role} (${message.createdAt})`, ...message.parts.flatMap((part) => renderPart(part) ?? [])].join("\n");
@@ -48449,8 +49129,8 @@ const make$7 = gen(function* () {
48449
49129
  flatMap$1((current) => events.publish({ type: "pullRequest.guide", url, state: current })),
48450
49130
  catchCause$1((cause) => logWarning("pull request guide push failed", url, cause))
48451
49131
  );
48452
- const endJobUnlessSuperseded = (url, head, next) => sync(() => {
48453
- if (jobs.get(url)?.head !== head) return;
49132
+ const endJobUnlessSuperseded = (url, head2, next) => sync(() => {
49133
+ if (jobs.get(url)?.head !== head2) return;
48454
49134
  if (next === null) jobs.delete(url);
48455
49135
  else jobs.set(url, next);
48456
49136
  });
@@ -49251,13 +49931,13 @@ const startForward = (openTunnel) => callback$1((resume) => {
49251
49931
  runFork(
49252
49932
  openTunnel().pipe(
49253
49933
  tap$2(
49254
- ({ socket, head }) => sync(() => {
49934
+ ({ socket, head: head2 }) => sync(() => {
49255
49935
  track(socket);
49256
49936
  if (local.destroyed) {
49257
49937
  socket.destroy();
49258
49938
  return;
49259
49939
  }
49260
- if (head.length > 0) local.write(head);
49940
+ if (head2.length > 0) local.write(head2);
49261
49941
  socket.pipe(local);
49262
49942
  local.pipe(socket);
49263
49943
  local.once("close", () => socket.destroy());
@@ -49841,6 +50521,7 @@ const handlers = {
49841
50521
  "browser.close": (input) => Browser.use((browser) => browser.close(input)),
49842
50522
  "app.ready": (_, desktop) => desktop?.show ?? void_$1,
49843
50523
  "app.focus": (_, desktop) => desktop?.focus ?? void_$1,
50524
+ "app.setBadgeCount": ({ count }, desktop) => desktop?.setBadgeCount(count) ?? void_$1,
49844
50525
  "app.setColorScheme": (scheme, desktop) => desktop?.setColorScheme(scheme) ?? void_$1,
49845
50526
  "projects.list": () => Projects.use((projects) => projects.listWithRepositories),
49846
50527
  "projects.create": (input) => Projects.use((projects) => projects.create(input)),
@@ -49867,8 +50548,12 @@ const handlers = {
49867
50548
  }),
49868
50549
  // Another agent starts from its own defaults, not the model, effort and tier picked for the last one.
49869
50550
  "threads.update": (input) => gen(function* () {
49870
- const patch = input.provider === void 0 ? input : { ...yield* newThreadOptions(input.provider), ...input };
49871
- const thread2 = yield* Threads.use((threads) => threads.update(patch));
50551
+ const { provider: switchTo } = input;
50552
+ const thread2 = switchTo === void 0 ? yield* Threads.use((threads) => threads.update(input)) : yield* newThreadOptions(switchTo).pipe(
50553
+ flatMap$1(
50554
+ (defaults) => AgentRunner.use((runner) => runner.switchAgent({ ...defaults, ...input, provider: switchTo }))
50555
+ )
50556
+ );
49872
50557
  if (input.accessMode !== void 0) {
49873
50558
  yield* AgentRunner.use((runner) => runner.setAccessMode(thread2.id, thread2.accessMode));
49874
50559
  }
@@ -49897,6 +50582,9 @@ const handlers = {
49897
50582
  "threads.changes": ({ threadId, scope: scope2 }) => Threads.use((threads) => threads.changes(threadId, scope2)),
49898
50583
  "threads.archive": ({ threadId }) => Threads.use((threads) => threads.archive(threadId)),
49899
50584
  "threads.unarchive": ({ threadId }) => Threads.use((threads) => threads.unarchive(threadId)),
50585
+ "threads.fork": ({ threadId, messageId }) => Threads.use((threads) => threads.fork(threadId, messageId)).pipe(
50586
+ tap$2((thread2) => Events.use((events) => events.publish({ type: "thread.updated", thread: thread2 })))
50587
+ ),
49900
50588
  "projects.currentBranch": ({ id }) => Worktrees.use((worktrees) => worktrees.currentBranch(id)),
49901
50589
  "projects.defaultBranch": ({ id }) => Worktrees.use((worktrees) => worktrees.defaultBranch(id)),
49902
50590
  "projects.branches": ({ id }) => Worktrees.use((worktrees) => worktrees.branches(id)),
@@ -50771,8 +51459,8 @@ const makeAppLayer = ({ userData, sbxConfigPath, keyring, updates, toWindows, se
50771
51459
  provideMerge(effectDiscard(serve2 ? applyServeConfig(serve2) : void_$1)),
50772
51460
  provideMerge(services),
50773
51461
  provide$3(mergeAll$1(claude, CodexProvider.layer, MuseProvider.layer)),
50774
- provideMerge(makeEventsLayer(toWindows)),
50775
51462
  provideMerge(mergeAll$1(layer$B, layer$z, layer$k)),
51463
+ provideMerge(makeEventsLayer(toWindows)),
50776
51464
  provide$3(mergeAll$1(layer$G(join$2(userData, "hinacode.sqlite")), keyring)),
50777
51465
  provide$3(layer$K)
50778
51466
  );
@@ -50803,7 +51491,7 @@ const hydratePath = async (env) => {
50803
51491
  env.PATH = [...new Set(entries)].join(":");
50804
51492
  };
50805
51493
  export {
50806
- callback$1 as $,
51494
+ ClientSettings as $,
50807
51495
  make$1c as A,
50808
51496
  makeAppLayer as B,
50809
51497
  autoUpdate as C,
@@ -50829,40 +51517,42 @@ export {
50829
51517
  Worktrees as W,
50830
51518
  pairingUrl as X,
50831
51519
  restartCommand as Y,
50832
- catchDefect as Z,
50833
- succeed$3 as _,
51520
+ TaggedError as Z,
51521
+ promise as _,
50834
51522
  spaced as a,
50835
- timeoutOrElse as a0,
50836
- seconds as a1,
50837
- TaggedError as a2,
50838
- promise as a3,
50839
- EVENT_CHANNEL as a4,
50840
- RPC_CHANNEL as a5,
50841
- isTrustedSender as a6,
50842
- route as a7,
50843
- map$3 as a8,
50844
- externalUrl as a9,
50845
- catch_$2 as aa,
50846
- logWarning as ab,
50847
- runFork as ac,
50848
- ignore$1 as ad,
50849
- ATTACHMENT_PROTOCOL as ae,
50850
- GITHUB_ASSET_PROTOCOL as af,
50851
- PROJECT_FILE_PROTOCOL as ag,
50852
- decodeUnknownOption as ah,
50853
- RpcMethods as ai,
50854
- Keyring as aj,
50855
- Environments as ak,
50856
- isInside as al,
50857
- githubAssetId as am,
50858
- GitHub as an,
50859
- projectFileRequest as ao,
50860
- Files as ap,
50861
- BROWSER_PARTITION as aq,
50862
- LIQUID_GLASS_ARGUMENT as ar,
50863
- lockDownWebview as as,
50864
- getOrUndefined$1 as at,
50865
- isAllowedNavigation as au,
51523
+ Environments as a0,
51524
+ projectFileRequest as a1,
51525
+ attachmentRequest as a2,
51526
+ githubAssetId as a3,
51527
+ externalUrl as a4,
51528
+ catch_$2 as a5,
51529
+ catchDefect as a6,
51530
+ succeed$3 as a7,
51531
+ callback$1 as a8,
51532
+ timeoutOrElse as a9,
51533
+ seconds as aa,
51534
+ EVENT_CHANNEL as ab,
51535
+ RPC_CHANNEL as ac,
51536
+ isTrustedSender as ad,
51537
+ route as ae,
51538
+ map$3 as af,
51539
+ logWarning as ag,
51540
+ runFork as ah,
51541
+ ignore$1 as ai,
51542
+ ATTACHMENT_PROTOCOL as aj,
51543
+ GITHUB_ASSET_PROTOCOL as ak,
51544
+ PROJECT_FILE_PROTOCOL as al,
51545
+ decodeUnknownOption as am,
51546
+ RpcMethods as an,
51547
+ Keyring as ao,
51548
+ isInside as ap,
51549
+ GitHub as aq,
51550
+ Files as ar,
51551
+ BROWSER_PARTITION as as,
51552
+ LIQUID_GLASS_ARGUMENT as at,
51553
+ lockDownWebview as au,
51554
+ getOrUndefined$1 as av,
51555
+ isAllowedNavigation as aw,
50866
51556
  Terminals as b,
50867
51557
  forEach$1 as c,
50868
51558
  decodeUnknownSync as d,