hinacode 0.1.0-alpha.14 → 0.1.0-alpha.15

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.
@@ -15840,6 +15840,15 @@ const Subagent = Struct({
15840
15840
  startedAt: String$1,
15841
15841
  endedAt: NullOr(String$1)
15842
15842
  });
15843
+ const BackgroundTaskKind = Literals(["shell", "workflow", "other"]);
15844
+ const BackgroundTask = Struct({
15845
+ id: String$1,
15846
+ kind: BackgroundTaskKind,
15847
+ /** What the agent said the task is for, or its command line. */
15848
+ label: String$1,
15849
+ /** When HinaCode first saw it running. */
15850
+ startedAt: String$1
15851
+ });
15843
15852
  const Compaction = Union2([
15844
15853
  Struct({ status: Literal2("running") }),
15845
15854
  Struct({
@@ -16905,6 +16914,9 @@ const RpcMethods = {
16905
16914
  "subagents.list": rpc(Struct({ threadId: String$1 }), ArraySchema(Subagent)),
16906
16915
  /** Stops one running sub-agent by its `Subagent.id`. The turn that spawned it keeps going. */
16907
16916
  "subagents.stop": rpc(Struct({ threadId: String$1, subagentId: String$1 }), Void2),
16917
+ /** Background tasks the thread's agent has running now, oldest first. */
16918
+ "backgroundTasks.list": rpc(Struct({ threadId: String$1 }), ArraySchema(BackgroundTask)),
16919
+ "backgroundTasks.stop": rpc(Struct({ threadId: String$1, taskId: String$1 }), Void2),
16908
16920
  /** Tokens the thread spent, read from its agent's transcripts. Null before the first turn or once they are gone. */
16909
16921
  "threads.usage": rpc(Struct({ threadId: String$1 }), NullOr(ThreadUsage)),
16910
16922
  /** Answers an agent's `request_secret`. `value: null` declines; otherwise it is stored under the request's name. */
@@ -17156,6 +17168,8 @@ const methodKind = {
17156
17168
  "secrets.clear": "mutation",
17157
17169
  "subagents.list": "read",
17158
17170
  "subagents.stop": "mutation",
17171
+ "backgroundTasks.list": "read",
17172
+ "backgroundTasks.stop": "mutation",
17159
17173
  "threads.usage": "read",
17160
17174
  "secrets.respond": "mutation",
17161
17175
  "pullRequests.list": "read",
@@ -17274,6 +17288,12 @@ const PushEvent = Union2([
17274
17288
  threadId: String$1,
17275
17289
  subagents: ArraySchema(Subagent)
17276
17290
  }),
17291
+ /** Every background task the thread's agent has running, oldest first, sent whenever the set changes. */
17292
+ Struct({
17293
+ type: Literal2("thread.backgroundTasks"),
17294
+ threadId: String$1,
17295
+ tasks: ArraySchema(BackgroundTask)
17296
+ }),
17277
17297
  /** Something changed directly inside a folder `fs.watch` asked for. */
17278
17298
  Struct({ type: Literal2("fs.changed"), root: String$1, path: String$1 }),
17279
17299
  /** An automation run was recorded or changed status. */
@@ -19723,6 +19743,15 @@ function updateSubagent(state, subagent) {
19723
19743
  state.subagents.set(subagent.id, subagent);
19724
19744
  return [{ type: "subagent_updated", subagent }];
19725
19745
  }
19746
+ const backgroundKinds = { local_bash: "shell", local_workflow: "workflow" };
19747
+ function backgroundTasksOf(message, previous, now2) {
19748
+ return message.tasks.filter((task) => task.task_type !== "local_agent" && task.ambient !== true).map((task) => ({
19749
+ id: task.task_id,
19750
+ kind: backgroundKinds[task.task_type] ?? "other",
19751
+ label: task.description,
19752
+ startedAt: previous.find((known) => known.id === task.task_id)?.startedAt ?? now2
19753
+ }));
19754
+ }
19726
19755
  const limitErrorText = /^(?:error:\s*)?(?:you['’]ve hit your (?:(?:usage )?limit|org['’]s monthly spend limit)|usage limit reached|(?:claude(?: api)? )?rate limit reached|api error:\s*429\b)/i;
19727
19756
  const orgSpendLimitText = /^(?:error:\s*)?you['’]ve hit your org['’]s monthly spend limit/i;
19728
19757
  function mapResult(result2, limitMessage, resetAt, state) {
@@ -20158,6 +20187,7 @@ const layer$C = effect(
20158
20187
  const sessions = /* @__PURE__ */ new Map();
20159
20188
  const resumable = /* @__PURE__ */ new Map();
20160
20189
  const wakes = yield* unbounded();
20190
+ const backgroundTaskChanges = yield* unbounded();
20161
20191
  const probedCommands = yield* make$1j({
20162
20192
  lookup: probeCommands,
20163
20193
  capacity: 32,
@@ -20182,9 +20212,15 @@ const layer$C = effect(
20182
20212
  session.expiry?.interruptUnsafe();
20183
20213
  session.expiry = null;
20184
20214
  };
20215
+ const setBackgroundTasks = (session, tasks) => {
20216
+ if (session.backgroundTasks.length === 0 && tasks.length === 0) return;
20217
+ session.backgroundTasks = tasks;
20218
+ offerUnsafe(backgroundTaskChanges, { threadId: session.threadId, tasks });
20219
+ };
20185
20220
  const closeSessionUnsafe = (session) => {
20186
20221
  if (session.closed) return;
20187
20222
  session.closed = true;
20223
+ setBackgroundTasks(session, []);
20188
20224
  cancelExpiry(session);
20189
20225
  if (sessions.get(session.threadId) === session) sessions.delete(session.threadId);
20190
20226
  shutdownUnsafe(session.prompts);
@@ -20235,6 +20271,7 @@ const layer$C = effect(
20235
20271
  session.taskSnapshots = true;
20236
20272
  session.tasks.clear();
20237
20273
  for (const task of message.tasks) if (task.ambient !== true) session.tasks.set(task.task_id, task.run_id);
20274
+ setBackgroundTasks(session, backgroundTasksOf(message, session.backgroundTasks, (/* @__PURE__ */ new Date()).toISOString()));
20238
20275
  return;
20239
20276
  }
20240
20277
  if (session.taskSnapshots) return;
@@ -20401,6 +20438,7 @@ const layer$C = effect(
20401
20438
  answering: [],
20402
20439
  tasks: /* @__PURE__ */ new Map(),
20403
20440
  taskSnapshots: false,
20441
+ backgroundTasks: [],
20404
20442
  reportsState: false,
20405
20443
  heldEnd: null,
20406
20444
  claims: 1,
@@ -20571,6 +20609,21 @@ const layer$C = effect(
20571
20609
  listCommands,
20572
20610
  runTurn,
20573
20611
  wakes: fromQueue(wakes),
20612
+ backgroundTasks: {
20613
+ changes: fromQueue(backgroundTaskChanges),
20614
+ // A background task's id is its CLI task id, like a sub-agent's.
20615
+ stop: (threadId, taskId) => suspend$2(() => {
20616
+ const session = sessions.get(threadId);
20617
+ if (session === void 0) return void_$1;
20618
+ return lease(
20619
+ session,
20620
+ (leased) => tryPromise({
20621
+ try: () => leased.query.stopTask(taskId),
20622
+ catch: agentError("Failed to stop the background task")
20623
+ })
20624
+ );
20625
+ })
20626
+ },
20574
20627
  steer,
20575
20628
  interrupt: (threadId) => {
20576
20629
  const session = sessions.get(threadId);
@@ -20660,7 +20713,7 @@ const usageLimitAssistant = {
20660
20713
  }
20661
20714
  };
20662
20715
  const markdownFixture = '# Heading 1 with `code`\n\nA paragraph right under a heading. It runs long enough to wrap, so the line height and the measure of the transcript column are visible. **Bold**, _italic_, **_bold italic_**, ~~strikethrough~~, `inline code`, and a [link to the docs](https://github.com/hinadev-ai/hinacode). A bare URL autolinks: https://github.com/hinadev-ai/hinacode. A pull request reference: #1.\n\nA second paragraph, to show the gap between paragraphs.\nThis line follows a soft break, so it joins the paragraph above.\\\nThis line follows a hard break, so it starts on its own line.\n\n## Heading 2\n\n### Heading 3\n\n#### Heading 4\n\n##### Heading 5\n\n###### Heading 6\n\n---\n\n## Links\n\nEach web link should start with an icon. Pull requests get the GitHub mark and a hover card, other sites their favicon, and a site without one the globe.\n\n- A bare pull request URL, shortened to `owner/repo#n`: https://github.com/react/react/pull/31139\n- A pull request with its own text: [the React Compiler ref fix](https://github.com/react/react/pull/34000)\n- A pull request in another repository: https://github.com/vercel/next.js/pull/71000\n- A GitHub issue, which is not a pull request: https://github.com/react/react/issues/11347\n- A repository: https://github.com/react/react\n- Documentation sites: [React docs](https://react.dev/reference/react/useMemo), [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap) and https://tailwindcss.com/docs/overflow-wrap\n- A site with no favicon: https://example.com\n- A link inside **bold text: [react.dev](https://react.dev)** and one inside a sentence that wraps across lines so the icon stays with its text: [the Effect documentation on services and layers](https://effect.website/docs/requirements-management/services/)\n- Not web links, so no icon: [an email](mailto:dev@example.com) and [a relative path](./README.md)\n\n## Lists\n\n- An unordered item\n- An item with **bold** and `code`\n - A nested item\n - A third level\n- An item long enough to wrap onto a second line, to check that the wrapped line lines up with the text and not with the bullet.\n\n1. First\n2. Second\n 1. Nested ordered\n 2. Another\n3. Third\n\nAn ordered list that starts at five:\n\n5. Five\n6. Six\n\nA task list:\n\n- [x] A finished task\n- [ ] An open task\n - [ ] A nested task\n\nA loose list:\n\n- A loose list item, with a blank line after it.\n\n- The next loose item, with a paragraph inside.\n\n A second paragraph in the same item.\n\n## Quotes\n\n> A quote with a single paragraph, long enough to wrap, so the bar runs the height of both lines and stays inside the quote.\n\n> A quote with a list:\n>\n> - one\n> - two\n>\n> > A nested quote.\n\n## Code\n\nInline `const answer = 42` sits on the baseline of the text around it.\n\n```ts\nimport { Effect } from "effect"\n\n/** A long line to check horizontal scrolling inside the block, instead of the whole transcript widening past the column. */\nexport const greet = (name: string) => Effect.succeed(`Hello, ${name}`)\n```\n\n```\nA fence without a language.\n```\n\n```sh\npnpm typecheck && pnpm lint && pnpm test\n```\n\n## Table\n\n| Left | Center | Right | Notes |\n| :----------------------------------- | :----: | -----: | ------------------------------------------------------------------------- |\n| `fonts/otf/` | 8 | 1.2 MB | Static weights from Thin to ExtraBold |\n| `fonts/ttf/` | 8 | 1.4 MB | The same weights as TTF |\n| `fonts/variable/PaperMono[wght].ttf` | 1 | 310 KB | One file covering the whole weight range, long enough to wrap in its cell |\n| `fonts/webfonts/` | 9 | 640 KB | WOFF2 versions of all of the above |\n\n## Diagram\n\n```mermaid\nflowchart LR\n Prompt --> Agent --> Worktree --> PR\n```\n\n## Text in other scripts\n\n這是一段繁體中文,用來檢查中英混排時的行高與字距,例如 `pnpm dev` 與 HinaCode 之間的間隔。\n\nこれは日本語の段落です。行の高さと、英数字の HinaCode や `git fetch` との混在を確認します。\n\n## Edge cases\n\nA footnote reference[^1] and an escaped \\*asterisk\\*. Keys render as keys: press <kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>. Other raw HTML stays text: <div>, and a tag written in prose like <Suspense> stays visible.\n\nA very long unbroken token: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\n[^1]: The footnote text.\n';
20663
- const mockScenarios = ["usage-limit", "org-spend-limit", "todos", "markdown", "stream"];
20716
+ const mockScenarios = ["usage-limit", "org-spend-limit", "todos", "markdown", "stream", "activity"];
20664
20717
  const commands = [
20665
20718
  {
20666
20719
  trigger: "/",
@@ -20733,10 +20786,51 @@ const todoTurn = (first) => first ? [
20733
20786
  { type: "text_delta", text: "All tasks are done." },
20734
20787
  { type: "turn_completed" }
20735
20788
  ];
20789
+ const activityTurn = () => [
20790
+ ...todoTurn(true).filter((event) => event.type !== "turn_completed" && event.type !== "text_delta"),
20791
+ {
20792
+ type: "subagent_updated",
20793
+ subagent: {
20794
+ id: "agent-1",
20795
+ label: "Audit the composer",
20796
+ callId: null,
20797
+ status: "running",
20798
+ summary: "Reading Composer.tsx",
20799
+ lastTool: "Read",
20800
+ toolUses: 3,
20801
+ tokens: 1200,
20802
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
20803
+ endedAt: null
20804
+ }
20805
+ },
20806
+ ...toolCall(
20807
+ "activity-shell-1",
20808
+ "Bash",
20809
+ { command: "pnpm dev", description: "Start the dev server", run_in_background: true },
20810
+ "Command running in background with ID: shell-1"
20811
+ ),
20812
+ ...toolCall(
20813
+ "activity-shell-2",
20814
+ "Bash",
20815
+ { command: "pnpm test --watch", description: "Watch the unit tests", run_in_background: true },
20816
+ "Command running in background with ID: shell-2"
20817
+ )
20818
+ ];
20819
+ const activityShells = () => [
20820
+ { id: "shell-1", kind: "shell", label: "Start the dev server", startedAt: (/* @__PURE__ */ new Date()).toISOString() },
20821
+ { id: "shell-2", kind: "shell", label: "Watch the unit tests", startedAt: (/* @__PURE__ */ new Date()).toISOString() }
20822
+ ];
20736
20823
  const usageLimitLayer = (scenario = "usage-limit", resetAfterMs = 6e4) => effect(
20737
20824
  ClaudeProvider,
20738
- sync(() => {
20825
+ gen(function* () {
20739
20826
  const attempted = /* @__PURE__ */ new Set();
20827
+ const shells = /* @__PURE__ */ new Map();
20828
+ const shellChanges = yield* unbounded();
20829
+ const heldTurns = /* @__PURE__ */ new Map();
20830
+ const setShells = (threadId, tasks) => {
20831
+ shells.set(threadId, tasks);
20832
+ offerUnsafe(shellChanges, { threadId, tasks });
20833
+ };
20740
20834
  return ClaudeProvider.of({
20741
20835
  id: "claude",
20742
20836
  listModels: succeed$3([unlistedModel("claude-sonnet-5-5", "claude")]),
@@ -20763,6 +20857,16 @@ const usageLimitLayer = (scenario = "usage-limit", resetAfterMs = 6e4) => effect
20763
20857
  copySession: () => void_$1,
20764
20858
  listCommands: () => succeed$3(commands),
20765
20859
  runTurn: (input) => suspend(() => {
20860
+ if (scenario === "activity") {
20861
+ setShells(input.threadId, activityShells());
20862
+ const interrupted = makeUnsafe$9();
20863
+ heldTurns.set(input.threadId, interrupted);
20864
+ const ended = { type: "turn_failed", message: "Interrupted" };
20865
+ return concat(
20866
+ fromIterable(activityTurn()),
20867
+ fromEffect(_await(interrupted).pipe(as(ended)))
20868
+ );
20869
+ }
20766
20870
  if (scenario === "markdown") return fromIterable(markdownTurn());
20767
20871
  if (scenario === "stream")
20768
20872
  return fromIterable(streamTurn()).pipe(tap$1(() => sleep("20 millis")));
@@ -20817,8 +20921,20 @@ const usageLimitLayer = (scenario = "usage-limit", resetAfterMs = 6e4) => effect
20817
20921
  ];
20818
20922
  return fromIterable(events);
20819
20923
  }),
20924
+ backgroundTasks: {
20925
+ changes: fromQueue(shellChanges),
20926
+ stop: (threadId, taskId) => sync(
20927
+ () => setShells(
20928
+ threadId,
20929
+ (shells.get(threadId) ?? []).filter((task) => task.id !== taskId)
20930
+ )
20931
+ )
20932
+ },
20820
20933
  steer: () => fail$2(new AgentError({ provider: "claude", message: "No turn is running on this thread" })),
20821
- interrupt: () => void_$1,
20934
+ interrupt: (threadId) => {
20935
+ const held = heldTurns.get(threadId);
20936
+ return held === void 0 ? void_$1 : succeed$5(held, void 0).pipe(asVoid);
20937
+ },
20822
20938
  respondApproval: () => void_$1,
20823
20939
  respondQuestion: () => void_$1,
20824
20940
  setAccessMode: () => void_$1
@@ -21198,6 +21314,11 @@ const GetAccountRateLimitsResponse = Struct({
21198
21314
  rateLimits: RateLimitSnapshot,
21199
21315
  rateLimitsByLimitId: NullOr(Record(String$1, RateLimitSnapshot))
21200
21316
  });
21317
+ const ThreadBackgroundTerminal = Struct({ processId: String$1, command: String$1 });
21318
+ const ThreadBackgroundTerminalsListResponse = Struct({
21319
+ data: ArraySchema(ThreadBackgroundTerminal),
21320
+ nextCursor: NullOr(String$1)
21321
+ });
21201
21322
  const CLIENT_VERSION$1 = "0.1.0";
21202
21323
  const FAST_SERVICE_TIER = "priority";
21203
21324
  const decisionToWire = {
@@ -21280,6 +21401,8 @@ const copySession = (threadId, from, to) => tryPromise({
21280
21401
  )
21281
21402
  );
21282
21403
  const interruptedEvent$1 = { type: "turn_failed", message: "Turn interrupted" };
21404
+ const TERMINAL_POLL_INTERVAL = seconds(2);
21405
+ const sameTasks = (a, b) => a.length === b.length && a.every((task, index) => task.id === b[index]?.id);
21283
21406
  const make$U = gen(function* () {
21284
21407
  const providerScope = yield* scope;
21285
21408
  const clientLock = yield* make$1d(1);
@@ -21315,6 +21438,64 @@ const make$U = gen(function* () {
21315
21438
  const subagentsByThread = /* @__PURE__ */ new Map();
21316
21439
  const subagentTurns = /* @__PURE__ */ new Map();
21317
21440
  const loadedCompactLimits = /* @__PURE__ */ new Map();
21441
+ const terminalsByThread = /* @__PURE__ */ new Map();
21442
+ const backgroundTaskChanges = yield* unbounded();
21443
+ const listTerminals = (terminals) => gen(function* () {
21444
+ const found2 = [];
21445
+ let cursor = null;
21446
+ do {
21447
+ const params2 = { threadId: terminals.codexThreadId, cursor, limit: 100 };
21448
+ const raw2 = yield* terminals.client.request("thread/backgroundTerminals/list", params2);
21449
+ const page = yield* decodeUnknownEffect(
21450
+ ThreadBackgroundTerminalsListResponse
21451
+ )(raw2);
21452
+ found2.push(...page.data);
21453
+ cursor = page.nextCursor;
21454
+ } while (cursor);
21455
+ return found2;
21456
+ });
21457
+ const refreshTerminals = (threadId, terminals) => gen(function* () {
21458
+ const listed = yield* listTerminals(terminals).pipe(orElseSucceed(() => []));
21459
+ const now2 = yield* nowIso;
21460
+ const tasks = listed.map((terminal) => ({
21461
+ id: terminal.processId,
21462
+ kind: "shell",
21463
+ label: terminal.command,
21464
+ startedAt: terminals.tasks.find((task) => task.id === terminal.processId)?.startedAt ?? now2
21465
+ }));
21466
+ if (sameTasks(terminals.tasks, tasks)) return tasks;
21467
+ terminals.tasks = tasks;
21468
+ yield* offer(backgroundTaskChanges, { threadId, tasks });
21469
+ return tasks;
21470
+ });
21471
+ const watchTerminals = (threadId, client, codexThreadId) => gen(function* () {
21472
+ const current = terminalsByThread.get(threadId);
21473
+ if (current?.client === client && current.codexThreadId === codexThreadId) return;
21474
+ if (current?.poll) yield* interrupt(current.poll);
21475
+ const terminals = { client, codexThreadId, tasks: current?.tasks ?? [] };
21476
+ terminalsByThread.set(threadId, terminals);
21477
+ terminals.poll = yield* gen(function* () {
21478
+ while (true) {
21479
+ yield* sleep(TERMINAL_POLL_INTERVAL);
21480
+ const tasks = yield* refreshTerminals(threadId, terminals);
21481
+ if (tasks.length === 0 && !runs.has(threadId)) return;
21482
+ }
21483
+ }).pipe(
21484
+ ensuring$2(
21485
+ sync(() => terminalsByThread.get(threadId) === terminals && terminalsByThread.delete(threadId))
21486
+ ),
21487
+ forkIn(providerScope)
21488
+ );
21489
+ });
21490
+ const stopBackgroundTask = (threadId, taskId) => suspend$2(() => {
21491
+ const terminals = terminalsByThread.get(threadId);
21492
+ if (terminals === void 0) return void_$1;
21493
+ const params2 = {
21494
+ threadId: terminals.codexThreadId,
21495
+ processId: taskId
21496
+ };
21497
+ return terminals.client.request("thread/backgroundTerminals/terminate", params2).pipe(andThen(refreshTerminals(threadId, terminals)), asVoid);
21498
+ });
21318
21499
  const listModels = gen(function* () {
21319
21500
  const client = yield* getClient(null);
21320
21501
  const models = [];
@@ -21446,6 +21627,7 @@ const make$U = gen(function* () {
21446
21627
  const commandOutput = /* @__PURE__ */ new Map();
21447
21628
  const startedTools = /* @__PURE__ */ new Set();
21448
21629
  const openTools = /* @__PURE__ */ new Set();
21630
+ const backgroundable = /* @__PURE__ */ new Set();
21449
21631
  const approvalIdByRpcId = /* @__PURE__ */ new Map();
21450
21632
  const questionIdByRpcId = /* @__PURE__ */ new Map();
21451
21633
  let subagents = subagentsByThread.get(input.threadId);
@@ -21650,6 +21832,10 @@ const make$U = gen(function* () {
21650
21832
  yield* emit({ type: "compaction_updated", compaction: { status: "running" } });
21651
21833
  }
21652
21834
  yield* startTool(params2.item);
21835
+ if (params2.item.type === "commandExecution" && params2.item.processId != null) {
21836
+ backgroundable.add(params2.item.id);
21837
+ yield* watchTerminals(input.threadId, client, thread.id);
21838
+ }
21653
21839
  yield* emitSubagents(applyParentItem(subagents, params2.item, yield* nowIso));
21654
21840
  return false;
21655
21841
  }
@@ -21706,8 +21892,9 @@ const make$U = gen(function* () {
21706
21892
  const params2 = message.params;
21707
21893
  const { status, error } = params2.turn;
21708
21894
  for (const callId of openTools) {
21709
- const output = commandOutput.get(callId) ?? `Turn ${status}`;
21710
- yield* emit({ type: "tool_call_finished", callId, output, isError: true });
21895
+ const isError2 = status !== "completed" || !backgroundable.has(callId);
21896
+ const output = commandOutput.get(callId) ?? (isError2 ? `Turn ${status}` : "Running in the background");
21897
+ yield* emit({ type: "tool_call_finished", callId, output, isError: isError2 });
21711
21898
  }
21712
21899
  openTools.clear();
21713
21900
  yield* emit(
@@ -21748,7 +21935,7 @@ const make$U = gen(function* () {
21748
21935
  yield* end(out);
21749
21936
  })
21750
21937
  );
21751
- const interrupt2 = (threadId) => suspend$2(() => {
21938
+ const interrupt$12 = (threadId) => suspend$2(() => {
21752
21939
  const run2 = runs.get(threadId);
21753
21940
  if (!run2) return void_$1;
21754
21941
  const stop = succeed$5(run2.stop, void 0);
@@ -21792,8 +21979,9 @@ const make$U = gen(function* () {
21792
21979
  copySession,
21793
21980
  listCommands,
21794
21981
  runTurn,
21982
+ backgroundTasks: { changes: fromQueue(backgroundTaskChanges), stop: stopBackgroundTask },
21795
21983
  steer,
21796
- interrupt: interrupt2,
21984
+ interrupt: interrupt$12,
21797
21985
  stopSubagent,
21798
21986
  respondApproval,
21799
21987
  respondQuestion,
@@ -21935,6 +22123,21 @@ const toApprovalRequest = (params2, id, threadId) => ({
21935
22123
  input: toolInput(params2.rawArgs),
21936
22124
  sessionScope: sessionScope(params2)
21937
22125
  });
22126
+ const isBackgrounded = (item) => item.status === "inProgress" && (item.background === true || item.backgroundStatus?.state === "backgrounded");
22127
+ const labelOf = (item) => {
22128
+ const input = toolInput(item.args);
22129
+ const field2 = (name) => isObject(input) && typeof input[name] === "string" ? input[name] : "";
22130
+ return field2("description") || field2("command") || (item.tool ?? "tool");
22131
+ };
22132
+ const backgroundTasksAfter = (previous, item, now2) => {
22133
+ const known = previous.some((task) => task.id === item.itemId);
22134
+ if (item.status !== "inProgress") return known ? previous.filter((task) => task.id !== item.itemId) : previous;
22135
+ if (known || !isBackgrounded(item)) return previous;
22136
+ return [
22137
+ ...previous,
22138
+ { id: item.itemId, kind: item.tool === "bash" ? "shell" : "other", label: labelOf(item), startedAt: now2 }
22139
+ ];
22140
+ };
21938
22141
  const modelLabel = ({ modelId, displayLabel }) => displayLabel !== modelId ? displayLabel : modelId.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
21939
22142
  const toModelInfo = (model) => ({
21940
22143
  id: model.modelId,
@@ -22111,6 +22314,18 @@ const ViewPage = Struct({
22111
22314
  events: ArraySchema(Struct({ method: String$1, params: Unknown2 })),
22112
22315
  nextCursor: NullOr(String$1)
22113
22316
  });
22317
+ const ToolCallFrame = Struct({
22318
+ sessionId: String$1,
22319
+ item: Struct({
22320
+ itemId: String$1,
22321
+ kind: Literal2("toolCall"),
22322
+ status: String$1,
22323
+ tool: optional$7(String$1),
22324
+ args: optional$7(String$1),
22325
+ background: optional$7(Boolean$1),
22326
+ backgroundStatus: optional$7(Struct({ state: String$1 }))
22327
+ })
22328
+ });
22114
22329
  const MAX_TEXT = 500;
22115
22330
  const toQuestion = (question) => ({
22116
22331
  id: question.id,
@@ -22306,6 +22521,34 @@ const make$T = gen(function* () {
22306
22521
  let current;
22307
22522
  let planUsage;
22308
22523
  const decodePlanUsage = decodeUnknownOption(SubscriptionUsage);
22524
+ const decodeToolCall = decodeUnknownOption(ToolCallFrame);
22525
+ const backgroundTaskChanges = yield* unbounded();
22526
+ const threadOf = (sessionId) => [...threadSessions.entries()].find(([, session]) => session === sessionId)?.[0];
22527
+ const setBackgroundTasks = (entry, sessionId, tasks) => {
22528
+ if ((entry.backgroundTasks.get(sessionId) ?? []) === tasks) return;
22529
+ if (tasks.length === 0) entry.backgroundTasks.delete(sessionId);
22530
+ else entry.backgroundTasks.set(sessionId, tasks);
22531
+ const threadId = threadOf(sessionId);
22532
+ if (threadId !== void 0) offerUnsafe(backgroundTaskChanges, { threadId, tasks });
22533
+ };
22534
+ const trackBackgroundTasks = (entry, message) => {
22535
+ if (message.kind === "exit") {
22536
+ for (const sessionId2 of entry.backgroundTasks.keys()) setBackgroundTasks(entry, sessionId2, []);
22537
+ return;
22538
+ }
22539
+ if (message.kind !== "notification") return;
22540
+ if (message.method === "session/closed") {
22541
+ const sessionId2 = message.params?.sessionId;
22542
+ if (sessionId2 !== void 0) setBackgroundTasks(entry, sessionId2, []);
22543
+ return;
22544
+ }
22545
+ if (message.method !== "item/updated" && message.method !== "item/completed") return;
22546
+ const frame = decodeToolCall(message.params);
22547
+ if (isNone(frame)) return;
22548
+ const { sessionId, item } = frame.value;
22549
+ const previous = entry.backgroundTasks.get(sessionId) ?? [];
22550
+ setBackgroundTasks(entry, sessionId, backgroundTasksAfter(previous, item, (/* @__PURE__ */ new Date()).toISOString()));
22551
+ };
22309
22552
  const getEntry = (home) => withPermit(
22310
22553
  hostLock,
22311
22554
  gen(function* () {
@@ -22323,16 +22566,17 @@ const make$T = gen(function* () {
22323
22566
  provide$4(scope2),
22324
22567
  onError(() => close(scope2, void_$2))
22325
22568
  );
22326
- const sessions = /* @__PURE__ */ new Map();
22569
+ const entry = { host, scope: scope2, sessions: /* @__PURE__ */ new Map(), backgroundTasks: /* @__PURE__ */ new Map() };
22327
22570
  yield* host.subscribe((message) => {
22571
+ trackBackgroundTasks(entry, message);
22328
22572
  if (message.kind !== "notification") return;
22329
22573
  if (message.method === "usage/changed") {
22330
22574
  planUsage = getOrElse(decodePlanUsage(message.params), () => planUsage);
22331
22575
  } else {
22332
- trackContext(sessions, message.method, message.params);
22576
+ trackContext(entry.sessions, message.method, message.params);
22333
22577
  }
22334
22578
  }).pipe(provide$4(scope2));
22335
- current = { host, scope: scope2, sessions };
22579
+ current = entry;
22336
22580
  return current;
22337
22581
  })
22338
22582
  );
@@ -22499,6 +22743,7 @@ const make$T = gen(function* () {
22499
22743
  const summaryParts = /* @__PURE__ */ new Map();
22500
22744
  const toolOutput = /* @__PURE__ */ new Map();
22501
22745
  const openTools = /* @__PURE__ */ new Set();
22746
+ const backgroundedTools = /* @__PURE__ */ new Set();
22502
22747
  let context2;
22503
22748
  let compacting = false;
22504
22749
  const decide = (approval, decision) => gen(function* () {
@@ -22624,8 +22869,23 @@ const make$T = gen(function* () {
22624
22869
  input: toolInput(item.args)
22625
22870
  });
22626
22871
  };
22872
+ const backgroundTool = (params2) => gen(function* () {
22873
+ const frame = decodeToolCall(params2);
22874
+ if (isNone(frame)) return;
22875
+ const { item } = frame.value;
22876
+ if (!isBackgrounded(item) || !openTools.has(item.itemId)) return;
22877
+ openTools.delete(item.itemId);
22878
+ toolOutput.delete(item.itemId);
22879
+ backgroundedTools.add(item.itemId);
22880
+ yield* emit({
22881
+ type: "tool_call_finished",
22882
+ callId: item.itemId,
22883
+ output: "Running in the background",
22884
+ isError: false
22885
+ });
22886
+ });
22627
22887
  const finishTool = (item) => gen(function* () {
22628
- if (item.tool === void 0) return;
22888
+ if (item.tool === void 0 || backgroundedTools.has(item.itemId)) return;
22629
22889
  yield* startTool(item);
22630
22890
  openTools.delete(item.itemId);
22631
22891
  yield* emit({
@@ -22735,6 +22995,9 @@ const make$T = gen(function* () {
22735
22995
  }
22736
22996
  return false;
22737
22997
  }
22998
+ case "item/updated":
22999
+ yield* backgroundTool(message.params);
23000
+ return false;
22738
23001
  case "item/delta":
22739
23002
  yield* onDelta(message.params);
22740
23003
  return false;
@@ -22836,6 +23099,20 @@ const make$T = gen(function* () {
22836
23099
  yield* run2.entry.host.command("session/setApprovalMode", { sessionId: run2.sessionId, mode }).pipe(mapError(toAgentError));
22837
23100
  loaded.approvalMode = mode;
22838
23101
  });
23102
+ const stopBackgroundTask = (threadId, taskId) => gen(function* () {
23103
+ const sessionId = threadSessions.get(threadId);
23104
+ if (!current?.host.isAlive() || sessionId === void 0) return;
23105
+ const { host, backgroundTasks } = current;
23106
+ const tasks = backgroundTasks.get(sessionId) ?? [];
23107
+ yield* host.command("task/stop", { sessionId, taskId }).pipe(
23108
+ // Muse 1.4.12 refuses `task/stop` with `invalid_target` for a shell it backgrounded past its yield time,
23109
+ // though `task/stopAll` reaches it. Stopping all is only the same thing when it is the one task.
23110
+ catch_$2(
23111
+ (error) => tasks.length === 1 && tasks[0].id === taskId ? host.command("task/stopAll", { sessionId }) : fail$2(error)
23112
+ ),
23113
+ mapError(toAgentError)
23114
+ );
23115
+ });
22839
23116
  const respondApproval = (requestId, decision) => suspend$2(() => {
22840
23117
  const deferred = approvals.get(requestId);
22841
23118
  return deferred ? succeed$5(deferred, decision) : void_$1;
@@ -22854,6 +23131,7 @@ const make$T = gen(function* () {
22854
23131
  runTurn,
22855
23132
  steer,
22856
23133
  interrupt: interrupt2,
23134
+ backgroundTasks: { changes: fromQueue(backgroundTaskChanges), stop: stopBackgroundTask },
22857
23135
  respondApproval,
22858
23136
  respondQuestion,
22859
23137
  setAccessMode
@@ -39375,6 +39653,7 @@ const make$c = gen(function* () {
39375
39653
  const secretRequests = /* @__PURE__ */ new Map();
39376
39654
  const threadLocks = /* @__PURE__ */ new Map();
39377
39655
  const subagents = /* @__PURE__ */ new Map();
39656
+ const backgroundTasks = /* @__PURE__ */ new Map();
39378
39657
  let seq = 0;
39379
39658
  yield* threads.resetInterrupted;
39380
39659
  yield* messages.closeInterrupted;
@@ -39774,6 +40053,17 @@ const make$c = gen(function* () {
39774
40053
  scope$12
39775
40054
  );
39776
40055
  }
40056
+ for (const provider of Object.values(providers)) {
40057
+ if (provider.backgroundTasks === void 0) continue;
40058
+ yield* forkIn(
40059
+ runForEach(provider.backgroundTasks.changes, ({ threadId, tasks }) => {
40060
+ if (tasks.length === 0) backgroundTasks.delete(threadId);
40061
+ else backgroundTasks.set(threadId, tasks);
40062
+ return push.publish({ type: "thread.backgroundTasks", threadId, tasks });
40063
+ }),
40064
+ scope$12
40065
+ );
40066
+ }
39777
40067
  const requestSecret = (threadId, name, description2) => gen(function* () {
39778
40068
  const turn = activeTurns.get(threadId);
39779
40069
  if (turn === void 0) {
@@ -39878,6 +40168,15 @@ const make$c = gen(function* () {
39878
40168
  const latest = subagents.get(threadId)?.get(subagentId);
39879
40169
  if (latest?.status === "running") yield* updateSubagent2(threadId, { ...latest, status: "stopped", endedAt });
39880
40170
  }),
40171
+ backgroundTasks: (threadId) => sync(() => backgroundTasks.get(threadId) ?? []),
40172
+ stopBackgroundTask: (threadId, taskId) => gen(function* () {
40173
+ const { provider: id } = yield* threads.get(threadId);
40174
+ const tasks = providers[id].backgroundTasks;
40175
+ if (tasks === void 0) {
40176
+ return yield* new AgentError({ provider: id, message: "This agent cannot stop a background task" });
40177
+ }
40178
+ yield* tasks.stop(threadId, taskId);
40179
+ }),
39881
40180
  listCommands: (threadId) => gen(function* () {
39882
40181
  const thread = yield* threads.get(threadId);
39883
40182
  const { cwd } = yield* activeWorkspace(threadId);
@@ -46478,6 +46777,8 @@ const handlers = {
46478
46777
  "secrets.clear": ({ name }) => Secrets.use((secrets) => secrets.clear(name)),
46479
46778
  "subagents.list": ({ threadId }) => AgentRunner.use((runner) => runner.subagents(threadId)),
46480
46779
  "subagents.stop": ({ threadId, subagentId }) => AgentRunner.use((runner) => runner.stopSubagent(threadId, subagentId)),
46780
+ "backgroundTasks.list": ({ threadId }) => AgentRunner.use((runner) => runner.backgroundTasks(threadId)),
46781
+ "backgroundTasks.stop": ({ threadId, taskId }) => AgentRunner.use((runner) => runner.stopBackgroundTask(threadId, taskId)),
46481
46782
  "threads.usage": ({ threadId }) => AgentRunner.use((runner) => runner.usage(threadId)),
46482
46783
  "pullRequests.list": ({ threadId }) => PullRequests.use((pullRequests) => pullRequests.list(threadId)),
46483
46784
  "pullRequests.all": () => PullRequests.use((pullRequests) => pullRequests.listAll),
@@ -4,7 +4,7 @@ import { homedir, hostname } from "node:os";
4
4
  import { dirname, delimiter, basename, join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import QRCode from "qrcode";
7
- import { S as Struct, e as effect, U as Updates, g as gen, u as unsupported, E as Events, t as tryPromise, d as decodeUnknownSync, m as make$1, s as suspend, r as repeat, a as spaced, f as forkScoped, T as Threads, W as Worktrees, b as Terminals, c as forEach, o as orElseSucceed, h as sync, i as isThreadBusy, j as String$1, v as void_, k as andThen, l as matchEffect, n as forkDetach, p as flatMap, q as UsageError, w as USAGE, x as parseCommand, y as serveConfig, z as hydratePath, A as make$2, B as makeAppLayer, C as autoUpdate, D as layer$1, F as provideMerge, G as mergeAll, H as layer$2, I as layer$3, J as provide, K as noKeyring, L as layer$4, M as succeed, N as MinimumLogLevel, O as Settings, R as RemoteAccess, P as pairingUrl, Q as isPortInUse, V as restartCommand } from "./chunks/shellPath-BAeR7gJe.js";
7
+ import { S as Struct, e as effect, U as Updates, g as gen, u as unsupported, E as Events, t as tryPromise, d as decodeUnknownSync, m as make$1, s as suspend, r as repeat, a as spaced, f as forkScoped, T as Threads, W as Worktrees, b as Terminals, c as forEach, o as orElseSucceed, h as sync, i as isThreadBusy, j as String$1, v as void_, k as andThen, l as matchEffect, n as forkDetach, p as flatMap, q as UsageError, w as USAGE, x as parseCommand, y as serveConfig, z as hydratePath, A as make$2, B as makeAppLayer, C as autoUpdate, D as layer$1, F as provideMerge, G as mergeAll, H as layer$2, I as layer$3, J as provide, K as noKeyring, L as layer$4, M as succeed, N as MinimumLogLevel, O as Settings, R as RemoteAccess, P as pairingUrl, Q as isPortInUse, V as restartCommand } from "./chunks/shellPath-Bu35qy-f.js";
8
8
  import { execFile } from "node:child_process";
9
9
  import { promisify } from "node:util";
10
10
  import "node:crypto";
package/out/main/index.js CHANGED
@@ -2,7 +2,7 @@ import { existsSync, renameSync } from "node:fs";
2
2
  import { join, delimiter } from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { Notification, nativeImage, BrowserWindow, ipcMain, app, dialog, shell, protocol, safeStorage, powerMonitor, Menu, net, session } from "electron";
5
- import { h as sync, X as catchDefect, Y as succeed, Z as callback, _ as timeoutOrElse, $ as seconds, a0 as TaggedError, j as String$1, a1 as promise, t as tryPromise, S as Struct, a2 as optional, a3 as RpcCall, a4 as decodeUnknownOption, a5 as EVENT_CHANNEL, a6 as RPC_CHANNEL, a7 as isTrustedSender, g as gen, a8 as getOrUndefined, a9 as dispatch, aa as Environments, p as flatMap, ab as catch_, ac as all$1, ad as map, ae as decodeUnknownEffect, af as RpcMethods, ag as inlineSource, u as unsupported, E as Events, ah as runFork, ai as logWarning, r as repeat, a as spaced, f as forkScoped, U as Updates, s as suspend, e as effect, v as void_, aj as ignore, z as hydratePath, ak as ATTACHMENT_PROTOCOL, al as GITHUB_ASSET_PROTOCOL, am as PROJECT_FILE_PROTOCOL, M as succeed$1, an as Keyring, A as make$1, B as makeAppLayer, ao as isInside, ap as githubAssetId, aq as GitHub, ar as externalUrl, as as projectFileRequest, at as Files, au as BROWSER_PARTITION, av as lockDownWebview, aw as isAllowedNavigation } from "./chunks/shellPath-BAeR7gJe.js";
5
+ import { h as sync, X as catchDefect, Y as succeed, Z as callback, _ as timeoutOrElse, $ as seconds, a0 as TaggedError, j as String$1, a1 as promise, t as tryPromise, S as Struct, a2 as optional, a3 as RpcCall, a4 as decodeUnknownOption, a5 as EVENT_CHANNEL, a6 as RPC_CHANNEL, a7 as isTrustedSender, g as gen, a8 as getOrUndefined, a9 as dispatch, aa as Environments, p as flatMap, ab as catch_, ac as all$1, ad as map, ae as decodeUnknownEffect, af as RpcMethods, ag as inlineSource, u as unsupported, E as Events, ah as runFork, ai as logWarning, r as repeat, a as spaced, f as forkScoped, U as Updates, s as suspend, e as effect, v as void_, aj as ignore, z as hydratePath, ak as ATTACHMENT_PROTOCOL, al as GITHUB_ASSET_PROTOCOL, am as PROJECT_FILE_PROTOCOL, M as succeed$1, an as Keyring, A as make$1, B as makeAppLayer, ao as isInside, ap as githubAssetId, aq as GitHub, ar as externalUrl, as as projectFileRequest, at as Files, au as BROWSER_PARTITION, av as lockDownWebview, aw as isAllowedNavigation } from "./chunks/shellPath-Bu35qy-f.js";
6
6
  import { createRequire } from "node:module";
7
7
  import { execFile, spawn } from "node:child_process";
8
8
  import { access } from "node:fs/promises";
@@ -120,6 +120,8 @@ const routes = {
120
120
  "search.files": thread,
121
121
  "subagents.list": thread,
122
122
  "subagents.stop": thread,
123
+ "backgroundTasks.list": thread,
124
+ "backgroundTasks.stop": thread,
123
125
  "pullRequests.list": thread,
124
126
  "pullRequests.unlink": thread,
125
127
  "pullRequests.create": thread,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hinacode",
3
- "version": "0.1.0-alpha.14",
3
+ "version": "0.1.0-alpha.15",
4
4
  "description": "Run coding agents on this machine and drive them from the HinaCode desktop or phone app",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -17,7 +17,7 @@
17
17
  "type": "module",
18
18
  "main": "./out/main/index.js",
19
19
  "scripts": {
20
- "dev": "node scripts/dev-app-identity.mjs && node scripts/build-resource-monitor.mjs && electron-vite dev",
20
+ "dev": "node scripts/dev-app-identity.ts && node scripts/build-resource-monitor.ts && electron-vite dev",
21
21
  "dev:markdown": "HINACODE_MOCK_CLAUDE=markdown HINACODE_USER_DATA=/tmp/kk-markdown pnpm dev",
22
22
  "build": "electron-vite build",
23
23
  "preview": "electron-vite preview",
@@ -25,10 +25,10 @@
25
25
  "start:xvfb": "DISPLAY=:99 electron-vite preview -- --no-sandbox --disable-gpu --remote-debugging-port=9222",
26
26
  "serve": "electron-vite build && node out/main/daemon.js serve",
27
27
  "paraglide": "paraglide-js compile --project ./project.inlang --outdir ./src/renderer/paraglide --strategy globalVariable baseLocale --silent",
28
- "typecheck": "pnpm paraglide && tsc --noEmit -p tsconfig.node.json && tsc --noEmit -p tsconfig.web.json && tsc --noEmit -p tsconfig.web-test.json && tsc --noEmit -p tsconfig.e2e.json",
28
+ "typecheck": "pnpm paraglide && tsrs --noEmit -p tsconfig.node.json && tsrs --noEmit -p tsconfig.web.json && tsrs --noEmit -p tsconfig.web-test.json && tsrs --noEmit -p tsconfig.e2e.json && tsrs --noEmit -p tsconfig.scripts.json",
29
29
  "lint": "oxlint",
30
- "check:specs": "node scripts/tlc.mjs",
31
- "chart:thread": "node scripts/thread-chart.mjs",
30
+ "check:specs": "node scripts/tlc.ts",
31
+ "chart:thread": "node scripts/thread-chart.ts",
32
32
  "resource-monitor": "tools/resource-monitor/bin/resource-monitor",
33
33
  "format": "oxfmt",
34
34
  "test": "vitest run",
@@ -102,6 +102,7 @@
102
102
  "shadcn": "4.21.4",
103
103
  "sonner": "2.0.8",
104
104
  "tailwindcss": "4.3.3",
105
+ "tsrs": "0.18.0-ts7.1.0-dev.20260929",
105
106
  "tw-shimmer": "^0.4.13",
106
107
  "typescript": "6.0.3",
107
108
  "vite": "7.3.7",