@timqi/pier 0.0.19 → 0.0.20

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.
Files changed (85) hide show
  1. package/dist/agent/config-sync.js +123 -0
  2. package/dist/agent/config.js +95 -3
  3. package/dist/agent/events.js +10 -1
  4. package/dist/agent/pi.js +50 -28
  5. package/dist/config-sync-fetch.js +97 -0
  6. package/dist/config-sync-task.js +59 -0
  7. package/dist/config-sync.js +179 -0
  8. package/dist/core/hub.js +10 -3
  9. package/dist/core/reply.js +12 -2
  10. package/dist/core/router.js +162 -37
  11. package/dist/db.js +6 -0
  12. package/dist/main.js +31 -1
  13. package/dist/tasks/agent.js +11 -22
  14. package/dist/tasks/callbacks.js +1 -1
  15. package/dist/tasks/definitions.js +25 -16
  16. package/dist/tasks/execution.js +11 -3
  17. package/dist/tasks/messages.js +57 -14
  18. package/dist/tasks/routes.js +58 -10
  19. package/dist/tasks/runs.js +0 -5
  20. package/dist/tasks/service.js +9 -4
  21. package/dist/tasks/store.js +45 -0
  22. package/dist/tasks/tool.js +8 -4
  23. package/dist/web/config-sync.js +91 -0
  24. package/dist/web/public/assets/activity-DYo7QS7k.js +5 -0
  25. package/dist/web/public/assets/activity-DYo7QS7k.js.br +0 -0
  26. package/dist/web/public/assets/activity-DYo7QS7k.js.gz +0 -0
  27. package/dist/web/public/assets/{boards-DEMQ51m1.js → boards-CwohTbtv.js} +1 -1
  28. package/dist/web/public/assets/boards-CwohTbtv.js.br +0 -0
  29. package/dist/web/public/assets/boards-CwohTbtv.js.gz +0 -0
  30. package/dist/web/public/assets/{code-DjWvqL94.js → code-p-Tq1bMK.js} +1 -1
  31. package/dist/web/public/assets/{explorer-BTGQ6Syc.js → explorer-50no_DrD.js} +1 -1
  32. package/dist/web/public/assets/explorer-50no_DrD.js.br +0 -0
  33. package/dist/web/public/assets/explorer-50no_DrD.js.gz +0 -0
  34. package/dist/web/public/assets/{ghostty-web-D8CLFi_l.js → ghostty-web-Bvhh3ZFk.js} +1 -1
  35. package/dist/web/public/assets/ghostty-web-Bvhh3ZFk.js.br +0 -0
  36. package/dist/web/public/assets/ghostty-web-Bvhh3ZFk.js.gz +0 -0
  37. package/dist/web/public/assets/{index-yNocr797.css → index-DuZ2vERd.css} +1 -1
  38. package/dist/web/public/assets/index-DuZ2vERd.css.br +0 -0
  39. package/dist/web/public/assets/index-DuZ2vERd.css.gz +0 -0
  40. package/dist/web/public/assets/index-WrsNstrb.js +79 -0
  41. package/dist/web/public/assets/index-WrsNstrb.js.br +0 -0
  42. package/dist/web/public/assets/index-WrsNstrb.js.gz +0 -0
  43. package/dist/web/public/assets/runs-BAXZF-6r.js +1 -0
  44. package/dist/web/public/assets/runs-BAXZF-6r.js.br +0 -0
  45. package/dist/web/public/assets/runs-BAXZF-6r.js.gz +0 -0
  46. package/dist/web/public/assets/settings-BmNXgRne.js +6 -0
  47. package/dist/web/public/assets/settings-BmNXgRne.js.br +0 -0
  48. package/dist/web/public/assets/settings-BmNXgRne.js.gz +0 -0
  49. package/dist/web/public/assets/task-runs-CpgHxFLf.js +3 -0
  50. package/dist/web/public/assets/task-runs-CpgHxFLf.js.br +0 -0
  51. package/dist/web/public/assets/task-runs-CpgHxFLf.js.gz +0 -0
  52. package/dist/web/public/assets/tasks-DybtogPF.js +4 -0
  53. package/dist/web/public/assets/tasks-DybtogPF.js.br +0 -0
  54. package/dist/web/public/assets/tasks-DybtogPF.js.gz +0 -0
  55. package/dist/web/public/assets/{terminal-zLyOvGto.js → terminal-m2_WYu5W.js} +2 -2
  56. package/dist/web/public/assets/terminal-m2_WYu5W.js.br +0 -0
  57. package/dist/web/public/assets/terminal-m2_WYu5W.js.gz +0 -0
  58. package/dist/web/public/index.html +13 -2
  59. package/dist/web/public/index.html.br +0 -0
  60. package/dist/web/public/index.html.gz +0 -0
  61. package/dist/web/server.js +65 -60
  62. package/package.json +2 -2
  63. package/skills/pier-tasks/SKILL.md +14 -9
  64. package/dist/web/public/assets/activity-BsoWK6vt.js +0 -5
  65. package/dist/web/public/assets/activity-BsoWK6vt.js.br +0 -0
  66. package/dist/web/public/assets/activity-BsoWK6vt.js.gz +0 -0
  67. package/dist/web/public/assets/boards-DEMQ51m1.js.br +0 -0
  68. package/dist/web/public/assets/boards-DEMQ51m1.js.gz +0 -0
  69. package/dist/web/public/assets/explorer-BTGQ6Syc.js.br +0 -0
  70. package/dist/web/public/assets/explorer-BTGQ6Syc.js.gz +0 -0
  71. package/dist/web/public/assets/ghostty-web-D8CLFi_l.js.br +0 -0
  72. package/dist/web/public/assets/ghostty-web-D8CLFi_l.js.gz +0 -0
  73. package/dist/web/public/assets/index-BFzmvpGX.js +0 -78
  74. package/dist/web/public/assets/index-BFzmvpGX.js.br +0 -0
  75. package/dist/web/public/assets/index-BFzmvpGX.js.gz +0 -0
  76. package/dist/web/public/assets/index-yNocr797.css.br +0 -0
  77. package/dist/web/public/assets/index-yNocr797.css.gz +0 -0
  78. package/dist/web/public/assets/settings-DSTKXN2o.js +0 -6
  79. package/dist/web/public/assets/settings-DSTKXN2o.js.br +0 -0
  80. package/dist/web/public/assets/settings-DSTKXN2o.js.gz +0 -0
  81. package/dist/web/public/assets/tasks-Dy1SCAE_.js +0 -4
  82. package/dist/web/public/assets/tasks-Dy1SCAE_.js.br +0 -0
  83. package/dist/web/public/assets/tasks-Dy1SCAE_.js.gz +0 -0
  84. package/dist/web/public/assets/terminal-zLyOvGto.js.br +0 -0
  85. package/dist/web/public/assets/terminal-zLyOvGto.js.gz +0 -0
@@ -0,0 +1,6 @@
1
+ import{A as e,B as t,C as n,D as r,E as i,G as a,I as o,M as s,N as c,O as l,S as u,V as d,_ as f,b as p,c as m,f as h,g,h as _,j as v,k as y,l as b,m as x,o as S,p as C,q as w,r as T,t as E,v as D,w as O,x as k,y as A}from"./index-WrsNstrb.js";import{n as j,t as M}from"./code-p-Tq1bMK.js";var N={display_information:{name:`Pier`,description:`Coding agent sessions in Slack threads`,background_color:`#262626`},features:{bot_user:{display_name:`Pier`,always_online:!1},app_home:{messages_tab_enabled:!0,messages_tab_read_only_enabled:!1}},oauth_config:{scopes:{bot:[`chat:write`,`reactions:write`,`channels:history`,`channels:read`,`groups:history`,`groups:read`,`im:history`,`im:write`,`mpim:history`,`mpim:read`,`mpim:write`,`users:read`,`files:read`,`files:write`]}},settings:{event_subscriptions:{bot_events:[`message.channels`,`message.groups`,`message.im`,`message.mpim`]},interactivity:{is_enabled:!0},socket_mode_enabled:!0,token_rotation_enabled:!1}},P=()=>`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(N))}`,F=()=>p(`Getting a bot token`,[`Open [@BotFather](https://t.me/BotFather) in Telegram.`,"Send `/newbot`, pick a display name, then a username ending in `bot`.","Copy the token it prints (`123456789:AA…`) and paste it here.","Send `/setprivacy` → `Disable` if the bot should see plain group messages. Left enabled it only ever receives mentions, replies and commands — the usual reason a bot looks dead in a group.","Send `/setjoingroups` → `Enable`, then add the bot to your group or forum."]),I=(e=`left`)=>p(`Enabling topics on a group`,["In Telegram open the group → `Edit` → turn on `Topics`. Owner only; group size no longer matters.","The group becomes a forum supergroup and the existing chat becomes its `General` topic.","Make the bot an admin with `Manage Topics`. That is the one right topic creation needs — without it Pier logs the failure and answers in General instead.","Send one message in the group so Pier discovers it, then enable it under `Chats` below.","After that, a message in General opens its own topic with its own session. A reply, or anything starting with `/`, stays where it was sent."],e);function L(){let e=g(`Create Slack app ↗`,!0);e.classList.add(`mt-1`,`w-fit`),e.onclick=()=>window.open(P(),`_blank`,`noreferrer`);let t=c(`btn w-fit text-[12.5px]`,()=>JSON.stringify(N,null,2));return p(`Creating a Slack app`,[y(`Opens Slack with every scope, event and Socket Mode already filled in. Pick your workspace → Create.`,e),"`Install to Workspace` → allow. Then `OAuth & Permissions` → copy the bot token (`xoxb-…`) into the field above.","`Basic Information` → `App-Level Tokens` → `Generate` with scope `connections:write`. Paste that `xapp-…` token below. The manifest cannot mint this one for you.","In Slack, invite the bot where you want it: `/invite @Pier`. It answers in threads only, so it never adds noise to the channel.",y(`Prefer to paste it yourself? Create the app from a manifest and use this:`,t)])}var R=()=>p(`What agent access allows`,["Gives agent sessions a `slack` tool: read a channel's history for a time range, read one thread, and post, edit or delete a message.",`Editing and deleting reach only what Pier's own bot posted — Slack refuses either on anyone else's message.`,`Pier performs every call itself — the bot token is never given to the agent, and Slack's own membership rules still apply, so the bot reaches only channels it was invited to.`,`Every read fetches live from Slack — Pier keeps no message archive.`,`This includes sessions started by tasks and subagents. Switch it off if an agent should never post to your workspace on its own.`,`The tool is only given to sessions opened while Slack is connected and this is on, so an unused tool costs no context. A session opened earlier keeps it, and a call made after you switch it off is refused with the reason.`]),z=(e=`left`)=>p(`How Slack threads work here`,[`Pier never posts in a channel's main flow. A message in the channel is answered in *its own thread*; a message in a thread is answered in that thread.`,`Each thread is its own Pi session, so one channel hosts many parallel sessions.`,`The same applies in a DM: every new message you send there starts its own thread and its own session. Reply *inside* a thread to continue that conversation.`,"Inside a thread Pier already owns, no `@mention` is needed — continuing that thread is addressing it.","Commands are bare words after a mention: `@bot settings`, `@bot stop`, `@bot bind <code>`. Slack's client swallows an unregistered `/command` before it ever reaches an app."],e),ee=()=>p(`Creating a Feishu app`,["On [open.feishu.cn](https://open.feishu.cn/app) create a 企业自建应用 (custom app). `Credentials & Basic Info` shows the App ID (`cli_…`) and App Secret — paste both here.","`Add Features` → enable **Bot** (机器人).","`Permissions` (权限管理), add: `im:message` (read messages), `im:message:send_as_bot` (send), `im:resource` (attachments, both directions), `im:message.reactions:create` + `:read` + `:delete` (the 👀 receipt), `im:chat:readonly` (chat names for this page), `contact:user.base:readonly` (speaker names).","`Events & Callbacks` → set the mode to **长连接 (long connection)** — no public URL needed. Under Events subscribe `im.message.receive_v1` (接收消息); Callbacks gain `card.action.trigger` automatically once cards are sent, add it if listed.",`**Publish a version** (版本管理与发布 → 创建版本 → 申请发布). Nothing above takes effect until this is approved — the usual reason a configured bot stays silent.`,`Add the bot to a group (群设置 → 群机器人), or DM it directly.`]),B=(e=`left`)=>p(`How Lark topics work here`,[`Pier never posts in a chat's main flow. A message in the chat is answered in *its own topic* (话题); a message inside a topic is answered there.`,`Each topic is its own Pi session, so one group hosts many parallel sessions.`,`The same applies in a DM: every new message starts its own topic and its own session. Reply *inside* a topic to continue that conversation.`,`Inside a topic Pier already owns, no @mention is needed — continuing that topic is addressing it.`,"Commands are slash words: `/stop`, `/settings`, `/bind <code>`. A bare @mention with nothing else also opens the settings panel."],e),V=[[`telegram`,`Telegram`],[`slack`,`Slack`],[`lark`,`Lark`]],H=(e,t)=>o(`span`,`flex items-center gap-1.5 text-[13px] text-neutral-400`,o(`span`,``,e),t),te={dm:`bg-sky-50 text-sky-700 ring-sky-200`,group:`bg-neutral-100 text-neutral-600 ring-neutral-200`,forum:`bg-violet-50 text-violet-700 ring-violet-200`},U=`pier.channelsPlatform`;function ne(e){let t=localStorage.getItem(U),n=V.some(([e])=>e===t)?t:`telegram`,r=null,c=[],p=o(`div`,`ml-auto flex items-center gap-1.5 text-[11.5px]`),m=o(`div`,`sticky top-0 z-30 flex items-center gap-1 border-b border-neutral-200 bg-white px-4 py-2`,p),h=o(`div`,`px-4 py-5`);e.append(o(`div`,`min-h-0 flex-1 overflow-y-auto bg-neutral-50/60`,m,h));function v(){m.replaceChildren(...V.map(([e,t])=>u(t,e===n,()=>{y&&M(),n=e,localStorage.setItem(U,e),N()})),p)}let y,b=!1,S=null;function w(e){if(p.replaceChildren(),e!==`clean`){if(p.className=`ml-auto flex items-center gap-1.5 text-[11.5px] ${C[e]}`,e===`saving`)p.append(o(`span`,`spinner`),o(`span`,``,`Saving…`));else if(e===`saved`)p.append(o(`span`,``,`✓`),o(`span`,``,`Saved`)),setTimeout(()=>{p.textContent?.includes(`Saved`)&&w(`clean`)},2e3);else{let e=_(`Retry`,`cursor-pointer underline`);e.onclick=M,p.append(o(`span`,``,`⚠`),o(`span`,``,`Save failed`),e)}}}function O(){w(`saving`),clearTimeout(y),y=setTimeout(M,500)}let k=e=>t=>{e(t),O()};async function j(e){b=!0,w(`saving`);try{w((await a(`/api/channels/${e.platform}`,e.config,`PUT`)).ok?`saved`:`failed`)}catch{w(`failed`)}finally{b=!1;let e=S;S=null,e&&j(e)}}function M(){if(clearTimeout(y),y=void 0,!r)return;let e={platform:n,config:r};b?S=e:j(e)}async function N(){if(!c.length){let e=await d(`/api/models`,`Could not load the model catalog`);e.ok&&(c=e.value)}let e=await d(`/api/channels/${n}`,`Failed to load`);if(!e.ok){r=null,v(),h.replaceChildren(D(e.error));return}r=e.value,w(`clean`),W()}function P(e){let t=n===`slack`,r=n===`lark`,a=i(e.token,t?`xoxb-…`:r?`cli_…`:`123456789:AA…`,k(t=>e.token=t),!0),o=i(e.appToken,r?``:`xapp-…`,k(t=>e.appToken=t),!0),s=E(e.cwd,`(pier process cwd)`,k(t=>e.cwd=t));return f(`Connection`,t?`Pier connects over Socket Mode; no public URL or webhook needed.`:r?`Pier connects over Feishu's WebSocket long connection; no public URL or webhook needed.`:`Pier polls Telegram for updates; no public URL or webhook needed.`,l(`Enabled`,`Start the adapter when Pier boots.`,e.enabled,k(t=>{e.enabled=t,v()})),A(r?`App ID`:`Bot token`,a,{hint:`Stored locally, shown masked once saved.`,help:n===`telegram`?F():t?L():ee()}),...t?[A(`App-level token`,o,{hint:`Opens the Socket Mode connection. Needs connections:write.`}),l(`Agent access`,`Let agent sessions read channel history and post through the slack tool. Off makes the tool refuse; inbound messages are unaffected.`,e.agentTool,k(t=>e.agentTool=t),R())]:[],...r?[A(`App Secret`,o,{hint:`From Credentials & Basic Info, beside the App ID.`})]:[],A(`Default working directory`,s.el,{hint:`Where sessions this channel opens start.`}))}function ne(e){return f(`Defaults for new chats`,`Copied into a group the first time the bot sees it; changing them here never touches a group that already exists. DMs are always bound-users-only.`,l(`Require mention in groups`,`Ignore group messages that do not @mention or reply to the bot.`,e.requireMention,k(t=>e.requireMention=t)),l(`Require bound user`,`Only users bound with a code below can drive the agent.`,e.requireBind,k(t=>e.requireBind=t)),...n===`slack`?[H(`Thread mode: always on`,z())]:n===`lark`?[H(`Thread mode: always on`,B())]:[l(`Topic mode`,`In a forum group, each new request opens its own topic and its own session.`,e.topicMode,k(t=>e.topicMode=t),I())],T(`Model & reasoning`,e,c,k(t=>{e.model=t.model,e.thinking=t.thinking,W()})))}function re(e){let t=o(`span`,`font-mono text-[15px] font-semibold tracking-widest`),r=o(`div`,`hidden items-center gap-2 rounded-lg bg-indigo-50 px-3 py-2 text-[12.5px] text-indigo-800`,t,o(`span`,`text-[11.5px] text-indigo-500`,`DM the bot /bind <code> · expires in 10 min`)),i=g(`Generate bind code`);i.onclick=async()=>{let e=await fetch(`/api/channels/${n}/bind-code`,{method:`POST`});if(!e.ok)return;let{code:i}=await e.json();t.textContent=i,r.classList.replace(`hidden`,`flex`)};let a=o(`div`,`flex flex-col`);e.users.length||a.append(D(`No bound users yet.`));for(let t of e.users){let e=_(`Remove`,`cursor-pointer text-[11.5px] text-neutral-400 opacity-0 transition-opacity hover:text-red-600 group-hover:opacity-100`);e.onclick=async()=>{await fetch(`/api/channels/${n}/users/${encodeURIComponent(t.id)}`,{method:`DELETE`}),await N()},a.append(o(`div`,`group flex items-center gap-2.5 border-b border-neutral-100 py-2 last:border-0`,o(`span`,`flex h-6 w-6 flex-none items-center justify-center rounded-full bg-neutral-100 text-[11px] font-semibold text-neutral-500`,(t.name[0]??`?`).toUpperCase()),o(`span`,`min-w-0 flex-1 truncate text-[13px] text-neutral-700`,t.name),o(`span`,`flex-none font-mono text-[11.5px] text-neutral-400`,t.id),e))}return f(`Bound users`,`A code is single-use and expires; redeeming it in a DM binds that account.`,a,o(`div`,`flex flex-col gap-2`,i,r))}function ie(e,t){let r=o(`div`,`rounded-xl border px-3.5 py-3 transition-colors ${t.enabled?`border-neutral-200 bg-white`:`border-neutral-200 bg-neutral-50/60`}`),i=o(`div`,`flex items-center gap-2`,o(`span`,`min-w-0 flex-1 truncate text-[13px] font-medium ${t.enabled?`text-neutral-800`:`text-neutral-400`}`,t.name||t.id),x(t.kind,te[t.kind]),o(`span`,`flex-none font-mono text-[11px] text-neutral-400`,t.id)),a=l(``,``,t.enabled,k(e=>{t.enabled=e,W()}));a.classList.add(`flex-none`,`items-center`),i.append(a);let s=o(`div`,`mt-3 flex flex-wrap items-center gap-x-6 gap-y-2`);t.kind===`dm`?s.append(o(`span`,`text-[13px] text-neutral-400`,n===`telegram`?`Direct message · bound users only, mention and topics not applicable`:`Direct message · bound users only, mention not applicable`)):s.append(l(`Require mention`,``,t.requireMention,k(e=>t.requireMention=e)),l(`Require bind`,``,t.requireBind,k(e=>t.requireBind=e)),n===`slack`?H(`Thread mode: always on`,z(`right`)):n===`lark`?H(`Thread mode: always on`,B(`right`)):t.kind===`forum`?l(`Topic mode`,``,t.topicMode,k(e=>t.topicMode=e),I(`right`)):H(`Topic mode: forum groups only`,I(`right`)));let u=E(t.cwd,``,k(e=>t.cwd=e)),d=o(`div`,`mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2`,A(`Working directory`,u.el),T(`Model & reasoning`,t,c,k(e=>{t.model=e.model,t.thinking=e.thinking,W()})));return r.append(i,s,d),r}function ae(e){let t=o(`div`,`flex flex-col gap-2.5`);return e.chats.length?t.append(...e.chats.map(t=>ie(e,t))):t.append(D(`None yet. Chats appear here after the bot sees a message in them.`)),f(n===`slack`?`Channels`:`Chats`,`Discovered from inbound traffic — no platform reliably lists every chat a bot is in.`,t)}function W(){if(!r)return;v();let e=o(`div`,`mx-auto flex max-w-3xl flex-col gap-4`);e.append(P(r),ne(r),re(r),ae(r)),h.replaceChildren(e)}return s(e,()=>void N(),()=>{y&&M()})}function re(){let e=o(`div`,`min-h-0 min-w-0 flex-1 overflow-y-auto p-4`),n=o(`div`,`mx-auto flex max-w-3xl min-w-0 flex-col gap-4`),r=o(`p`,`text-[12px] break-words`),s=o(`section`,`flex min-w-0 flex-col gap-3 border-b border-neutral-200 pb-4`),u=o(`section`,`flex min-w-0 flex-col gap-3`);n.append(o(`h2`,`text-[14px] font-semibold text-neutral-700`,`Configuration sync`),r,s,u),e.append(n);let f=null,p=!1,m=!1,h=0,_=``,v=!1,y=e=>e?new Date(e).toLocaleString():`Never`;async function b(){let e=h,t=await d(`/api/config-sync`,`Could not load configuration sync`,{cache:`no-store`});if(!(m||e!==h)){if(!t.ok){O(r,`failed`,t.error);return}f=t.value,v||(_=f.sourceUrl),C()}}async function x(e){if(!p){++h,p=!0,C(),O(r,`saving`,`Working...`);try{let n=await a(`/api/config-sync`,{action:e,...e===`subscribe`?{url:_}:{}});if(!n.ok)throw Error(await t(n,`Configuration sync failed`));let i=await n.json();f=i,v=!1,_=i.sourceUrl,O(r,`saved`,i.result??`Saved`)}catch(e){O(r,`failed`,e instanceof Error?e.message:`Configuration sync failed`),await b()}finally{p=!1,m||C()}}}function S(e,t){let n=g(e);return n.disabled=p,n.onclick=()=>{x(t)},n}function C(){if(!f||m)return;if(s.replaceChildren(o(`h3`,`text-[13px] font-medium text-neutral-700`,`Publish`)),f.publishedPath){let e=`${f.publicUrl||window.location.origin}${f.publishedPath}`,t=i(e,``,()=>{},!0);t.readOnly=!0,t.setAttribute(`aria-label`,`Sharing URL`),s.append(t,o(`div`,`flex flex-wrap items-center gap-2`,c(`btn text-[12px]`,()=>e),S(`Revoke link`,`revoke`)))}else s.append(o(`div`,``,S(`Generate link`,`publish`)));s.append(o(`p`,`text-[12px] text-neutral-500`,`Anyone with the link can read shared prompts. Provider connections and credentials stay private.`));let e=i(_,`https://example.com/config-sync/...`,e=>{_=e,v=!0},!0);e.type=`url`,e.setAttribute(`aria-label`,`Configuration source URL`),e.disabled=p||f.enabled;let t=l(`Automatic sync`,``,f.enabled,e=>{x(e?`subscribe`:`pause`)});t.querySelector(`input`).disabled=p;let n=o(`div`,`flex flex-wrap items-center gap-3`,t);f.enabled&&n.append(S(`Sync now`,`sync`)),u.replaceChildren(o(`h3`,`text-[13px] font-medium text-neutral-700`,`Source`),A(`Source URL`,e),n);let r=o(`dl`,`grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1 text-[12px]`);for(let[e,t]of[[`Last checked`,y(f.lastChecked)],[`Last applied`,y(f.lastApplied)],[`Next check`,f.enabled?y(f.nextRunAt):`Paused`]])r.append(o(`dt`,`text-neutral-500`,e),o(`dd`,`min-w-0 break-words text-neutral-700`,t));if(u.append(r),f.error&&u.append(o(`p`,`text-[12px] break-words text-red-600`,f.error)),f.needsReload&&u.append(o(`p`,`text-[12px] text-amber-700`,`Reload pending; retry synchronization.`)),f.taskId){let e=o(`a`,`text-[12px] text-indigo-600 hover:underline`,`Sync task history`);e.href=`#/tasks/${encodeURIComponent(f.taskId)}`,u.append(e)}}b();let w=setInterval(()=>{!p&&!v&&b()},15e3);return{el:e,dispose:()=>{m=!0,clearInterval(w)}}}async function ie(e,n){let r;try{r=await a(`/api/settings`,e,`PUT`)}catch(e){return{outcome:{state:`failed`,text:`Could not save: ${String(e)}`}}}if(!r.ok)return{outcome:{state:`failed`,text:await t(r,`could not save`)}};let i;try{i=await r.json()}catch(e){return{outcome:{state:`failed`,text:`Saved, but the answer could not be read: ${String(e)}`}}}return i.toolsSync?.state===`refused`?{outcome:{state:`failed`,text:`Saved, but nothing will install it: ${i.toolsSync.reason}`},answer:i}:i.toolsSync?.state===`waiting`?{outcome:{state:`saved`,text:`Saved — a sync is already running; this change goes in the run right after it.`},answer:i}:{outcome:{state:`saved`,text:n},answer:i}}function ae(e,t){return e.enabled?{body:{tool:{name:e.name,on:!1}},saved:`Switched ${e.name} off — the next run uninstalls it. Remove it again once its binary is gone.`}:{body:{customTools:t.filter(t=>t.name!==e.name)},saved:`Removed ${e.name}.`}}function W(e,n){let r=`global`,c=null,u=0,f=0,p=``,m=null,g=[],_=``,y=null,S=null,C=()=>{S?.dispose(),S=null},w=()=>{C(),++f,S=re(),L.replaceChildren(S.el)},T=[],E=()=>g.filter(e=>e.kind===`extension`),D=e=>e.source===`binary`&&e.custom===!0,k=()=>g.filter(e=>e.kind===`tool`),N=document.createElement(`select`);N.className=`select w-full rounded-md border border-neutral-300 px-2 py-1 text-[12.5px] focus:border-indigo-400 focus:outline-none`,N.onchange=()=>{C(),r=N.value,c=null,K.clear(),te()};let P=o(`div`,`flex flex-none flex-col gap-1 border-b border-neutral-200 px-3 pb-2.5 pt-2`);P.append(o(`span`,`text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,`Scope`),N);let F=o(`div`,`min-h-0 flex-1 overflow-y-auto py-1`),I=o(`nav`,`flex w-64 flex-none flex-col border-r border-neutral-200 text-[13px] max-md:max-h-48 max-md:w-full max-md:border-r-0 max-md:border-b`);I.append(P,F);let L=o(`div`,`flex min-w-0 flex-1 flex-col`),R=o(`div`,`flex min-h-0 flex-1 max-md:flex-col`);R.append(I,L),e.append(R);let z=(e=``)=>`?scope=${encodeURIComponent(r)}${e}`;async function ee(){if(r!==`global`){g=[],_=``;return}let e=await d(`/api/settings`,`could not be loaded`,{cache:`no-store`});if(!e.ok){g=[],_=e.error;return}B(e.value),_=``}function B(e){g=e.catalog,T=e.customTools,y=e.toolsTaskId}async function V(e,t){let{outcome:n,answer:r}=await ie(e,t);return r&&(B(r),J(m)),n}function H(e,t){let n={name:e,on:t};return g.find(t=>t.name===e)?.source===`binary`?{tool:n}:{extension:n}}async function te(){let e=++u;f++;let[t]=await Promise.all([d(`/api/config${z()}`,`failed to load config`,{cache:`no-store`}),ee()]);if(e!==u)return;if(!t.ok){J(null),Y(t.error);return}let n=t.value;r===`global`&&n.dir&&(p=n.dir,pe()),m=n,J(n),c?c.type===`sync`&&w():se()}function U(e){return o(`div`,`px-3 pb-0.5 pt-2.5 text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e)}let ne=()=>{let e=o(`span`,`flex-none rounded bg-neutral-100 px-1 text-[10px] font-semibold uppercase tracking-wide text-neutral-500`,`link`);return e.title=`Reached through a symlink`,e},W=()=>o(`span`,`flex-none rounded bg-emerald-50 px-1 text-[10px] font-semibold uppercase tracking-wide text-emerald-700`,`on`);function G(e,t,n,r,i=0,a){let s=o(`button`,`flex w-full cursor-pointer items-center gap-1.5 py-1 pr-3 text-left hover:bg-neutral-100 ${t?`bg-indigo-50 hover:bg-indigo-50`:``} ${n?`text-neutral-400`:``}`);return s.append(o(`span`,`truncate`,e)),a&&s.append(a),s.style.paddingLeft=`${20+i*14}px`,s.title=e,s.onclick=r,s}function oe(e){let t={files:[],dirs:new Map,link:!0};for(let n of e){let e=n.name.split(`/`),r=t;for(let t of e.slice(0,-1)){let e=r.dirs.get(t);e||r.dirs.set(t,e={files:[],dirs:new Map,link:!0}),e.link&&=n.link,r=e}r.files.push({name:e[e.length-1],link:n.link})}return t}let K=new Set;function q(e,t,n,r,i,a){let s=[];for(let[c,l]of t.dirs){let t=n?`${n}/${c}`:c,u=`${e}:${t}`,d=document.createElement(`details`);d.open=K.has(u),d.ontoggle=()=>d.open?K.add(u):K.delete(u);let f=o(`summary`,`flex cursor-pointer select-none items-center gap-1 truncate py-1 pr-3 hover:bg-neutral-100`);f.style.paddingLeft=`${20+r*14}px`,f.title=t,f.append(o(`span`,`chev`,`▶`),o(`span`,`truncate text-neutral-600`,c)),l.link&&f.append(ne()),d.append(f,...q(e,l,t,r+1,i,a)),s.push(d)}for(let o of t.files){let t={type:`resource`,kind:e,name:n?`${n}/${o.name}`:o.name};s.push(G(o.name,i(t),!1,()=>a(t),r,o.link?ne():void 0))}return s}function J(e){if(!e){F.replaceChildren();return}let t=e=>JSON.stringify(e)===JSON.stringify(c),n=t=>{C(),c=t,J(e),t.type===`file`?ce(t.name):t.type===`bundled`?ue(t.name):t.type===`tools`?$():t.type===`sync`?w():fe(t.kind,t.name)},i=[];if(r===`global`){let e={type:`sync`};i.push(U(`Instance`),G(`Configuration sync`,t(e),!1,()=>n(e)))}i.push(U(`Files`));for(let r of e.files){let e={type:`file`,name:r.name};i.push(G(r.name,t(e),!r.exists,()=>n(e)))}if(r===`global`){i.push(U(`bundled with Pier`)),_?i.push(o(`p`,`py-1 pl-5 pr-3 text-[12.5px] text-red-600`,_)):E().length||i.push(o(`p`,`py-1 pl-5 pr-3 text-[12.5px] text-neutral-400`,`none`));for(let e of E()){let r={type:`bundled`,name:e.name};i.push(G(e.name,t(r),!1,()=>n(r),0,e.enabled?W():void 0))}if(!_){let e={type:`tools`},r=k().filter(e=>e.enabled).length;i.push(G(`command-line tools`,t(e),!1,()=>n(e),0,r?W():void 0))}}for(let r of[`extensions`,`skills`]){i.push(U(`${r} (read-only)`));let a=e.resources[r];a.length||i.push(o(`p`,`py-1 pl-5 pr-3 text-[12.5px] text-neutral-400`,`none`)),i.push(...q(r,oe(a),``,0,t,n))}F.replaceChildren(...i)}function se(){L.replaceChildren(o(`p`,`px-4 py-3 text-[13px] text-neutral-400`,`Select a file to edit, or browse extensions and skills.`))}function Y(e){L.replaceChildren(o(`p`,`px-4 py-3 text-[13px] text-red-600`,e))}let X=(e,...t)=>o(`div`,`flex flex-none items-center gap-3 border-b border-neutral-200 px-4 py-2`,o(`span`,`font-mono text-[12.5px] text-neutral-500`,e),...t);async function ce(e){let n=++f,r=await d(`/api/config/files/${encodeURIComponent(e)}${z()}`,`failed to load ${e}`,{cache:`no-store`});if(!r.ok){n===f&&Y(r.error);return}if(n!==f)return;let{content:i}=r.value,s=i,c=o(`span`,`text-[11.5px] text-neutral-400`,``),l=o(`button`,`btn btn-primary ml-auto text-[12.5px]`,`Save`),u=document.createElement(`textarea`);u.className=`block min-h-0 flex-1 resize-none bg-white p-4 font-mono text-[13px] leading-relaxed focus:outline-none`,u.spellcheck=!1,u.value=i;let p=async()=>{if(l.disabled)return;let n=u.value;l.disabled=!0,O(c,`saving`,`saving…`);try{let r=await a(`/api/config/files/${encodeURIComponent(e)}${z()}`,{content:n,expected:s},`PUT`);if(!r.ok)return O(c,`failed`,await t(r,`save failed`));let i=await r.json();s=i.content,u.value===n?(u.value=i.content,O(c,`saved`,`saved — applies to new sessions`)):O(c,`idle`,`saved; newer changes are unsaved`)}catch(e){O(c,`failed`,`save failed: ${String(e)}`)}finally{l.disabled=!1}};l.onclick=()=>void p(),u.onkeydown=e=>{(e.metaKey||e.ctrlKey)&&e.key===`s`&&(e.preventDefault(),p())},u.oninput=()=>{O(c,`idle`,`unsaved changes`)},L.replaceChildren(X(e,c,l),u),u.focus()}function le(e){if(!y)return null;let t=o(`a`,`text-indigo-600 hover:underline`,e);return t.href=`#/tasks/${encodeURIComponent(y)}`,t}let Z=()=>{let e=o(`a`,`text-indigo-600 hover:underline`,`ubix`);return e.href=`https://github.com/timqi/ubix`,e.target=`_blank`,e.rel=`noreferrer`,e};function Q(e){if(e.source!==`binary`)return``;let{spec:t,error:n,installed:r,version:i,path:a}=e.binary;return n?`${t} — ${n}`:r?`${t} — ${i??`unknown version`} at ${a??`an unknown path`}`:`${t} — not installed`}function ue(e,t){f++;let n=g.find(t=>t.name===e&&t.kind===`extension`);if(!n)return Y(`unknown extension: ${e}`);let r=o(`span`,`text-[11.5px] text-neutral-400`,``);t&&O(r,t.state,t.text);let i=le(`every run of the update task`);L.replaceChildren(X(n.name,o(`span`,`ml-auto text-[11px] uppercase tracking-wide text-neutral-400`,n.source===`binary`?`installed by Pier`:`ships with Pier`)),o(`div`,`flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4`,o(`p`,`max-w-2xl text-[13px] leading-relaxed text-neutral-600`,n.summary),o(`dl`,`flex max-w-2xl flex-col gap-1.5`,...(n.source===`bundled`?n.adds:[]).flatMap(e=>[o(`dt`,`font-mono text-[12px] text-neutral-700`,e.name),o(`dd`,`text-[12px] leading-snug text-neutral-500`,`needs ${e.needs}`)]),...n.source===`binary`?[o(`dt`,`font-mono text-[12px] text-neutral-700`,`binary`),o(`dd`,`font-mono text-[12px] leading-snug ${n.binary.error?`text-red-600`:`text-neutral-500`}`,Q(n))]:[]),l(`Enabled`,n.source===`binary`?`Installed into Pier's own bin directory, first on the PATH every session, task and terminal inherits; it registers its own Pi extension. Switching it off uninstalls both.`:`Loaded from inside Pier — nothing is installed and no update touches your own extensions. A session mid-turn keeps the tools it started with; the next message picks this up.`,n.enabled,t=>void de(n.name,t,t=>ue(e,t))),o(`p`,`max-w-2xl text-[12px] leading-snug text-neutral-400`,...n.source===`binary`?i?[`A daily task installs and updates it — its history is `,i,`.`]:[`Its installs run as the daily update task.`]:[`An extension of your own that registers the same tool wins: this copy stands down and says so in the log.`]),r))}function $(e,t={name:``,toml:``}){f++;let n=o(`span`,`text-[11.5px] text-neutral-400`,``);e&&O(n,e.state,e.text);let r=k(),a=le(`the update task`),s=e=>{let t=o(`div`,`flex min-w-0 flex-1 flex-col gap-0.5`,o(`span`,`flex items-center gap-2 text-[13px] text-neutral-700`,o(`span`,`font-mono`,e.name),...D(e)?[x(`yours`,`bg-neutral-50 text-neutral-500 ring-neutral-200`)]:[]),o(`span`,`text-[11.5px] leading-snug text-neutral-400`,e.summary||Q(e)),...e.summary?[o(`span`,`font-mono text-[11px] leading-snug ${e.source===`binary`&&e.binary.error?`text-red-600`:`text-neutral-400`}`,Q(e))]:[]),n=l(``,``,e.enabled,t=>void de(e.name,t,e=>$(e))),r=o(`button`,`btn text-[12px] text-neutral-500 hover:text-red-600`,`Remove`);return r.onclick=()=>{r.disabled=!0;let t=ae(e,T);V(t.body,t.saved).then(e=>$(e))},o(`div`,`flex max-w-2xl items-start gap-3 border-b border-neutral-100 py-2.5 last:border-0`,t,...D(e)?[r]:[],n)},c={...t},u=o(`span`,`font-mono text-[12px] text-neutral-500`,`[tools.<name>]`),d=i(c.name,`claude`,e=>{c.name=e,u.textContent=`[tools.${e.trim()||`<name>`}]`},!0),p=document.createElement(`textarea`);p.className=`${h} h-24 resize-y font-mono leading-snug`,p.spellcheck=!1,p.value=c.toml,p.placeholder=`spec = "github:owner/repo"
2
+ exe = "tool"`,p.oninput=()=>c.toml=p.value;let m=o(`button`,`btn btn-primary text-[12.5px]`,`Add`);m.onclick=()=>{let e={name:c.name.trim(),toml:c.toml.trim()};if(!e.name||!e.toml)return O(n,`failed`,`A custom tool needs a name and a block with a spec line.`);m.disabled=!0,V({customTools:[...T,e],tool:{name:e.name,on:!0}},`Added ${e.name} — installing now.`).then(e=>$(e,e.state===`failed`?c:void 0))},L.replaceChildren(X(`command-line tools`,o(`span`,`ml-auto text-[11px] uppercase tracking-wide text-neutral-400`,`installed by Pier`)),o(`div`,`flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4`,o(`p`,`max-w-2xl text-[12.5px] leading-relaxed text-neutral-500`,`Pier writes no downloader: `,Z(),` does the work — a declarative installer that resolves a spec like `,o(`span`,`font-mono text-[11.5px]`,`github:owner/repo`),` to the right release asset for this machine, verifies it, and upgrades in place. Pier bootstraps it, generates its config from the switches below, and keeps its files under Pier's own directory — your own ubix setup is untouched.`),_?o(`p`,`max-w-2xl text-[12.5px] text-red-600`,_):o(`div`,`flex max-w-2xl flex-col`,...r.map(s)),o(`div`,`flex max-w-2xl flex-col gap-2 border-t border-neutral-200 pt-4`,o(`span`,`text-[12.5px] font-medium text-neutral-600`,`Add one of your own`),A(`Name`,d),A(`The block Pier writes under the header`,p,{hint:`A line that opens a section of its own is refused, because it could rewrite the rest of the file.`}),o(`div`,`flex items-center gap-3`,u,m)),o(`p`,`max-w-2xl text-[12px] leading-snug text-neutral-400`,...a?[`Installs and daily updates run as `,a,` — output, failures and all.`]:[`Switching one on creates the daily task that installs it and keeps it current.`]),n))}async function de(e,t,n){let r=g.find(t=>t.name===e);n(await V(H(e,t),r?.source===`binary`?t?`Saved — installing now; watch the run.`:`Saved — uninstalling in the next run.`:`Saved — sessions take it on their next message.`))}async function fe(e,t){let n=++f,r=await d(`/api/config/resource${z(`&kind=${e}&name=${encodeURIComponent(t)}`)}`,`failed to load ${t}`,{cache:`no-store`});if(!r.ok){n===f&&Y(r.error);return}if(n!==f)return;let{content:i}=r.value,a=i.split(`
3
+ `);a.at(-1)===``&&a.pop();let s=await b(t);n===f&&L.replaceChildren(X(t,o(`span`,`ml-auto text-[11px] uppercase tracking-wide text-neutral-400`,`read-only`)),o(`div`,`min-h-0 flex-1 overflow-auto`,M(j(a),s)))}function pe(){N.replaceChildren(new Option(p?`Global (${p})`:`Global`,`global`),...n().map(e=>new Option(`${v(e)} — ${e}`,e))),[...N.options].some(e=>e.value===r)||(r=`global`),N.value=r}return s(e,()=>{pe(),te()},C)}var G=e=>`${e.provider}/${e.id}`,oe=[`hardest reasoning — architecture, gnarly debugging`,`long autonomous implementation runs`,`balanced default — implementation, review`,`cheap & fast — listings, extraction, simple checks`,`cross-vendor second opinion`];function K(){let e=[],r=[],i=!1,s=o(`span`,`text-[11.5px]`,``),c=g(`Save menu`,!0),l=o(`div`,`flex min-w-0 flex-col gap-2`),u=o(`div`,`flex items-center gap-2`),p=o(`div`,`mx-auto flex w-full max-w-3xl min-w-0 flex-col gap-6`);function h(){i=!0,O(s,`idle`,`unsaved changes`)}function _(t){let r=k(t.note??``);r.classList.remove(`w-full`),r.classList.add(`min-w-0`,`flex-1`),r.placeholder=`why this one — pick a preset or write your own`,r.setAttribute(`list`,`model-menu-notes`),r.oninput=()=>{t.note=r.value,h()};let i=n([[`thinking: model default`,``],...m.map(e=>[`thinking: ${w(e)}`,e])],t.thinking??``);i.classList.replace(`w-full`,`w-44`),i.classList.add(`flex-none`),i.onchange=()=>{i.value?t.thinking=i.value:delete t.thinking,h()};let a=g(`Remove`);a.classList.add(`flex-none`),a.onclick=()=>{e=e.filter(e=>e!==t),h(),y()};let s=o(`span`,`w-52 flex-none truncate font-mono text-[12px] text-neutral-700`,G(t));return s.title=G(t),o(`div`,`flex min-w-0 items-center gap-2 rounded-lg border border-neutral-200 bg-white px-3 py-2 shadow-2xs max-md:flex-wrap`,s,i,r,a)}function v(){let t=r.filter(t=>!e.some(e=>G(e)===G(t))),i=n(t.map(e=>[G(e),G(e)]),t[0]?G(t[0]):``);i.classList.replace(`w-full`,`flex-1`),i.classList.add(`min-w-0`);let a=g(`+ Pin model`);a.classList.add(`flex-none`,`whitespace-nowrap`),a.disabled=t.length===0,a.onclick=()=>{let n=t.find(e=>G(e)===i.value);n&&(e.push({...n}),h(),y())},u.replaceChildren(i,a)}function y(){l.replaceChildren(...e.length?e.map(_):[D(`Nothing pinned — every picker shows the curated catalog as is.`)]),v()}async function b(){O(s,`saving`,`saving…`);let n=e.map(({provider:e,id:t,thinking:n,note:r})=>({provider:e,id:t,...n?{thinking:n}:{},...r?.trim()?{note:r.trim()}:{}})),r=await a(`/api/settings`,{modelMenu:n},`PUT`);if(!r.ok)return O(s,`failed`,await t(r,`Could not save`));e=(await r.json()).modelMenu,i=!1,O(s,`saved`,`Saved — agents see it on their next models call.`),y()}c.onclick=()=>void b();function x(){i||(async()=>{let[t,n]=await Promise.all([d(`/api/settings`,`Could not load the menu`),d(`/api/models`,`Could not load the model catalog`)]);if(!t.ok)return O(s,`failed`,t.error);e=t.value.modelMenu,r=n.ok?n.value:[],s.textContent=``,y()})()}let S=o(`datalist`,``);return S.id=`model-menu-notes`,S.append(...oe.map(e=>new Option(e))),p.append(f(`Model menu`,`Which few models this deployment favors, each with a usual reasoning level and one line of intent. Pinned entries lead every model picker, and agents delegating work match your notes against the task instead of guessing ids.`,A(`Pinned models`,l,{hint:`The note is what an agent matches a task against — say when to reach for it, not what it is.`}),A(`Add`,u,{hint:`The list is the live catalog — only models that exist right now can be pinned.`}),o(`div`,`flex items-center gap-3`,c,s),S)),{el:p,load:x}}var q=(e,t)=>{let n;try{n=new URL(e)}catch{return null}if(n.protocol!==`http:`&&n.protocol!==`https:`)return null;let r=o(`a`,`text-indigo-600 hover:underline`,t);return r.href=n.href,r.target=`_blank`,r.rel=`noreferrer`,r};function J(e,n,r,i){let s=document.createElement(`dialog`);s.className=`m-auto w-[min(32rem,92vw)] rounded-lg border border-neutral-200 bg-white p-0 shadow-xl backdrop:bg-black/30`;let l=o(`div`,`flex flex-col gap-2`),u=o(`div`,`flex flex-col gap-2`),d=o(`p`,`text-[12.5px] text-neutral-400`,`Starting…`),f=g(`Cancel`),p=(e,t)=>{d.className=`text-[12.5px] ${C[e]}`,d.textContent=t};s.append(o(`div`,`border-b border-neutral-200 px-4 py-2.5 text-[14px] font-semibold`,n),o(`div`,`flex max-h-[65vh] flex-col gap-3 overflow-y-auto px-4 py-3`,l,u,d),o(`div`,`flex justify-end border-t border-neutral-200 px-4 py-2.5`,f)),document.body.append(s),s.showModal();let m=e.id,h=e.state,_,v,y=new Set,b=!1,x=!1,S=async e=>{if(!x){if(e&&h===`running`){x=!0,f.disabled=!0;try{let e=await a(`/api/providers/flows/${m}/cancel`,{});if(!e.ok&&e.status!==404){p(`failed`,await t(e,`Could not cancel authentication flow`));return}}catch(e){p(`failed`,`Could not cancel authentication flow: ${String(e)}`);return}finally{x=!1,f.disabled=!1}}clearTimeout(_),s.close()}};f.onclick=()=>void S(!0),s.oncancel=e=>{e.preventDefault(),S(!0)},s.onclose=()=>{b=!0,clearTimeout(_),s.remove()};let w=e=>{if(e.type===`auth_url`){let t=o(`div`,`flex flex-col gap-1 text-[12.5px] text-neutral-600`);return e.instructions&&t.append(o(`p`,``,e.instructions)),t.append(q(e.url,`Open authorization page`)??o(`span`,`text-red-600`,`Invalid authorization URL`)),t}if(e.type===`device_code`){let t=o(`div`,`flex flex-col gap-2 text-[12.5px] text-neutral-600`);return t.append(o(`div`,`flex items-center gap-2`,o(`code`,`font-mono text-[17px] font-semibold text-neutral-800`,e.userCode),c(`btn text-[11px]`,()=>e.userCode))),t.append(q(e.verificationUri,`Open verification page`)??o(`span`,`text-red-600`,`Invalid verification URL`)),t}let t=o(`div`,`text-[12.5px] text-neutral-600`,e.message);if(e.type===`info`)for(let n of e.links??[]){let e=q(n.url,n.label??n.url);e&&t.append(` `,e)}return t},T=(e,n)=>{v=n.id;let r;if(n.type===`select`){let e=document.createElement(`select`);e.append(...n.options.map(e=>new Option(e.description?`${e.label} — ${e.description}`:e.label,e.id))),r=e}else{let e=k(``,n.type===`secret`?`password`:`text`);e.placeholder=n.placeholder??``,e.autocomplete=`off`,r=e}r.className=`${r.tagName===`SELECT`?`select `:``}w-full rounded-lg border border-neutral-300 bg-white px-2.5 py-1.5 text-[12.5px] focus:border-indigo-400 focus:outline-none`;let i=g(`Continue`,!0);i.type=`submit`;let s=o(`form`,`flex flex-col gap-2`,o(`label`,`text-[12.5px] font-medium text-neutral-700`,n.message),r,o(`div`,`flex justify-end`,i));s.onsubmit=o=>{o.preventDefault(),i.disabled=!0,(async()=>{try{let i=await a(`/api/providers/flows/${e.id}/respond`,{promptId:n.id,value:r.value});if(b)return;if(!i.ok){p(`failed`,await t(i,`Could not submit response`));return}y.add(n.id),v=void 0,u.replaceChildren(),p(`saving`,`Waiting for provider…`)}catch(e){b||p(`failed`,`Could not submit response: ${String(e)}`)}finally{i.disabled=!1}})()},u.replaceChildren(s),r.focus()},E=e=>{h=e.state,l.replaceChildren(...e.events.map(w));let t=e.prompt&&!y.has(e.prompt.id)?e.prompt:void 0;if(t?.id!==v&&(t?T(e,t):(v=void 0,u.replaceChildren())),e.state===`running`){p(`saving`,t?`Waiting for your response.`:`Waiting for provider…`);return}clearTimeout(_),u.replaceChildren(),e.state===`succeeded`?p(`saved`,`${r} configured.`):p(`failed`,e.state===`cancelled`?`Cancelled.`:e.error??`Authentication failed.`),f.textContent=`Close`,f.onclick=()=>void S(!1),e.state===`succeeded`&&i()},D=async()=>{if(!(b||h!==`running`))try{let e=await fetch(`/api/providers/flows/${m}`,{cache:`no-store`});if(b)return;if(!e.ok){p(`failed`,await t(e,`Authentication status unavailable`)),e.status===404?h=`failed`:_=setTimeout(()=>void D(),1e3);return}E(await e.json()),h===`running`&&(_=setTimeout(()=>void D(),500))}catch(e){if(b)return;p(`failed`,`Authentication status unavailable: ${String(e)}`),_=setTimeout(()=>void D(),1e3)}};E(e),h===`running`&&(_=setTimeout(()=>void D(),500))}var se=[`anthropic`,`openai`,`openai-codex`,`google`,`openrouter`,`deepseek`],Y=[[`OpenAI Chat Completions`,`openai-completions`],[`OpenAI Responses`,`openai-responses`],[`Anthropic Messages`,`anthropic-messages`],[`Google Generative AI`,`google-generative-ai`]],X=`__custom__`;async function ce(e){let r=g(`Add provider`,!0);r.classList.add(`ml-auto`);let i=o(`div`,`flex flex-none items-center gap-3 rounded-t-xl border-b border-neutral-200/70 bg-neutral-50/70 px-4 py-2`,o(`h2`,`text-[13px] font-semibold text-neutral-700`,`Providers`),r),s=o(`div`,`min-h-0 flex-1 overflow-y-auto`);e.replaceChildren(i,s);let c=[],l=``,u=async()=>{s.replaceChildren(o(`p`,`px-4 py-3 text-[13px] text-neutral-400`,`Loading…`));try{let[e,t]=await Promise.all([d(`/api/providers`,`Could not load providers`,{cache:`no-store`}),d(`/api/models`,`the model catalog could not be read`,{cache:`no-store`})]);if(c=t.ok?t.value:[],l=t.ok?``:t.error,!e.ok){s.replaceChildren(D(e.error));return}let n=e.value;r.onclick=()=>Z(n,void 0,u),_(n)}catch(e){s.replaceChildren(D(`Could not load providers: ${String(e)}`))}},f=async e=>{if(window.confirm(`Remove the stored credential for ${e.name}?`))try{let n=await a(`/api/providers/${encodeURIComponent(e.id)}/logout`,{});if(!n.ok){window.alert(await t(n,`Could not remove credential`));return}await u()}catch(e){window.alert(`Could not remove credential: ${String(e)}`)}},p=e=>[...new Set([...(e.models??[]).map(e=>e.id),...c.filter(t=>t.provider===e.id).map(e=>e.id)])],m=(e,t)=>o(`div`,`flex flex-col gap-1`,o(`span`,`text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e),o(`pre`,`max-h-56 overflow-auto whitespace-pre-wrap break-all rounded-md bg-neutral-50 p-2 font-mono text-[11.5px] leading-relaxed text-neutral-600`,t)),h=async(e,n)=>{try{let r=await a(`/api/providers/${encodeURIComponent(e)}/check`,{model:n});return r.ok?await r.json():await t(r,`Could not test`)}catch(e){return`Could not test: ${String(e)}`}},_=e=>{let t=e.filter(e=>e.configured);if(!t.length){s.replaceChildren(D(`No providers configured.`));return}s.replaceChildren(...t.map(t=>{let r=o(`div`,`min-w-0 flex-1`,o(`div`,`truncate text-[13px] font-medium text-neutral-700`,t.name),o(`div`,`truncate font-mono text-[11px] text-neutral-400`,t.id)),i=t.stored===`api_key`?`API key`:t.stored===`oauth`?`OAuth`:t.source??`configured`,a=t.endpoint??`Default endpoint`,s=o(`div`,`flex min-w-32 flex-col items-start gap-1`,x(`configured`,`bg-emerald-50 text-emerald-700 ring-emerald-200`),o(`span`,`max-w-48 truncate text-[11px] text-neutral-500`,i),o(`span`,`max-w-48 truncate text-[11px] text-neutral-400`,a));s.title=a;let c=o(`span`,`text-[11.5px]`,``),d=o(`div`,`hidden flex-col gap-2 px-4 pb-3`,c),_=o(`div`,`flex flex-wrap justify-end gap-1.5`),v=p(t);if(!v.length)O(c,`idle`,l||`No models to test: none are configured here.`),d.classList.replace(`hidden`,`flex`);else{let e=n([[`Model to test…`,``],...v.map(e=>[e,e])],``);e.classList.add(`max-w-52`,`text-[12px]`);let r=g(`Test`);r.disabled=!0,e.onchange=()=>r.disabled=!e.value,r.onclick=()=>{let n=e.value;r.disabled=!0,d.replaceChildren(c),d.classList.replace(`hidden`,`flex`),O(c,`saving`,`asking ${n}…`),h(t.id,n).then(e=>{if(r.disabled=!1,typeof e==`string`)return O(c,`failed`,e);O(c,e.ok?`saved`:`failed`,`${e.model} ${e.ok?`answered`:`did not answer`} in ${e.ms} ms`),d.append(m(`sent`,e.request||`(the request was never made)`),m(e.ok?`answered`:`replied`,e.response))})},_.append(e,r)}if(t.builtin||t.api&&t.models){let n=g(`Edit`);n.onclick=()=>Z(e,t,u),_.append(n)}if(t.stored){let e=g(`Remove credential`);e.onclick=()=>void f(t),_.append(e)}return o(`div`,`border-b border-neutral-100`,o(`div`,`grid grid-cols-[minmax(8rem,1fr)_minmax(8rem,auto)_minmax(9rem,auto)] items-center gap-3 px-4 py-2.5 max-sm:grid-cols-[1fr_auto]`,r,s,_),d)}))};await u()}function le(e,t){let n=t.filter(e=>!e.configured&&e.methods.length&&(e.builtin||e.api!==void 0&&e.models!==void 0)),r=(t,n)=>{if(!n.length)return;let r=document.createElement(`optgroup`);r.label=t,r.append(...n.map(e=>new Option(e.name,e.id))),e.append(r)};r(`Common`,se.flatMap(e=>n.filter(t=>t.id===e))),r(`More providers`,n.filter(e=>e.builtin&&!se.includes(e.id)).sort((e,t)=>e.name.localeCompare(t.name))),r(`Custom providers`,n.filter(e=>!e.builtin).sort((e,t)=>e.name.localeCompare(t.name))),e.append(new Option(`Custom provider…`,X))}function Z(e,n,i){let s=document.createElement(`dialog`);s.className=`m-auto w-[min(32rem,92vw)] rounded-lg border border-neutral-200 bg-white p-0 shadow-xl backdrop:bg-black/30`;let c=document.createElement(`select`);c.className=`${h} select`,n||le(c,e);let l=k(),u=k(),d=k(),f=document.createElement(`select`);f.className=`${h} select`,f.append(...Y.map(([e,t])=>new Option(e,t)));let p=r(``,4);p.placeholder=`model-id
4
+ another-model-id`;let m=document.createElement(`input`);m.type=`checkbox`;let _=document.createElement(`select`);_.className=`${h} select`;let v=o(`div`,`flex flex-col gap-4`),y=o(`span`,`text-[11.5px] text-red-600`,``),b=g(`Cancel`),x=g(n?`Save`:`Add`,!0);x.type=`submit`;let S=()=>n??e.find(e=>e.id===c.value),C=()=>{let e=S(),t=e?!e.builtin:c.value===X;l.value=e?.id??``,l.disabled=n!==void 0,u.value=e?.name??``,d.value=e?.endpoint??``,f.value=e?.api??`openai-completions`,p.value=e?.models?.map(e=>e.id).join(`
5
+ `)??``;let r=e?.models?.map(e=>e.reasoning)??[];m.checked=r.length?r.every(Boolean):!e,m.indeterminate=r.some(Boolean)&&!r.every(Boolean);let i=[];e?.configured&&i.push(new Option(`Keep current authentication`,``));let a=e?.methods??[{type:`api_key`,name:`API key`}];for(let t of a.filter(t=>e?.builtin!==!1||t.type===`api_key`))i.push(new Option(t.name,t.type));_.replaceChildren(...i);let s=[];n||s.push(A(`Provider`,c)),t?s.push(A(`Provider ID`,l),A(`Display name`,u),A(`Endpoint`,d),A(`API format`,f),A(`Models`,p),A(`Model capabilities`,o(`label`,`flex items-center gap-2 text-[12.5px] text-neutral-600`,m,o(`span`,``,`Reasoning`)))):(d.placeholder=`Provider default`,s.push(A(`Endpoint`,d))),s.push(A(`Authentication`,_)),v.replaceChildren(...s)};c.onchange=C,C();let w=o(`form`,`flex flex-col gap-4 px-4 py-3`,v,o(`div`,`flex items-center justify-end gap-2`,y,b,x)),T=!1;b.onclick=()=>{T||s.close()},s.oncancel=e=>{T&&e.preventDefault()},w.onsubmit=e=>{if(e.preventDefault(),T)return;y.textContent=``;let n=S(),r=(n?!n.builtin:c.value===X)?{kind:`custom`,id:l.value.trim(),...u.value.trim()?{name:u.value.trim()}:{},endpoint:d.value.trim(),api:f.value,models:[...new Set(p.value.split(`
6
+ `).map(e=>e.trim()).filter(Boolean))].map(e=>({id:e,reasoning:m.indeterminate?n?.models?.find(t=>t.id===e)?.reasoning??m.checked:m.checked}))}:{kind:`builtin`,id:n.id,...d.value.trim()?{endpoint:d.value.trim()}:{}},o=_.value||null;T=!0,x.disabled=!0,b.disabled=!0,(async()=>{try{let e=await a(`/api/providers/setup`,{setup:r,authType:o});if(!e.ok){y.textContent=await t(e,`Could not configure provider`);return}if(s.close(),e.status===202){let t=_.selectedOptions[0]?.textContent??`Authentication`;J(await e.json(),r.id,t,()=>void i())}else await i()}catch(e){y.textContent=`Could not configure provider: ${String(e)}`}finally{T=!1,x.disabled=!1,b.disabled=!1}})()},s.append(o(`div`,`border-b border-neutral-200 px-4 py-2.5 text-[14px] font-semibold`,n?`Edit ${n.name}`:`Add provider`),w),s.onclose=()=>s.remove(),document.body.append(s),s.showModal(),(n?d:c).focus()}var Q=[[`models`,`Models`],[`files`,`Agent`],[`channels`,`Channels`],[`instance`,`Instance`],[`security`,`Security`]],ue=e=>Q.some(([t])=>t===e),$=`pier.settingsTopic`;function de(e){return[/\bEdg\//.test(e)?`Edge`:/\b(Firefox|Chrome|Safari)\/[\d.]+/.exec(e)?.[1],/\(([^;)]+)/.exec(e)?.[1]?.trim()].filter(Boolean).join(` · `)||e||`unknown client`}function fe(n,r,i){let c=localStorage.getItem($)??void 0,l=ue(c)?c:`models`,p=o(`header`,`flex h-10 flex-none items-center gap-3 border-b border-neutral-200 bg-white px-4 max-md:hidden`,o(`span`,`font-medium`,`Settings`)),m=o(`div`,`tabstrip bg-white`);function h(){m.replaceChildren(...Q.map(([e,t])=>u(t,e===l,()=>i(e))))}let _=k();_.placeholder=`https://pier.example.com`,_.autocomplete=`off`;let v=o(`span`,`text-[11.5px]`,``),y=g(`Save`,!0);async function b(){O(v,`saving`,`saving…`);let e=await a(`/api/settings`,{publicUrl:_.value},`PUT`);if(!e.ok)return O(v,`failed`,await t(e,`Could not save`));let{publicUrl:n}=await e.json();_.value=n,O(v,`saved`,n?`Saved — boards link as ${n}/p/<slug>-<token>/`:`Cleared.`)}y.onclick=()=>void b(),_.onkeydown=e=>{e.key===`Enter`&&b()};let C=f(`Public URL`,`Where this Pier is reached from outside — the proxy's address, not the port it listens on.`,A(`Base URL`,_,{hint:`Agents read it to hand you a clickable board link instead of a path. Nothing here changes what Pier serves; leave it empty if Pier is only reachable locally.`}),o(`div`,`flex items-center gap-3`,y,v)),w=k(``,`password`),T=k(``,`password`),E=k(``,`password`);for(let e of[w,T,E])e.autocomplete=`off`;let j=o(`span`,`text-[11.5px]`,``),M=g(`Change password`,!0);async function N(){if(T.value!==E.value)return O(j,`failed`,`The two new passwords differ.`);O(j,`saving`,`changing…`);let e=await a(`/api/password`,{current:w.value,next:T.value});if(!e.ok)return O(j,`failed`,await t(e,`Could not change the password`));for(let e of[w,T,E])e.value=``;O(j,`saved`,`Changed. Sign in again with the new password.`),location.href=`/login`}M.onclick=()=>void N(),E.onkeydown=e=>{e.key===`Enter`&&N()};let P=f(`Password`,`One shared password guards every page and API route. Changing it signs out every signed-in browser, this one included.`,A(`Current password`,w),A(`New password`,T,{hint:`At least 10 characters.`}),A(`Repeat new password`,E),o(`div`,`flex items-center gap-3`,M,j)),F=g(`Reload`,!0),I=o(`span`,`text-[11.5px]`,``);F.onclick=()=>{F.disabled=!0,O(I,`saving`,`reloading…`),(async()=>{let e=await a(`/api/reload`,{});if(F.disabled=!1,!e.ok)return O(I,`failed`,await t(e,`Could not reload`));let{recycled:n,busy:r}=await e.json(),i=n?`Recycled ${n} session(s).`:`No idle session needed it.`,o=r?` ${r} still mid-turn — they take it when the turn ends.`:``;O(I,r?`idle`:`saved`,i+o)})()};let L=f(`Reload configuration`,`Re-reads channel configuration and lets go of idle sessions, so the next message opens them with the current agent files, skills and credentials. Saving here does this on its own — use it after something outside the Console changed a file.`,o(`div`,`flex items-center gap-3`,F,I)),R=o(`div`,`flex flex-col gap-2`),z=o(`span`,`text-[11.5px]`,``);async function ee(e,n){O(z,`saving`,`signing out…`);try{let r=await a(e,{});if(r.ok)return!0;O(z,`failed`,await t(r,n))}catch(e){O(z,`failed`,`${n}: ${String(e)}`)}return!1}let B=g(`Sign out`);B.onclick=()=>{B.disabled=!0,ee(`/logout`,`Could not sign out`).then(e=>{e?location.href=`/login`:B.disabled=!1})};function V(t){R.replaceChildren(...t.map(t=>{let n=g(t.current?`This browser`:`Sign out`);n.disabled=t.current,n.onclick=()=>{n.disabled=!0,ee(`/api/devices/${encodeURIComponent(t.id)}/signout`,`Could not sign it out`).then(e=>{if(!e)return void(n.disabled=!1);O(z,`saved`,`Signed out.`),H()})};let r=o(`div`,`flex min-w-0 flex-col`,o(`span`,`truncate text-[12.5px] text-neutral-700`,de(t.agent)));return r.title=t.agent,r.append(o(`span`,`truncate text-[11.5px] text-neutral-400`,`${t.ip} · seen ${e(t.seenAt)} · signed in ${e(t.createdAt)}`)),o(`div`,`flex items-center justify-between gap-3 rounded-lg border border-neutral-200 px-3 py-2`,r,n)}))}async function H(){let e=await d(`/api/devices`,`Could not load signed-in devices`);if(!e.ok){R.replaceChildren(D(e.error));return}V(e.value)}let te=f(`Signed-in devices`,`One row per browser holding a session. Signing one out invalidates its cookie immediately; sessions expire on their own 7 days after last use.`,R,o(`div`,`flex items-center gap-3`,B,z)),U=o(`div`,`mx-auto flex max-w-2xl flex-col gap-6`,C,S(),L),re=e=>o(`div`,`hidden min-h-0 flex-1 overflow-y-auto bg-neutral-50/60`,o(`div`,`px-4 py-5`,e)),ie=K(),ae=o(`div`,`mx-auto flex w-full min-w-0 max-w-3xl flex-col rounded-xl border border-neutral-200 bg-white shadow-xs`),G=o(`section`,`hidden min-h-0 flex-1 flex-col`),oe=ne(G),q=o(`section`,`hidden min-h-0 flex-1 flex-col`),J=W(q,r);function se(){(async()=>{let e=await d(`/api/settings`,`Could not load settings`);if(!e.ok)return O(v,`failed`,e.error);_.value=e.value.publicUrl,v.textContent=``})()}let Y=o(`div`,`mx-auto flex max-w-2xl flex-col gap-6`),X=e=>Y.replaceChildren(e,P,te);async function le(){j.textContent=``,z.textContent=``,H();let e=await d(`/api/secrets`,`Could not load key status`);if(!e.ok){X(D(e.error));return}Z(e.value)}function Z(e,n){let r=e.state===`locked`,i=o(`span`,`text-[11.5px]`,``);n&&O(i,`saved`,n);let s=o(`div`,`flex items-center gap-2`,x(e.state,r?`bg-red-50 text-red-700 ring-red-200`:`bg-emerald-50 text-emerald-700 ring-emerald-200`),o(`span`,`text-[12.5px] text-neutral-600`,r?`Stored credentials cannot be read until the key is unlocked.`:e.mode===`vt`?`Key mode: vt:// — unlocking takes one vt approval per process start.`:`Key mode: file — the key sits raw in master.key; switch to vt:// to require an approval.`)),c=o(`a`,`text-indigo-600 hover:underline`,`vt`);c.href=`https://github.com/timqi/vt`,c.target=`_blank`,c.rel=`noreferrer`;let l=[s,o(`p`,`text-[12px] leading-snug text-neutral-500`,c,` is a small local KMS: it keeps the key wrapped and releases it only on an explicit approval — Touch ID on a Mac, a phone passkey on a headless host. Pier only stores the vt:// record, so master.key alone unlocks nothing.`)];if(r){l.push(o(`p`,`text-[12.5px] leading-snug text-red-600`,e.reason??`No reason reported.`));let n=g(`Unlock`,!0);n.onclick=()=>{O(i,`saving`,`unlocking… (vt mode waits on your approval)`),(async()=>{let e=await a(`/api/secrets/unlock`,{});if(!e.ok)return O(i,`failed`,await t(e,`Could not unlock`));Z(await e.json(),`Unlocked — channels are starting.`)})()},l.push(o(`div`,`flex items-center gap-3`,n,i))}else{let n=async(e,n,r)=>{if(!window.confirm(n))return;O(i,`saving`,e===`vt`?`rotating… (vt asks for an approval)`:`rotating…`);let o=await a(`/api/secrets/rotate`,{mode:e});if(!o.ok)return O(i,`failed`,await t(o,`Could not rotate`));Z(await o.json(),r)},r=e.mode??`file`,s=g(`Rotate key`,!0);s.onclick=()=>void n(r,`Generate a new master key? Stored credentials stay valid; the old key stops working.`,`Rotated.`);let c=r===`vt`?`file`:`vt`,u=g(c===`vt`?`Switch to vt://`:`Switch to file`);u.onclick=()=>void n(c,c===`vt`?`Move the master key into vt? Every process start will then wait on a vt approval.`:`Store the master key raw in master.key? Anyone who can read the file can read every credential.`,c===`vt`?`Switched to vt:// mode.`:`Switched to file mode.`),l.push(o(`div`,`flex items-center gap-3`,s,u,i))}if(r||e.mode===`vt`){let e=o(`pre`,`hidden overflow-x-auto rounded-lg bg-neutral-50 p-3 text-[11.5px] leading-snug text-neutral-700`),t=g(`vt doctor`);t.onclick=()=>{t.disabled=!0,e.classList.remove(`hidden`),e.textContent=`running vt doctor…`,(async()=>{let n=await d(`/api/secrets/doctor`,`Could not run vt doctor`);e.textContent=n.ok?n.value.report:n.error,t.disabled=!1})()},l.push(o(`div`,`flex items-center gap-3`,t),e)}X(f(`Master key`,`Seals every credential Pier stores (channel tokens, API keys). Rotating rewraps the key file; no stored data is rewritten.`,...l))}let fe=re(U),pe=re(o(`div`,`flex flex-col gap-6`,ae,ie.el)),me=re(Y),he=[[`instance`,fe,se],[`models`,pe,()=>{ce(ae),ie.load()}],[`security`,me,()=>void le()]];n.append(p,m,fe,pe,G,q,me);function ge(e){ue(e)&&(l=e),localStorage.setItem($,l),h();for(let[e,t,n]of he){let r=e===l;t.classList.toggle(`hidden`,!r),r&&n()}l===`channels`?oe.show():oe.hide(),l===`files`?J.show():J.hide()}return s(n,ge)}export{fe as createSettingsView};
@@ -0,0 +1,3 @@
1
+ import{F as e,I as t,U as n,V as r,g as i}from"./index-WrsNstrb.js";var a=e=>e===null?`-`:new Date(e).toLocaleString(),o=t=>t.startedAt===null?`-`:e((t.finishedAt??Date.now())-t.startedAt),s=e=>e.state===`succeeded`&&e.matched===!1?`No match`:e.state,c=e=>e.trigger.type===`manual`?`Manual`:e.trigger.type===`cron`?`${e.trigger.expression} (${e.trigger.timezone})`:`Every ${e.trigger.intervalSeconds}s · ${e.trigger.mode}`,l=e=>e.action.type===`agent`?`Agent · ${e.action.session.mode}`:e.action.type===`bash`?`Bash`:e.action.type===`system`?`System`:`Task`;function u(e,n){let r=t(`div`,`grid max-w-4xl grid-cols-[6rem_minmax(0,1fr)] gap-x-5 gap-y-3 p-4 text-[13px] md:grid-cols-[9.375rem_minmax(0,1fr)]`),o=[[`Status`,e.archived?`Archived`:e.trigger.type===`manual`?`Manual`:e.enabled?`Enabled`:`Paused`],[`Trigger`,c(e)],[`Action`,l(e)],[`Timeout`,`${e.timeoutSeconds}s`],[`Next run`,a(e.nextRunAt)],[`Revision`,String(e.revision)],[`Created by`,e.createdBySessionId??e.creator],[`Callback`,e.callback.type===`session`?e.callback.sessionId:e.callback.type],[`Description`,e.description||`-`]];e.action.type===`agent`&&(o.push([`Session policy`,e.action.session.mode]),e.action.session.mode===`reuse`&&o.push([`Session`,e.action.session.sessionId]),`cwd`in e.action.session&&o.push([`Directory`,e.action.session.cwd]),e.action.launch?.model&&o.push([`Model`,`${e.action.launch.model.provider}/${e.action.launch.model.id}`]),e.action.launch?.thinking&&o.push([`Thinking`,e.action.launch.thinking]),o.push([`Prompt`,e.action.prompt])),e.action.type===`bash`&&o.push([`Directory`,e.action.cwd],[`Script`,e.action.script]),e.action.type===`task`&&o.push([`Target task`,e.action.taskId]),e.action.type===`system`&&o.push([`System action`,e.action.name]),e.trigger.type===`watch`&&o.push([`Probe`,e.trigger.script]);for(let[e,n]of o)r.append(t(`span`,`text-[11px] font-semibold uppercase text-neutral-400`,e),t(`pre`,`whitespace-pre-wrap break-words font-mono text-[12.5px]`,n));if(e.action.type===`agent`&&e.action.session.mode===`reuse`){let{sessionId:a}=e.action.session,o=i(`Open session`);o.onclick=()=>n(a),r.append(t(`span`,``,``),o)}return r}function d(e){return[e.pendingDecisionId?`Awaiting decision`:``,e.callbackState&&e.callbackState!==`delivered`?`Callback not delivered (${e.callbackState})`:``,e.groupCallbackState&&e.groupCallbackState!==`delivered`?`Group callback not delivered (${e.groupCallbackState})`:``].filter(Boolean).join(` · `)}function f(e,n,r,i){let c=t(`div`,`divide-y divide-neutral-100`);for(let e of n){let n=t(`button`,`grid w-full cursor-pointer grid-cols-[minmax(0,1fr)_auto] gap-x-3 gap-y-1 px-4 py-2.5 text-left text-[12.5px] hover:bg-neutral-50 md:grid-cols-[7.5rem_minmax(0,1fr)_7.5rem_6.25rem]`);n.setAttribute(`type`,`button`),n.append(t(`span`,`font-medium`,s(e)),t(`span`,`truncate text-neutral-500`,a(e.queuedAt)),t(`span`,`text-neutral-500`,e.triggerSource),t(`span`,`text-right text-neutral-500`,o(e))),n.onclick=()=>r(e.id),c.append(n)}n.length||c.append(t(`p`,`p-4 text-[13px] text-neutral-400`,`No runs yet.`)),e.replaceChildren(c),e.scrollTop=i.top,e.onscroll=()=>{i.top=e.scrollTop}}var p=e=>`Exit code: ${e.exitCode??`-`}\nstdout:\n${e.stdout}${e.stdoutTruncated?`
2
+ [stdout truncated]`:``}\nstderr:\n${e.stderr}${e.stderrTruncated?`
3
+ [stderr truncated]`:``}`;async function m(e,c,l,f,m){let g=String(Number(e.dataset.runRequest??0)+1);e.dataset.runRequest=g,e.onscroll=()=>{m.scrollTop=e.scrollTop};let _=i(`Runs`);_.className=`cursor-pointer text-neutral-500 hover:underline`,_.onclick=()=>{m.selectedId=null,m.scrollTop=0,l()};let v=t(`div`,`flex flex-wrap items-center gap-2 border-b border-neutral-200 px-4 py-2`);v.append(_,t(`span`,`min-w-0 truncate font-mono text-[12px] text-neutral-400`,c));let y=e.dataset.runId!==c;y&&(e.dataset.runId=c,e.replaceChildren(v,t(`p`,`p-4 text-[13px] text-neutral-500`,`Loading run...`)));let[b,x]=await Promise.all([r(`/api/task-runs/${c}`,`Could not load the run`),r(`/api/task-runs/${c}/messages`,`Could not load the run's messages`)]);if(!e.isConnected||e.dataset.runRequest!==g||m.selectedId!==c)return;if(!b.ok){m.drawn=``,e.replaceChildren(v,t(`p`,`p-4 text-[13px] text-red-600`,b.error));return}let S=b.value,C=x.ok?x.value:[],w=JSON.stringify([S,x]);if(!y&&m.drawn===w)return;if(m.drawn=w,S.targetSessionId){let e=i(`Open session`);e.classList.add(`ml-auto`),e.onclick=()=>f.openSession(S.targetSessionId),v.append(e)}if(S.state===`queued`||S.state===`running`){if(S.context.definition.action.type===`agent`){let e=i(`Steer`);e.onclick=()=>void h(n(`Steer run`,`/api/task-runs/${S.id}/steer`,{mode:`steer`,sourceSessionId:f.currentSessionId()},`Run control failed`),f),v.append(e)}let e=i(`Stop run`);e.onclick=()=>void f.mutate(`/api/task-runs/${S.id}/cancel`),v.append(e)}else if(S.context.definition.action.type===`agent`&&S.targetSessionId){let e=i(`Continue`);e.onclick=()=>void h(n(`Continue run`,`/api/task-runs/${S.id}/resume`,{sourceSessionId:f.currentSessionId()},`Run control failed`),f,!0),v.append(e)}let T=C.find(e=>e.id===S.pendingDecisionId);if(T&&T.toSessionId===f.currentSessionId()){let e=i(`Reply to decision`);e.onclick=()=>void h(n(`Reply to decision`,`/api/task-messages/${T.id}/reply`,{sourceSessionId:f.currentSessionId()},`Reply failed`),f),v.append(e)}let E=t(`div`,`min-w-0`);E.append(t(`div`,`flex flex-wrap items-center gap-x-5 gap-y-2 border-b border-neutral-100 px-4 py-3 text-[12.5px]`,t(`span`,`font-medium`,s(S)),t(`span`,`text-amber-700`,d(S)),t(`span`,`text-neutral-500`,a(S.queuedAt)),t(`span`,`text-neutral-500`,S.triggerSource),t(`span`,`text-neutral-500`,o(S))));let D=t(`div`,`flex flex-wrap items-center gap-3 border-b border-neutral-100 px-4 py-3 text-[12px]`),O=(e,t)=>{let n=i(e);n.classList.add(`max-w-full`,`break-all`,`!whitespace-normal`),n.onclick=t,D.append(n)};if(S.context.definition.kind===`task`&&O(`Task: ${S.context.definition.name}`,()=>f.openTask(S.taskId)),S.parentRunId&&O(`Parent: ${S.parentRunId}`,()=>f.openRun(S.parentRunId)),S.resumedFromRunId&&O(`Resumed from: ${S.resumedFromRunId}`,()=>f.openRun(S.resumedFromRunId)),S.result?.type===`task`){let e=S.result.runId;O(`Child result: ${e}`,()=>f.openRun(e))}S.groupId&&D.append(t(`span`,`break-all text-neutral-500`,`Group: ${S.groupId}`)),E.append(D);for(let e of[S.error,S.skipReason,S.callbackError])e&&E.append(t(`p`,`whitespace-pre-wrap break-words p-4 text-[13px] text-red-600`,e));if(S.result){let e=S.result,n=e.type===`agent`||e.type===`system`?e.text:e.type===`bash`?p(e):e.type===`task`?`Child run: ${e.runId}`:`Watch did not match.`;E.append(t(`h3`,`px-4 pt-3 text-[12px] font-medium`,`Result`),t(`pre`,`whitespace-pre-wrap break-words p-4 font-mono text-[12px]`,n||`No output.`))}S.probe&&E.append(t(`h3`,`px-4 pt-3 text-[12px] font-medium`,`Watch probe: ${S.matched===null?`not evaluated`:S.matched?`matched`:`not matched`}`),t(`pre`,`whitespace-pre-wrap break-words p-4 font-mono text-[12px]`,p(S.probe)));let k=t(`details`,`border-t border-neutral-200`);if(k.append(t(`summary`,`cursor-pointer px-4 py-3 text-[12px] text-neutral-500`,`Configuration snapshot (revision ${S.taskRevision})`),u(S.context.definition,f.openSession)),E.append(k),x.ok||E.append(t(`p`,`p-4 text-[13px] text-red-600`,x.error)),C.length){let e=t(`div`,`border-t border-neutral-200`);e.append(t(`div`,`px-4 py-2 text-[11px] font-semibold uppercase text-neutral-400`,`Messages`));for(let n of C){let r=t(`div`,`grid grid-cols-[auto_1fr] gap-3 border-t border-neutral-100 px-4 py-2 text-[12px] md:grid-cols-[6.25rem_6.25rem_minmax(0,1fr)]`);r.append(t(`span`,`font-medium`,n.kind),t(`span`,`text-neutral-500`,n.state),t(`span`,`col-span-2 whitespace-pre-wrap break-words md:col-span-1`,n.content)),n.error&&r.append(t(`span`,`col-span-2 break-words text-red-600 md:col-span-3`,n.error)),e.append(r)}E.append(e)}let A=t(`details`,`border-t border-neutral-200`);A.open=m.rawOpen,A.ontoggle=()=>{A.isConnected&&(m.rawOpen=A.open)},A.append(t(`summary`,`cursor-pointer px-4 py-3 text-[12px] text-neutral-500`,`Raw record`),t(`pre`,`whitespace-pre-wrap break-words px-4 pb-4 font-mono text-[12px]`,JSON.stringify(S,null,2))),E.append(A),e.replaceChildren(v,E),e.scrollTop=m.scrollTop,e.onscroll=()=>{m.scrollTop=e.scrollTop}}async function h(e,t,n=!1){let r=await e;if(r.sent){if(r.error)t.onError(r.error);else if(n&&r.response)try{let e=await r.response.json();t.openRun(e.id)}catch(e){t.onError(`Could not open continuation: ${String(e)}`)}else await t.reload()}}export{f as a,s as c,m as i,c as l,a as n,d as o,u as r,o as s,l as t};
@@ -0,0 +1,4 @@
1
+ import{B as e,C as t,D as n,G as r,I as i,M as a,T as o,V as s,W as c,g as l,x as u,y as d,z as f}from"./index-WrsNstrb.js";import{a as p,c as m,l as h,n as g,r as _,s as v,t as y}from"./task-runs-CpgHxFLf.js";function b(e,t){let n=e.map(e=>[`${e.title??`Untitled`} · ${e.cwd}`,e.id]);return t&&!n.some(([,e])=>e===t)&&n.push([`Current session · ${t}`,t]),n}function x(e,r){let a=document.createElement(`dialog`);a.className=`m-auto w-[38.75rem] max-w-[94vw] rounded-lg border border-neutral-200 p-0 shadow-xl backdrop:bg-black/20`;let o=document.createElement(`form`);o.className=`flex max-h-[88vh] flex-col`;let s=i(`span`,`mr-auto text-[12px] text-red-600`),c=i(`header`,`flex h-11 flex-none items-center border-b border-neutral-200 px-4 font-medium`,r?`Edit task`:`New task`),f=i(`div`,`grid min-h-0 flex-1 grid-cols-2 gap-3 overflow-y-auto p-4`),p=u(r?.name??``);p.required=!0;let m=u(r?.description??``),h=u(String(r?.timeoutSeconds??900),`number`);h.min=`1`,h.max=`86400`;let g=t([[`Manual`,`manual`],[`Scheduled`,`cron`],[`Watch`,`watch`]],r?.trigger.type??`manual`),_=t([[`Bash`,`bash`],[`Agent`,`agent`],[`Task`,`task`]],r?.action.type??`bash`),v=t([[`No callback`,`none`],[`Invoking session`,`origin`],[`Specific session`,`session`]],r?.callback.type??`none`),y=r?.callback.type===`session`?r.callback.sessionId:null,x=t(b(e.sessions(),y),y??``),C=d(`Callback session`,x);C.classList.toggle(`hidden`,v.value!==`session`),v.onchange=()=>C.classList.toggle(`hidden`,v.value!==`session`),f.append(d(`Name`,p),d(`Description`,m),d(`Trigger`,g),d(`Action`,_),d(`Callback`,v),C,d(`Timeout (seconds)`,h));let w=i(`div`,`col-span-2 grid grid-cols-2 gap-3 border-t border-neutral-200 pt-3`);f.append(w);let T=()=>{w.replaceChildren();let c,l,f,y,C,T;if(g.value===`cron`)c=u(r?.trigger.type===`cron`?r.trigger.expression:`0 9 * * *`),l=u(r?.trigger.type===`cron`?r.trigger.timezone:Intl.DateTimeFormat().resolvedOptions().timeZone),w.append(d(`Cron`,c),d(`Timezone`,l));else if(g.value===`watch`){f=n(r?.trigger.type===`watch`?r.trigger.script:``,4),T=u(r?.trigger.type===`watch`?r.trigger.cwd:e.sessions()[0]?.cwd??``),y=u(String(r?.trigger.type===`watch`?r.trigger.intervalSeconds:60),`number`),C=t([[`Continue after matches`,`repeat`],[`Stop after first match`,`once`]],r?.trigger.type===`watch`?r.trigger.mode:`repeat`);let i=d(`Probe script (0=match, 1=no match)`,f);i.classList.add(`col-span-2`),w.append(i,d(`Probe directory`,T),d(`Interval (seconds)`,y),d(`Mode`,C))}let E,D,O,k,A,j,M,N,P,F;if(_.value===`bash`){D=u(r?.action.type===`bash`?r.action.cwd:e.sessions()[0]?.cwd??``),E=n(r?.action.type===`bash`?r.action.script:``,6);let t=d(`Bash script`,E);t.classList.add(`col-span-2`),w.append(d(`Working directory`,D),i(`span`,``),t)}else if(_.value===`agent`){let i=e.sessions(),a=r?.action.type===`agent`?r.action:null,o=a?.session.mode===`reuse`?a.session.sessionId:``,s=b(i,o||null);O=t([[`Reuse session`,`reuse`],[`Fresh child per run`,`fresh`]],a?.session.mode===`reuse`?`reuse`:`fresh`),k=t(s,o||s[0]?.[1]||``);let c=a&&`cwd`in a.session?a.session.cwd??``:``;A=u(c||i[0]?.cwd||``),j=n(a?.prompt??``,6),M=t([[`Project default`,``],[`Off`,`off`],[`Low`,`low`],[`Medium`,`medium`],[`High`,`high`],[`Extra high`,`xhigh`]],a?.launch?.thinking??``),N=u(a?.launch?.model?.provider??``),P=u(a?.launch?.model?.id??``);let l=d(`Session`,k),f=d(`Child directory`,A),p=[d(`Thinking`,M),d(`Model provider (optional)`,N),d(`Model id (optional)`,P)],m=()=>{let e=O?.value===`reuse`;l.classList.toggle(`hidden`,!e),f.classList.toggle(`hidden`,e);for(let t of p)t.classList.toggle(`hidden`,e)};O.onchange=m,m();let h=d(`Prompt`,j);h.classList.add(`col-span-2`),w.append(d(`Session policy`,O),l,f,...p,h)}else F=t(e.tasks().filter(e=>e.id!==r?.id&&!e.archived).map(e=>[e.name,e.id]),r?.action.type===`task`?r.action.taskId:``),w.append(d(`Target task`,F));o.onsubmit=t=>{t.preventDefault();let n=g.value===`manual`?{type:`manual`}:g.value===`cron`?{type:`cron`,expression:c.value,timezone:l.value}:{type:`watch`,script:f.value,cwd:T.value,intervalSeconds:Number(y.value),mode:C.value},i=_.value===`agent`&&O.value!==`reuse`?{...M.value?{thinking:M.value}:{},...N.value.trim()&&P.value.trim()?{model:{provider:N.value.trim(),id:P.value.trim()}}:{}}:void 0,o=_.value===`bash`?{type:`bash`,cwd:D.value,script:E.value}:_.value===`agent`?{type:`agent`,prompt:j.value,session:O.value===`reuse`?{mode:`reuse`,sessionId:k.value}:{mode:`fresh`,cwd:A.value},...i?{launch:i}:{}}:{type:`task`,taskId:F.value},u=v.value===`origin`?{type:`origin`}:v.value===`session`?{type:`session`,sessionId:x.value}:{type:`none`},d={name:p.value,description:m.value,trigger:n,action:o,callback:u,timeoutSeconds:Number(h.value)};s.textContent=``,S(r?.id,d,a,s,e.onSaved)}};g.onchange=T,_.onchange=T,T();let E=l(`Cancel`);E.onclick=()=>a.close();let D=l(`Save`,!0);D.type=`submit`;let O=i(`footer`,`flex flex-none justify-end gap-2 border-t border-neutral-200 px-4 py-3`);O.append(s,E,D),o.append(c,f,O),a.append(o),a.addEventListener(`close`,()=>a.remove()),document.body.append(a),a.showModal(),p.focus()}async function S(e,t,n,i,a){let o=await r(e?`/api/tasks/${e}`:`/api/tasks`,t,e?`PATCH`:`POST`);if(!o.ok){i.textContent=(await o.json()).error??`Task save failed`;return}let s=await o.json(),c=`task`in s?s.task:s;n.close(),a(c.id)}function C(n,u,d,b,S,C,w){let T=[],E=[],D=null,O=`active`,k=`all`,A=``,j=`runs`,M={top:0},N=0,P=0,F=``,I=f(async()=>{let e=`${O}:${k}`,t=await s(`/api/tasks?state=${O}&kind=task`,`Failed to load tasks`);if(!t.ok)return F=``,L(t.error);if(e!==`${O}:${k}`)return;let n=JSON.stringify(t.value);e+n===F&&!D||(F=e+n,T=t.value,E=O===`archived`?await R():T,e===`${O}:${k}`&&(k!==`all`&&(T=T.filter(e=>e.trigger.type===k)),D?await G(D):U()))});function L(e){n.querySelector(`[role=alert]`)?.remove();let t=i(`p`,`flex-none p-4 text-[13px] text-red-600`,e);t.setAttribute(`role`,`alert`),n.append(t)}async function R(){let e=await s(`/api/tasks?state=active`,`Failed to load tasks`);return e.ok?e.value:E}let z={sessions:u,tasks:()=>E,onSaved:e=>{V(e),j=`definition`,w(e)}};function B(e,t){let n=i(`header`,`flex min-h-10 flex-none flex-wrap items-center gap-2 border-b border-neutral-200 px-4 py-2`);if(n.append(typeof e==`string`?i(`span`,`truncate font-medium max-md:hidden`,e):e),t.length){let e=i(`div`,`ml-auto flex flex-wrap items-center gap-2 max-md:w-full`);e.append(...t),n.append(e)}return n}function V(e){D=e,j=`runs`,M.top=0}function H(){D=null,N++,U()}function U(){let e=l(`New task`,!0);e.onclick=()=>void d().then(()=>x(z));let r=i(`div`,`flex flex-none flex-wrap items-center gap-3 border-b border-neutral-200 px-4 py-2`),a=(e,n,a,o)=>{let s=t(n,a);s.setAttribute(`aria-label`,e),s.classList.add(`!w-auto`,`pr-8`),s.onchange=()=>{o(s.value),P=0,I()},r.append(i(`label`,`flex items-center gap-2 text-[12px] text-neutral-500`,e,s))};a(`Status`,[[`Current`,`active`],[`Archived`,`archived`]],O,e=>{O=e});let o=i(`input`,`min-w-0 rounded border border-neutral-200 px-2 py-1 text-[13px]`);o.type=`search`,o.placeholder=`Search tasks`,o.setAttribute(`aria-label`,`Search tasks`),o.value=A,o.oninput=()=>{A=o.value,u()},r.append(o),a(`Trigger`,[[`All triggers`,`all`],[`Manual`,`manual`],[`Scheduled`,`cron`],[`Watching`,`watch`]],k,e=>{k=e});let s=document.createElement(`table`);s.className=`w-full table-fixed text-left text-[12.5px]`,s.innerHTML=`<thead class="sticky top-0 bg-neutral-50 text-[10.5px] uppercase text-neutral-400"><tr>
2
+ <th class="w-[42%] px-4 py-2 font-semibold md:w-[24%]">Name</th><th class="hidden w-[10%] px-2 py-2 font-semibold md:table-cell">Action</th>
3
+ <th class="hidden w-[23%] px-2 py-2 font-semibold md:table-cell">Trigger</th><th class="hidden w-[17%] px-2 py-2 font-semibold md:table-cell">Next</th>
4
+ <th class="px-2 py-2 font-semibold md:w-[14%]">Last result</th><th class="w-[6rem] px-2 py-2 font-semibold"></th></tr></thead>`;let c=document.createElement(`tbody`),u=()=>{let e=T.filter(e=>`${e.name} ${e.description??``}`.toLowerCase().includes(A.toLowerCase()));c.replaceChildren(...e.map(W)),f.classList.toggle(`hidden`,e.length>0)};s.append(c);let f=i(`p`,`p-4 text-[13px] text-neutral-500`,`No matching tasks.`),p=i(`div`,`min-h-0 flex-1 overflow-auto`,s,f);u(),p.onscroll=()=>{P=p.scrollTop},n.replaceChildren(B(`Tasks`,[e]),r,p),p.scrollTop=P}function W(e){let t=document.createElement(`tr`);t.className=`cursor-pointer border-b border-neutral-100 hover:bg-neutral-50`,t.onclick=()=>w(e.id);let n=e.archived?`Archived`:e.trigger.type===`manual`?`Manual`:e.enabled?`Enabled`:`Paused`,r=l(e.name);r.className=`block w-full cursor-pointer truncate text-left font-medium`,r.title=e.name,t.append(i(`td`,`truncate py-2.5 pl-4 pr-2`,r,i(`div`,`truncate text-[11px] text-neutral-400`,n),i(`div`,`truncate text-[11px] text-neutral-400 md:hidden`,h(e))));for(let n of[y(e),h(e),g(e.nextRunAt)]){let e=i(`td`,`hidden truncate px-2 py-2.5 md:table-cell`,n);e.title=n,t.append(e)}t.append(i(`td`,`px-2 py-2.5`,i(`div`,`break-words`,e.lastRun?m(e.lastRun):`-`),i(`div`,`text-[11px] text-neutral-400`,e.lastRun?v(e.lastRun):``)));let a=l(`Run now`);return a.disabled=e.archived,a.onclick=t=>{t.stopPropagation(),K(e.id)},t.append(i(`td`,`px-2 py-1 text-right`,a)),t}async function G(e){let t=++N,r=n.querySelector(`[data-task-detail]`),[a,c]=await Promise.all([s(`/api/tasks/${e}`,`Failed to load task`),s(`/api/tasks/${e}/runs`,`Failed to load the task's runs`)]);if(t!==N||D!==e)return;if(!a.ok)return L(a.error);if(!c.ok)return L(c.error);let u=a.value,f=c.value,m=l(`Tasks`);m.className=`cursor-pointer text-neutral-500 hover:underline`,m.onclick=()=>w();let h=i(`span`,`flex min-w-0 items-center gap-1.5`,m,i(`span`,`text-neutral-400`,`›`),i(`span`,`truncate font-medium`,u.name)),g=l(`Run now`,!0);g.disabled=u.archived,g.onclick=()=>void K(u.id);let v=l(u.enabled?`Pause schedule`:`Resume schedule`);v.disabled=u.archived||u.action.type===`system`||u.trigger.type===`manual`,v.onclick=()=>void q(`/api/tasks/${u.id}/${u.enabled?`pause`:`resume`}`);let y=l(`Edit`);y.disabled=u.archived||u.action.type===`system`,y.onclick=()=>void d().then(()=>x(z,u));let S=l(`Archive`);S.disabled=u.archived||u.action.type===`system`,S.onclick=()=>void q(`/api/tasks/${u.id}/archive`);let T=i(`div`,`flex flex-none gap-1 border-b border-neutral-200 px-4 py-2`),E=i(`div`,`min-h-0 flex-1 overflow-auto`);E.dataset.taskDetail=e;let O=()=>{T.replaceChildren(o(`Recent runs (${f.length})`,j===`runs`,()=>{j=`runs`,O()}),o(`Definition`,j===`definition`,()=>{j=`definition`,O()})),j===`runs`?p(E,f,e=>C({},e),M):(E.onscroll=null,E.replaceChildren(_(u,b)))},k=r?.scrollTop??0,A=l(`All runs`);A.onclick=()=>C({taskId:u.id}),n.replaceChildren(B(h,[g,...u.trigger.type===`manual`?[]:[v],y,S,A]),T,E),O(),E.scrollTop=k}async function K(t){try{let n=await r(`/api/tasks/${t}/run`,{sourceSessionId:S()});if(!n.ok)return L(await e(n,`Failed to run task`));C({},(await n.json()).runId)}catch(e){L(`Failed to run task: ${String(e)}`)}}async function q(e){let t=await c(e,`POST`,`Task update failed`);if(t)return L(t);await I()}let J=a(n,e=>{e&&e!==D&&V(e),e||H(),n.childElementCount||U(),I()});return Object.assign(J,{refresh(e){J.visible&&(!D||!e||D===e)&&I()}})}export{C as createTasksView};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ghostty-web-D8CLFi_l.js","assets/index-BFzmvpGX.js","assets/index-yNocr797.css"])))=>i.map(i=>d[i]);
2
- import{B as e,G as t,H as n,I as r,M as i,a,d as o,i as s,n as c,w as l}from"./index-BFzmvpGX.js";var u=`pier.terminalPrefs`,d={fontFamily:`monospace`,fontSize:14,cursorBlink:!0},f=()=>{try{let e=JSON.parse(localStorage.getItem(u)??`null`),t=typeof e?.fontSize==`number`?e.fontSize:d.fontSize;return{fontFamily:typeof e?.fontFamily==`string`&&e.fontFamily.trim()?e.fontFamily.slice(0,200):d.fontFamily,fontSize:Math.round(Math.max(10,Math.min(24,t))),cursorBlink:typeof e?.cursorBlink==`boolean`?e.cursorBlink:d.cursorBlink}}catch{return{...d}}},p=e=>localStorage.setItem(u,JSON.stringify(e)),m=null,h=()=>(m||=o(()=>import(`./ghostty-web-D8CLFi_l.js`).then(async e=>(await e.init(),e)),__vite__mapDeps([0,1,2])).catch(e=>{throw m=null,e}),m),g=()=>{let e=()=>void h().catch(e=>{console.warn(`terminal: emulator warm-up failed`,e)});`requestIdleCallback`in window?requestIdleCallback(e,{timeout:1e4}):setTimeout(e,3e3)},_={background:`#1a1b26`,foreground:`#a9b1d6`,cursor:`#c0caf5`};function v(e){let t=e.renderer,n=document.createElement(`canvas`).getContext(`2d`);if(!n||typeof t?.remeasureFont!=`function`){console.warn(`terminal: could not correct cell metrics — rows will render tight`);return}t.measureFont=()=>{let{fontSize:t,fontFamily:r}=e.options;n.font=`${t}px ${r}`;let i=n.measureText(`M`),a=i.fontBoundingBoxAscent||i.actualBoundingBoxAscent||t*.8,o=i.fontBoundingBoxDescent||i.actualBoundingBoxDescent||t*.25;return{width:Math.ceil(i.width),height:Math.ceil(a+o),baseline:Math.ceil(a)}},t.remeasureFont()}var y=`w-full rounded border border-neutral-300 px-2 py-1.5 font-mono text-[12px] outline-none focus:border-indigo-400`;function b(o,u,m,b,x,S){g();let C=``,w=null,T=null,E=null,D=!1,O=0,k=!1,A=f(),j=r(`div`,`ml-auto flex min-w-0 flex-none items-center gap-2`),M=r(`header`,`flex h-10 flex-none items-center gap-2 border-b border-neutral-200 bg-white px-3`),N=r(`div`,`min-h-0 flex-1 overflow-hidden p-1`);N.style.background=_.background,N.setAttribute(`data-owns-keyboard`,``),N.addEventListener(`keydown`,e=>{e.metaKey&&!e.defaultPrevented&&e.stopImmediatePropagation()},!0),N.addEventListener(`scroll`,()=>{N.scrollTop=0,N.scrollLeft=0}),N.addEventListener(`compositionend`,()=>{for(let e=N.childNodes.length-1;e>=0;e--){let t=N.childNodes[e];t&&t.nodeName!==`CANVAS`&&t.nodeName!==`TEXTAREA`&&t.remove()}}),o.append(M,N);let P=e=>{let t=r(`button`,`min-w-0 max-w-72 cursor-pointer truncate rounded-md bg-neutral-100 px-2 py-0.5 text-left font-mono text-[11.5px] text-neutral-600 hover:bg-neutral-200`,e);return t.type=`button`,t};function F(e,t){if(j.replaceChildren(),e&&j.append(r(`span`,`min-w-0 truncate text-[11.5px] text-neutral-400`,e)),t){let e=P(t.label);e.className=e.className.replace(`bg-neutral-100`,`bg-indigo-50 font-medium text-indigo-700 hover:bg-indigo-100`),e.onclick=t.run,j.append(e)}}function I(){w&&(w.options.fontFamily=A.fontFamily,w.options.fontSize=A.fontSize,w.options.cursorBlink=A.cursorBlink,requestAnimationFrame(H))}function L(){let i=document.createElement(`input`);i.type=`text`,i.placeholder=`tmux new -As "$(basename $PWD)"`,i.spellcheck=!1,i.autocomplete=`off`,i.autocapitalize=`off`,i.disabled=!0,i.className=`${y} disabled:bg-neutral-50`;let a=r(`span`,`block text-[11.5px] text-neutral-400`,`loading…`),o=(e,t)=>{a.isConnected?l(a,e,t):e===`failed`&&F(t)},s=``;(async()=>{try{s=(await n(`/api/settings`,`Could not load the startup command`)).terminalInitCommand??``,i.value=s,i.disabled=!1,o(`idle`,`Runs when a shell starts — Restart applies it here.`)}catch(e){o(`failed`,String(e))}})();let c=async()=>{let n=i.value.trim();if(!(i.disabled||n===s)){o(`saving`,`saving…`);try{let r=await t(`/api/settings`,{terminalInitCommand:n},`PUT`);if(!r.ok)return o(`failed`,await e(r,`Could not save the startup command`));s=(await r.json()).terminalInitCommand,i.value=s,o(`saved`,s?`Saved — the next shell runs it.`:`Cleared.`)}catch(e){o(`failed`,`Could not save the startup command: ${String(e)}`)}}};return i.onblur=()=>void c(),i.onkeydown=e=>{e.key===`Enter`&&c()},r(`div`,`space-y-1.5 border-t border-neutral-200 pt-2.5`,r(`div`,``,r(`span`,`text-[12px] font-semibold text-neutral-700`,`Startup command`),r(`span`,`block text-[11px] text-neutral-400`,`This Pier, every shell — not only this browser.`)),i,a)}function R(e){let t=document.createElement(`input`);t.type=`text`,t.value=A.fontFamily,t.setAttribute(`list`,`terminal-font-presets`),t.className=y;let n=document.createElement(`datalist`);n.id=`terminal-font-presets`;for(let e of[`monospace`,`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`,`JetBrains Mono, monospace`,`Cascadia Mono, monospace`,`Fira Code, monospace`]){let t=document.createElement(`option`);t.value=e,n.append(t)}let i=document.createElement(`input`);i.type=`number`,i.min=`10`,i.max=`24`,i.step=`1`,i.value=String(A.fontSize),i.className=`w-20 rounded border border-neutral-300 px-2 py-1.5 text-[12px] outline-none focus:border-indigo-400`;let o=document.createElement(`input`);o.type=`checkbox`,o.checked=A.cursorBlink,o.className=`h-4 w-4 accent-indigo-600`;let s=()=>{let e=t.value.trim(),n=Number(i.value);!e||!Number.isFinite(n)||(A={fontFamily:e.slice(0,200),fontSize:Math.round(Math.max(10,Math.min(24,n))),cursorBlink:o.checked},i.value=String(A.fontSize),p(A),I())};t.oninput=s,i.oninput=s,o.onchange=s;let c=r(`button`,`cursor-pointer text-[12px] text-neutral-500 hover:text-indigo-700`,`Reset`);c.type=`button`,c.onclick=()=>{A={...d},t.value=A.fontFamily,i.value=String(A.fontSize),o.checked=A.cursorBlink,p(A),I()},a(e,r(`div`,`w-72 space-y-3 px-3 py-2.5`,r(`div`,`flex items-center`,r(`span`,`text-[12px] font-semibold text-neutral-700`,`Terminal`),r(`span`,`ml-auto`,c)),r(`label`,`block space-y-1 text-[11.5px] text-neutral-500`,r(`span`,``,`Font family`),t,n),r(`label`,`flex items-center justify-between text-[11.5px] text-neutral-500`,r(`span`,``,`Font size`),i),r(`label`,`flex cursor-pointer items-center justify-between text-[11.5px] text-neutral-500`,r(`span`,``,`Blinking cursor`),o),L()))}function z(){let e=P(C||`Choose a folder…`);e.title=`Switch folder`,e.onclick=()=>c(e,u().map(e=>({path:e})),C||void 0,e=>e===C?void 0:b(e));let t=P(`Files`);t.title=`Browse this folder`,t.onclick=()=>x(C);let n=P(`Fit`);n.title=`Resize the shell to this window`,n.onclick=()=>{H(),w?.focus()};let i=P(`Restart`);i.title=`End this shell and start a new one`,i.onclick=()=>void V();let a=r(`button`,`icon-btn text-[15px]`,`⚙`);a.type=`button`,a.title=`Terminal settings`,a.setAttribute(`aria-label`,`Terminal settings`),a.onclick=()=>R(a);let o=r(`button`,`icon-btn`,`✕`);o.type=`button`,o.title=`Close Terminal`,o.setAttribute(`aria-label`,`Close Terminal`),o.onclick=S,M.replaceChildren(e,j,...C?[t]:[],n,i,a,o)}let B=()=>{w&&E?.readyState===WebSocket.OPEN&&E.send(JSON.stringify({t:`resize`,cols:w.cols,rows:w.rows}))};async function V(){if(E?.readyState!==WebSocket.OPEN){await W();return}window.confirm(`Restart the shell in ${C}? Anything running in it stops.`)&&(k=!0,F(`restarting…`),E.send(JSON.stringify({t:`restart`})))}function H(){!w||N.clientHeight===0||(T?.fit(),B())}window.addEventListener(`focus`,H),document.addEventListener(`visibilitychange`,()=>{document.hidden||H()});function U(){E?.close(),E=null,T=null,w?.dispose(),w=null,N.replaceChildren()}async function W(){let e=++O;U(),D=!1,k=!1,F(`connecting…`);let t;try{t=await h()}catch(e){F(`could not load the terminal: ${String(e)}`,{label:`Retry`,run:()=>void W()});return}if(e!==O)return;w=new t.Terminal({fontFamily:A.fontFamily,fontSize:A.fontSize,cursorBlink:A.cursorBlink,scrollback:2e3,theme:_}),w.open(N),v(w),T=new t.FitAddon,w.loadAddon(T),T.observeResize(),T.fit();let n=new WebSocket(`${location.protocol===`https:`?`wss`:`ws`}://${location.host}/api/terminal?cwd=${encodeURIComponent(C)}`);n.binaryType=`arraybuffer`,E=n,n.onopen=()=>{e===O&&(F(``),B(),w?.focus())},n.onmessage=t=>{if(e!==O)return;if(typeof t.data!=`string`){w?.write(new Uint8Array(t.data));return}let r;try{r=JSON.parse(t.data)}catch{D=!0,F(`invalid terminal response`,{label:`Reconnect`,run:()=>void W()}),n.close();return}if(r.t===`exit`){if(k){k=!1,W();return}D=!0,F(`shell exited (${r.code??`?`})`,{label:`Restart`,run:()=>void W()})}else r.t===`error`&&(D=!0,F(r.message??`terminal error`,{label:`Retry`,run:()=>void W()}))},n.onclose=()=>{e!==O||D||F(`disconnected`,{label:`Reconnect`,run:()=>void W()})},w.onData(e=>{n.readyState===WebSocket.OPEN&&n.send(JSON.stringify({t:`in`,d:e}))}),w.onResize(({cols:e,rows:t})=>{n.readyState===WebSocket.OPEN&&n.send(JSON.stringify({t:`resize`,cols:e,rows:t}))})}return i(o,e=>{let t=e?.startsWith(`/`)?e:C||m()||u()[0]||``;if(t===C&&w){z(),!D&&E&&E.readyState>WebSocket.OPEN?W():(H(),w.focus());return}if(C=t,z(),!C){F(`No project yet — pick a folder from the chip.`);return}W()},s)}export{b as createTerminalView};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ghostty-web-Bvhh3ZFk.js","assets/index-WrsNstrb.js","assets/index-DuZ2vERd.css"])))=>i.map(i=>d[i]);
2
+ import{B as e,G as t,H as n,I as r,M as i,a,d as o,i as s,n as c,w as l}from"./index-WrsNstrb.js";var u=`pier.terminalPrefs`,d={fontFamily:`monospace`,fontSize:14,cursorBlink:!0},f=()=>{try{let e=JSON.parse(localStorage.getItem(u)??`null`),t=typeof e?.fontSize==`number`?e.fontSize:d.fontSize;return{fontFamily:typeof e?.fontFamily==`string`&&e.fontFamily.trim()?e.fontFamily.slice(0,200):d.fontFamily,fontSize:Math.round(Math.max(10,Math.min(24,t))),cursorBlink:typeof e?.cursorBlink==`boolean`?e.cursorBlink:d.cursorBlink}}catch{return{...d}}},p=e=>localStorage.setItem(u,JSON.stringify(e)),m=null,h=()=>(m||=o(()=>import(`./ghostty-web-Bvhh3ZFk.js`).then(async e=>(await e.init(),e)),__vite__mapDeps([0,1,2])).catch(e=>{throw m=null,e}),m),g=()=>{let e=()=>void h().catch(e=>{console.warn(`terminal: emulator warm-up failed`,e)});`requestIdleCallback`in window?requestIdleCallback(e,{timeout:1e4}):setTimeout(e,3e3)},_={background:`#1a1b26`,foreground:`#a9b1d6`,cursor:`#c0caf5`};function v(e){let t=e.renderer,n=document.createElement(`canvas`).getContext(`2d`);if(!n||typeof t?.remeasureFont!=`function`){console.warn(`terminal: could not correct cell metrics — rows will render tight`);return}t.measureFont=()=>{let{fontSize:t,fontFamily:r}=e.options;n.font=`${t}px ${r}`;let i=n.measureText(`M`),a=i.fontBoundingBoxAscent||i.actualBoundingBoxAscent||t*.8,o=i.fontBoundingBoxDescent||i.actualBoundingBoxDescent||t*.25;return{width:Math.ceil(i.width),height:Math.ceil(a+o),baseline:Math.ceil(a)}},t.remeasureFont()}var y=`w-full rounded border border-neutral-300 px-2 py-1.5 font-mono text-[12px] outline-none focus:border-indigo-400`;function b(o,u,m,b,x,S){g();let C=``,w=null,T=null,E=null,D=!1,O=0,k=!1,A=f(),j=r(`div`,`ml-auto flex min-w-0 flex-none items-center gap-2`),M=r(`header`,`flex h-10 flex-none items-center gap-2 border-b border-neutral-200 bg-white px-3`),N=r(`div`,`min-h-0 flex-1 overflow-hidden p-1`);N.style.background=_.background,N.setAttribute(`data-owns-keyboard`,``),N.addEventListener(`keydown`,e=>{e.metaKey&&!e.defaultPrevented&&e.stopImmediatePropagation()},!0),N.addEventListener(`scroll`,()=>{N.scrollTop=0,N.scrollLeft=0}),N.addEventListener(`compositionend`,()=>{for(let e=N.childNodes.length-1;e>=0;e--){let t=N.childNodes[e];t&&t.nodeName!==`CANVAS`&&t.nodeName!==`TEXTAREA`&&t.remove()}}),o.append(M,N);let P=e=>{let t=r(`button`,`min-w-0 max-w-72 cursor-pointer truncate rounded-md bg-neutral-100 px-2 py-0.5 text-left font-mono text-[11.5px] text-neutral-600 hover:bg-neutral-200`,e);return t.type=`button`,t};function F(e,t){if(j.replaceChildren(),e&&j.append(r(`span`,`min-w-0 truncate text-[11.5px] text-neutral-400`,e)),t){let e=P(t.label);e.className=e.className.replace(`bg-neutral-100`,`bg-indigo-50 font-medium text-indigo-700 hover:bg-indigo-100`),e.onclick=t.run,j.append(e)}}function I(){w&&(w.options.fontFamily=A.fontFamily,w.options.fontSize=A.fontSize,w.options.cursorBlink=A.cursorBlink,requestAnimationFrame(H))}function L(){let i=document.createElement(`input`);i.type=`text`,i.placeholder=`tmux new -As "$(basename $PWD)"`,i.spellcheck=!1,i.autocomplete=`off`,i.autocapitalize=`off`,i.disabled=!0,i.className=`${y} disabled:bg-neutral-50`;let a=r(`span`,`block text-[11.5px] text-neutral-400`,`loading…`),o=(e,t)=>{a.isConnected?l(a,e,t):e===`failed`&&F(t)},s=``;(async()=>{try{s=(await n(`/api/settings`,`Could not load the startup command`)).terminalInitCommand??``,i.value=s,i.disabled=!1,o(`idle`,`Runs when a shell starts — Restart applies it here.`)}catch(e){o(`failed`,String(e))}})();let c=async()=>{let n=i.value.trim();if(!(i.disabled||n===s)){o(`saving`,`saving…`);try{let r=await t(`/api/settings`,{terminalInitCommand:n},`PUT`);if(!r.ok)return o(`failed`,await e(r,`Could not save the startup command`));s=(await r.json()).terminalInitCommand,i.value=s,o(`saved`,s?`Saved — the next shell runs it.`:`Cleared.`)}catch(e){o(`failed`,`Could not save the startup command: ${String(e)}`)}}};return i.onblur=()=>void c(),i.onkeydown=e=>{e.key===`Enter`&&c()},r(`div`,`space-y-1.5 border-t border-neutral-200 pt-2.5`,r(`div`,``,r(`span`,`text-[12px] font-semibold text-neutral-700`,`Startup command`),r(`span`,`block text-[11px] text-neutral-400`,`This Pier, every shell — not only this browser.`)),i,a)}function R(e){let t=document.createElement(`input`);t.type=`text`,t.value=A.fontFamily,t.setAttribute(`list`,`terminal-font-presets`),t.className=y;let n=document.createElement(`datalist`);n.id=`terminal-font-presets`;for(let e of[`monospace`,`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`,`JetBrains Mono, monospace`,`Cascadia Mono, monospace`,`Fira Code, monospace`]){let t=document.createElement(`option`);t.value=e,n.append(t)}let i=document.createElement(`input`);i.type=`number`,i.min=`10`,i.max=`24`,i.step=`1`,i.value=String(A.fontSize),i.className=`w-20 rounded border border-neutral-300 px-2 py-1.5 text-[12px] outline-none focus:border-indigo-400`;let o=document.createElement(`input`);o.type=`checkbox`,o.checked=A.cursorBlink,o.className=`h-4 w-4 accent-indigo-600`;let s=()=>{let e=t.value.trim(),n=Number(i.value);!e||!Number.isFinite(n)||(A={fontFamily:e.slice(0,200),fontSize:Math.round(Math.max(10,Math.min(24,n))),cursorBlink:o.checked},i.value=String(A.fontSize),p(A),I())};t.oninput=s,i.oninput=s,o.onchange=s;let c=r(`button`,`cursor-pointer text-[12px] text-neutral-500 hover:text-indigo-700`,`Reset`);c.type=`button`,c.onclick=()=>{A={...d},t.value=A.fontFamily,i.value=String(A.fontSize),o.checked=A.cursorBlink,p(A),I()},a(e,r(`div`,`w-72 space-y-3 px-3 py-2.5`,r(`div`,`flex items-center`,r(`span`,`text-[12px] font-semibold text-neutral-700`,`Terminal`),r(`span`,`ml-auto`,c)),r(`label`,`block space-y-1 text-[11.5px] text-neutral-500`,r(`span`,``,`Font family`),t,n),r(`label`,`flex items-center justify-between text-[11.5px] text-neutral-500`,r(`span`,``,`Font size`),i),r(`label`,`flex cursor-pointer items-center justify-between text-[11.5px] text-neutral-500`,r(`span`,``,`Blinking cursor`),o),L()))}function z(){let e=P(C||`Choose a folder…`);e.title=`Switch folder`,e.onclick=()=>c(e,u().map(e=>({path:e})),C||void 0,e=>e===C?void 0:b(e));let t=P(`Files`);t.title=`Browse this folder`,t.onclick=()=>x(C);let n=P(`Fit`);n.title=`Resize the shell to this window`,n.onclick=()=>{H(),w?.focus()};let i=P(`Restart`);i.title=`End this shell and start a new one`,i.onclick=()=>void V();let a=r(`button`,`icon-btn text-[15px]`,`⚙`);a.type=`button`,a.title=`Terminal settings`,a.setAttribute(`aria-label`,`Terminal settings`),a.onclick=()=>R(a);let o=r(`button`,`icon-btn`,`✕`);o.type=`button`,o.title=`Close Terminal`,o.setAttribute(`aria-label`,`Close Terminal`),o.onclick=S,M.replaceChildren(e,j,...C?[t]:[],n,i,a,o)}let B=()=>{w&&E?.readyState===WebSocket.OPEN&&E.send(JSON.stringify({t:`resize`,cols:w.cols,rows:w.rows}))};async function V(){if(E?.readyState!==WebSocket.OPEN){await W();return}window.confirm(`Restart the shell in ${C}? Anything running in it stops.`)&&(k=!0,F(`restarting…`),E.send(JSON.stringify({t:`restart`})))}function H(){!w||N.clientHeight===0||(T?.fit(),B())}window.addEventListener(`focus`,H),document.addEventListener(`visibilitychange`,()=>{document.hidden||H()});function U(){E?.close(),E=null,T=null,w?.dispose(),w=null,N.replaceChildren()}async function W(){let e=++O;U(),D=!1,k=!1,F(`connecting…`);let t;try{t=await h()}catch(e){F(`could not load the terminal: ${String(e)}`,{label:`Retry`,run:()=>void W()});return}if(e!==O)return;w=new t.Terminal({fontFamily:A.fontFamily,fontSize:A.fontSize,cursorBlink:A.cursorBlink,scrollback:2e3,theme:_}),w.open(N),v(w),T=new t.FitAddon,w.loadAddon(T),T.observeResize(),T.fit();let n=new WebSocket(`${location.protocol===`https:`?`wss`:`ws`}://${location.host}/api/terminal?cwd=${encodeURIComponent(C)}`);n.binaryType=`arraybuffer`,E=n,n.onopen=()=>{e===O&&(F(``),B(),w?.focus())},n.onmessage=t=>{if(e!==O)return;if(typeof t.data!=`string`){w?.write(new Uint8Array(t.data));return}let r;try{r=JSON.parse(t.data)}catch{D=!0,F(`invalid terminal response`,{label:`Reconnect`,run:()=>void W()}),n.close();return}if(r.t===`exit`){if(k){k=!1,W();return}D=!0,F(`shell exited (${r.code??`?`})`,{label:`Restart`,run:()=>void W()})}else r.t===`error`&&(D=!0,F(r.message??`terminal error`,{label:`Retry`,run:()=>void W()}))},n.onclose=()=>{e!==O||D||F(`disconnected`,{label:`Reconnect`,run:()=>void W()})},w.onData(e=>{n.readyState===WebSocket.OPEN&&n.send(JSON.stringify({t:`in`,d:e}))}),w.onResize(({cols:e,rows:t})=>{n.readyState===WebSocket.OPEN&&n.send(JSON.stringify({t:`resize`,cols:e,rows:t}))})}return i(o,e=>{let t=e?.startsWith(`/`)?e:C||m()||u()[0]||``;if(t===C&&w){z(),!D&&E&&E.readyState>WebSocket.OPEN?W():(H(),w.focus());return}if(C=t,z(),!C){F(`No project yet — pick a folder from the chip.`);return}W()},s)}export{b as createTerminalView};
@@ -33,8 +33,8 @@
33
33
  which style.css pays for with the safe-area inset. -->
34
34
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
35
35
  <title>Pier</title>
36
- <script type="module" crossorigin src="/assets/index-BFzmvpGX.js"></script>
37
- <link rel="stylesheet" crossorigin href="/assets/index-yNocr797.css">
36
+ <script type="module" crossorigin src="/assets/index-WrsNstrb.js"></script>
37
+ <link rel="stylesheet" crossorigin href="/assets/index-DuZ2vERd.css">
38
38
  </head>
39
39
  <!-- The document never scrolls: this is a fixed-viewport workbench, and every
40
40
  scrollable region is an inner pane. h-dvh, not h-screen, because 100vh can
@@ -79,6 +79,16 @@
79
79
  <span class="chev">▶</span>Console
80
80
  </summary>
81
81
  <ul class="pb-1 text-[13.5px]">
82
+ <li><button type="button" id="open-tasks"
83
+ class="flex w-full cursor-pointer items-center gap-2 py-1.5 pl-6 pr-3 text-left hover:bg-neutral-100">
84
+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" class="h-3.5 w-3.5 flex-none text-neutral-400">
85
+ <path d="M6 3h8M6 8h8M6 13h8M2 3h1M2 8h1M2 13h1" />
86
+ </svg>Tasks</button></li>
87
+ <li><button type="button" id="open-runs"
88
+ class="flex w-full cursor-pointer items-center gap-2 py-1.5 pl-6 pr-3 text-left hover:bg-neutral-100">
89
+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" class="h-3.5 w-3.5 flex-none text-neutral-400">
90
+ <path d="m5 3 7 5-7 5z" stroke-linejoin="round" />
91
+ </svg>Runs</button></li>
82
92
  <li><button type="button" id="open-activity"
83
93
  class="flex w-full cursor-pointer items-center gap-2 py-1.5 pl-6 pr-3 text-left hover:bg-neutral-100">
84
94
  <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" class="h-3.5 w-3.5 flex-none text-neutral-400">
@@ -139,6 +149,7 @@
139
149
  class="hidden h-10 w-10 flex-none cursor-pointer items-center justify-center rounded-md text-[20px] leading-none text-neutral-500 active:bg-neutral-200">⋯</button>
140
150
  </header>
141
151
  <section id="activity-view" class="hidden min-h-0 flex-1 flex-col"></section>
152
+ <section id="runs-view" class="hidden min-h-0 flex-1 flex-col"></section>
142
153
  <section id="tasks-view" class="hidden min-h-0 flex-1 flex-col"></section>
143
154
  <section id="boards-view" class="hidden min-h-0 flex-1 flex-col"></section>
144
155
  <section id="settings-view" class="hidden min-h-0 flex-1 flex-col"></section>
Binary file
Binary file
@@ -1,6 +1,7 @@
1
1
  // Web workbench backend: REST + SSE, a pure consumer of core.
2
2
  // See docs/design/03-web-workbench.md for the route contract.
3
3
  import { hostname } from "node:os";
4
+ import { randomUUID } from "node:crypto";
4
5
  import { readFile, stat } from "node:fs/promises";
5
6
  import { isAbsolute, join, relative } from "node:path";
6
7
  import { fileURLToPath } from "node:url";
@@ -10,7 +11,7 @@ import { compress } from "hono/compress";
10
11
  import { streamSSE } from "hono/streaming";
11
12
  import { EventHub } from "../core/hub.js";
12
13
  import { logger } from "../log.js";
13
- import { Router } from "../core/router.js";
14
+ import { QueueOperationError, Router } from "../core/router.js";
14
15
  import { registerConfigRoutes } from "./config.js";
15
16
  import { registerExplorerRoutes } from "./explorer.js";
16
17
  import { fileHeaders, MAX_FILE_BYTES, registerFsRoutes, scopedFile } from "./fs.js";
@@ -24,6 +25,17 @@ import {} from "./session-state.js";
24
25
  import { registerInstanceRoutes } from "./instance.js";
25
26
  import { registerProviderRoutes } from "./providers.js";
26
27
  const log = logger("web");
28
+ async function queueResponse(action, status = 200) {
29
+ try {
30
+ return Response.json(await action(), { status });
31
+ }
32
+ catch (err) {
33
+ const code = err instanceof QueueOperationError
34
+ ? err.reason === "draining" ? 503 : err.reason === "missing" ? 404 : 409
35
+ : 404;
36
+ return Response.json({ error: String(err) }, { status: code });
37
+ }
38
+ }
27
39
  /** A transcript without the bytes nobody has asked to see yet. A step's `args`
28
40
  * and `output` are ~90% of a long session's snapshot and sit inside a
29
41
  * collapsed group; the client fetches one turn's worth when it is opened. */
@@ -46,25 +58,20 @@ const HEARTBEAT_MS = 15_000;
46
58
  const SSE_HIGH_WATER = 4 * 1024 * 1024;
47
59
  // Canonical base64 only: Buffer.from(.., "base64") happily "decodes" garbage.
48
60
  const BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
49
- /** The SSE frame for one event, built once and shared by every stream watching
50
- * that session — three open tabs used to stringify the same delta three
51
- * times. One slot is the whole cache: the hub fans an event out to its
52
- * subscribers in one synchronous loop, so the reuse is always of the event
53
- * just built, and the memo is keyed on identity so a miss only costs a
54
- * rebuild. The hub stays transport-blind; this is the transport's business.
55
- * Byte-identical to hono's `writeSSE`: JSON has no raw newline, so `data` is
56
- * one line. */
57
- let lastEvent = null;
58
- let lastFrame = "";
59
- const sseFrame = (e) => {
60
- if (e !== lastEvent) {
61
- lastEvent = e;
62
- lastFrame = `data: ${JSON.stringify(e)}\nid: ${e.seq}\n\n`;
63
- }
64
- return lastFrame;
65
- };
66
61
  export function createServer({ factory, router, hub, sessions: state, config, providers, settings, catalog, names, onToolsChanged, validateCustomTools, secrets, onUnlocked, reload, updates, updater, backgroundRuns, activeBackgroundRunCounts, channelOf, }) {
67
62
  const app = new Hono();
63
+ const epoch = randomUUID();
64
+ // One frame shared by synchronous fan-out to every watching tab. The epoch
65
+ // and wire encoding stay here; core only stamps transport-blind events.
66
+ let lastEvent = null;
67
+ let lastFrame = "";
68
+ const sseFrame = (e) => {
69
+ if (e !== lastEvent) {
70
+ lastEvent = e;
71
+ lastFrame = `data: ${JSON.stringify(e)}\nid: ${epoch}:${e.seq}\n\n`;
72
+ }
73
+ return lastFrame;
74
+ };
68
75
  // A finished turn marks its session unread until some client reports it was
69
76
  // seen (session selected + tab visible → POST read below). Server-side so
70
77
  // every client shows the same attention state. Streaming → idle is the
@@ -246,16 +253,28 @@ export function createServer({ factory, router, hub, sessions: state, config, pr
246
253
  guarded(app, "GET", "/api/sessions/:id/history", 404, async (c) => {
247
254
  const id = c.req.param("id");
248
255
  const session = await ensureLoadable(id);
249
- return c.json({
250
- turns: (await session.history()).map(slim),
251
- lastSeq: hub.lastSeq(id),
252
- model: session.model ?? null,
253
- state: session.state,
254
- context: session.contextUsage ?? null,
255
- thinkingLevel: session.thinkingLevel,
256
- queue: await session.pendingQueue(),
257
- backgroundRuns: backgroundRuns?.(id) ?? [],
258
- });
256
+ // Async seam reads can straddle an event. Never label older content with a
257
+ // newer cursor, and never spin indefinitely if the session stays busy.
258
+ for (let attempt = 0; attempt < 3; attempt++) {
259
+ const lastSeq = hub.lastSeq(id);
260
+ const turns = (await session.history()).map(slim);
261
+ const queue = await session.pendingQueue();
262
+ if (hub.lastSeq(id) !== lastSeq)
263
+ continue;
264
+ return c.json({
265
+ turns, lastSeq, epoch,
266
+ model: session.model ?? null,
267
+ state: session.state,
268
+ context: session.contextUsage ?? null,
269
+ thinkingLevel: session.thinkingLevel,
270
+ queue,
271
+ queueRecovery: router.recoveryOf(id),
272
+ queueUncertain: router.queueUncertain(id),
273
+ backgroundRuns: backgroundRuns?.(id) ?? [],
274
+ });
275
+ }
276
+ log.warn(`snapshot for ${id} changed during all 3 reads`);
277
+ return c.json({ error: "Session changed while loading history; retry loading the session" }, 503);
259
278
  });
260
279
  // One turn's activity in full, for the group the user just opened. Indexed
261
280
  // like the edit route below; the steps carry their own id and tool name so a
@@ -404,8 +423,8 @@ export function createServer({ factory, router, hub, sessions: state, config, pr
404
423
  return c.json({ ok: true }, 202);
405
424
  });
406
425
  // Promote queued messages: "steer" delivers them into the running turn,
407
- // "restart" aborts the turn and sends them as a fresh prompt. Pi has no
408
- // promote primitive, so this is clear-queue + re-dispatch through core.
426
+ // "restart" aborts the turn and sends them as a fresh prompt. Core owns
427
+ // exclusion and retains originals through the asynchronous handoff.
409
428
  guarded(app, "POST", "/api/sessions/:id/queue/deliver", 404, async (c) => {
410
429
  const id = c.req.param("id");
411
430
  const body = await c.req.json().catch(() => null);
@@ -413,38 +432,20 @@ export function createServer({ factory, router, hub, sessions: state, config, pr
413
432
  if (mode !== "steer" && mode !== "restart") {
414
433
  return c.json({ error: "mode must be steer or restart" }, 400);
415
434
  }
416
- // Same reason as edit above: a refused dispatch must not cost the queue.
417
- if (router.isDraining())
418
- return c.json({ error: "Pier is restarting — try again in a moment" }, 503);
419
- const session = await ensure(id);
420
- const { steering, followUp } = await session.clearQueue();
421
- const text = [...steering, ...followUp].join("\n").trim();
422
- if (!text)
423
- return c.json({ error: "queue is empty" }, 409);
424
- if (mode === "restart")
425
- await router.abort(id); // resolves once idle
426
- // No sender here, unlike the other dispatches: the queued texts were
427
- // headed when they were first dispatched — and in a shared session they
428
- // are other speakers' words, which an operator header would claim.
429
- await router.dispatch({
430
- key: { channelId: "web", conversationId: id },
431
- senderId: "web",
432
- text,
433
- mode: mode === "steer" ? "steer" : "auto",
434
- });
435
- return c.json({ delivered: text }, 202);
435
+ return queueResponse(async () => ({ submitted: await router.deliverQueue(id, mode) }), 202);
436
436
  });
437
437
  // Recall: drop all pending queued messages and hand them back (composer restore).
438
438
  guarded(app, "POST", "/api/sessions/:id/queue/recall", 404, async (c) => {
439
439
  const id = c.req.param("id");
440
- const session = await ensure(id);
441
- const { steering, followUp } = await session.clearQueue();
442
- // Those messages carried the header that told the session who is speaking,
443
- // and they are going back to the composer instead of to the model.
444
- if (steering.length || followUp.length)
445
- router.forgetSender(id);
446
- return c.json({ messages: [...steering, ...followUp] });
440
+ return queueResponse(async () => {
441
+ const { steering, followUp } = await router.recallQueue(id);
442
+ return { messages: [...steering, ...followUp] };
443
+ });
447
444
  });
445
+ guarded(app, "POST", "/api/sessions/:id/queue/recovery/:batchId/ack", 404, async (c) => queueResponse(async () => {
446
+ router.acknowledgeRecovery(c.req.param("id"), c.req.param("batchId"));
447
+ return { ok: true };
448
+ }));
448
449
  // Shrink the context on demand: Pi summarizes the older transcript away and
449
450
  // the session continues from the summary. Refused while streaming, like the
450
451
  // edit route above and for the same reason — Pi's own compaction aborts a
@@ -496,10 +497,14 @@ export function createServer({ factory, router, hub, sessions: state, config, pr
496
497
  }));
497
498
  app.get("/api/sessions/:id/events", (c) => {
498
499
  const id = c.req.param("id");
499
- const lastId = Number(c.req.header("Last-Event-ID") ?? "") ||
500
- Number(c.req.query("after") ?? "") ||
501
- 0;
500
+ const cursor = c.req.header("Last-Event-ID") ?? c.req.query("after") ?? "";
501
+ const match = /^([^:]+):(0|[1-9]\d*)$/.exec(cursor);
502
+ const lastId = match ? Number(match[2]) : NaN;
502
503
  return streamSSE(c, async (stream) => {
504
+ if (match?.[1] !== epoch || !hub.covers(id, lastId)) {
505
+ await stream.writeSSE({ event: "reset", data: "snapshot required" });
506
+ return;
507
+ }
503
508
  let queued = 0; // frame chars written but not yet drained by the reader
504
509
  const send = (frame) => {
505
510
  if (stream.aborted || stream.closed)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timqi/pier",
3
- "version": "0.0.19",
3
+ "version": "0.0.20",
4
4
  "description": "A self-hosted workspace for coding agents: web workbench and IM channels in front of Pi sessions",
5
5
  "license": "AGPL-3.0-only",
6
6
  "repository": "github:timqi/pier",
@@ -44,7 +44,7 @@
44
44
  "vitest": "^4.1.11"
45
45
  },
46
46
  "dependencies": {
47
- "@earendil-works/pi-coding-agent": "^0.84.2",
47
+ "@earendil-works/pi-coding-agent": "^0.85.1",
48
48
  "@hono/node-server": "^2.1.1",
49
49
  "@larksuiteoapi/node-sdk": "^1.73.0",
50
50
  "croner": "^10.0.1",
@@ -32,12 +32,18 @@ A summary's `triggerSource` is who fired that run (`agent` when you did, plus
32
32
  `manual` / `cron` / `watch` / `task`); a definition's `trigger` is only its
33
33
  schedule policy, where `manual` means on-demand — by a human or by you.
34
34
 
35
- - `fresh`: clean context, requires `cwd`. `fork`: child starts with a copy of
36
- your conversation use when the task needs your context. `reuse`: sends
37
- work to an existing session by id.
35
+ - `fresh`: clean context, requires `cwd` how a child normally starts.
36
+ `reuse`: sends work to an existing session by id, continuing its history.
37
+ There is no way to copy your context into a child: what the child needs, you
38
+ write down.
39
+ - **The handoff is the prompt.** A child cannot see your discussion, so state:
40
+ the goal; the decisions *currently* in force (not the ones you argued out of);
41
+ the constraints the user added late; absolute paths; what "done" means and how
42
+ to verify it. Writing it is also the check — a decision you cannot state in a
43
+ sentence was not settled.
38
44
  - The child inherits your current model unless `launch.model` is set.
39
45
  Unknown models fail with the available list in the error. `launch` applies to
40
- `fresh` and `fork` only — a `reuse` session owns its own model and tools.
46
+ `fresh` only — a `reuse` session owns its own model and tools.
41
47
  - The child has the same tools you do.
42
48
  - Runs time out after 900s by default; set `timeoutSeconds` in the draft for
43
49
  longer jobs.
@@ -65,9 +71,8 @@ group in core — you never track run ids across turns:
65
71
  ## Chains
66
72
 
67
73
  Run step 1, end your turn, receive its callback, splice the needed part into
68
- step 2's prompt. Children share nothing implicitly (except fork's copied
69
- history) — every prompt must be self-contained: paths, acceptance criteria,
70
- expected output format. Branching and retries are your own logic between
74
+ step 2's prompt. Children share nothing implicitly every prompt must be
75
+ self-contained: paths, acceptance criteria, expected output format. Branching and retries are your own logic between
71
76
  turns.
72
77
 
73
78
  ## Choosing a model and thinking level
@@ -103,8 +108,8 @@ list in the error, so a stale guess costs one call.
103
108
 
104
109
  `{"operation":"contact","reason":"decision","message":"..."}` returns a
105
110
  receipt immediately. State what you are waiting for and **end your turn** —
106
- never spin or poll. The answer arrives as a follow-up if your run is still
107
- active; if your run already finished, Pier resumes your session with the
111
+ never spin or poll. The answer is steered into your current turn if your run is
112
+ still active; if your run already finished, Pier resumes your session with the
108
113
  reply as the prompt. One open decision per run.
109
114
 
110
115
  As a parent: the question arrives as a system input with a message id, steered
@@ -1,5 +0,0 @@
1
- import{F as e,I as t,K as n,M as r,R as i,T as a,V as o,z as s}from"./index-BFzmvpGX.js";var c=(e,t={})=>{let n=document.createElementNS(`http://www.w3.org/2000/svg`,e);for(let[e,r]of Object.entries(t))n.setAttribute(e,r);return n},l=t=>t===null?`-`:e(Date.now()-t),u={light:{edge:`#a3a3a3`,callback:`#0891b2`,message:`#d97706`,scheduler:{fill:`#f5f3ff`,stroke:`#a78bfa`,text:`#5b21b6`},console:{fill:`#eff6ff`,stroke:`#93c5fd`,text:`#1d4ed8`},task:{fill:`#fffbeb`,stroke:`#fbbf24`,text:`#92400e`},process:{fill:`#f5f5f5`,stroke:`#a3a3a3`,text:`#525252`,dash:`4 3`},streaming:{fill:`#ffffff`,stroke:`#10b981`,text:`#262626`},idle:{fill:`#fafafa`,stroke:`#d4d4d4`,text:`#737373`}},dark:{edge:`#7a7a7a`,callback:`#3fc3dd`,message:`#e0a13a`,scheduler:{fill:`#2b2440`,stroke:`#7d63c9`,text:`#c9b8f5`},console:{fill:`#1f2a3d`,stroke:`#4a7fbf`,text:`#a8c8f0`},task:{fill:`#3a2f1c`,stroke:`#b8862a`,text:`#f0d49a`},process:{fill:`#262626`,stroke:`#5c5c5c`,text:`#a3a3a3`,dash:`4 3`},streaming:{fill:`#22302a`,stroke:`#10b981`,text:`#e5e5e5`},idle:{fill:`#212121`,stroke:`#4a4a4a`,text:`#9a9a9a`}}},d=()=>u[document.documentElement.dataset.theme===`dark`?`dark`:`light`];function f(e,u,f){let p=`sessions`,m=`active`,h={sessions:[],runs:[],messages:[]},g=``,_=s(async()=>{let r=m,i=await o(`/api/activity?scope=${r}`,`Failed to load activity`);if(!i.ok){g=``,e.replaceChildren(t(`p`,`p-4 text-[13px] text-red-600`,i.error));return}if(r!==m)return;let a=JSON.stringify(i.value);if(a===g)return;g=a;let s=i.value;h={...s,sessions:s.sessions.map(e=>({...e,title:n(e.title)}))},v()});function v(){let n=t(`header`,`flex h-10 flex-none items-center gap-2 border-b border-neutral-200 px-4 max-md:hidden`,t(`span`,`font-medium`,`Activity`)),r=t(`div`,`tabstrip`);r.append(a(`Sessions`,p===`sessions`,()=>{p=`sessions`,v()}),a(`Dependencies`,p===`dependencies`,()=>{p=`dependencies`,v()}),a(`Tasks`,!1,()=>f()));let i=t(`div`,`ml-auto flex gap-1 max-md:ml-0 max-md:w-full`),o=e=>()=>{m=e,v(),_()};i.append(a(`Active`,m===`active`,o(`active`)),a(`Last 24h`,m===`recent`,o(`recent`))),r.append(i);let s=t(`div`,`min-h-0 flex-1 overflow-auto`);p===`sessions`?y(s):b(s),e.replaceChildren(n,r,s)}function y(e){let n=document.createElement(`table`);n.className=`w-full min-w-[38rem] table-fixed text-left text-[12.5px]`,n.innerHTML=`<thead class="bg-neutral-50 text-[10.5px] uppercase text-neutral-400"><tr>
2
- <th class="w-[34%] px-4 py-2 font-semibold">Session</th>
3
- <th class="w-[38%] px-2 py-2 font-semibold">Project</th>
4
- <th class="w-[14%] px-2 py-2 font-semibold">State</th>
5
- <th class="px-2 py-2 font-semibold">Duration</th></tr></thead>`;let r=document.createElement(`tbody`);for(let e of h.sessions){let n=document.createElement(`tr`);n.className=`cursor-pointer border-b border-neutral-100 hover:bg-neutral-50`,n.onclick=()=>u(e.id),n.append(t(`td`,`px-4 py-2.5`,t(`div`,`truncate font-medium`,e.title??i(e.cwd)),t(`div`,`truncate font-mono text-[11px] text-neutral-400`,e.id)),t(`td`,`truncate px-2 py-2.5 font-mono text-[11.5px]`,e.cwd||`-`),t(`td`,`px-2 py-2.5`,t(`span`,`mr-2 inline-block h-2 w-2 rounded-full ${e.state===`streaming`?`animate-pulse bg-green-500`:`bg-neutral-300`}`),e.state),t(`td`,`px-2 py-2.5 text-neutral-500`,l(e.stateSince))),r.append(n)}n.append(r),e.append(n),h.sessions.length||e.append(t(`p`,`p-4 text-[13px] text-neutral-400`,m===`active`?`No active sessions.`:`No sessions in the last 24 hours.`))}function b(e){let n=new Map,r=[],i=(e,t,r,i)=>{n.has(e)||n.set(e,{id:e,label:t,kind:r,state:i})};for(let e of h.sessions)i(e.id,e.title??e.id.slice(0,10),`session`,e.state);for(let e of h.runs){let t=e.invokedBySessionId??`scheduler`,n=e.targetSessionId??(e.context.definition.action.type===`bash`?`process:${e.id}`:`task:${e.id}`);i(t,t===`scheduler`?`Scheduler`:t.slice(0,10),t===`scheduler`?`scheduler`:`session`),i(n,e.targetSessionId?e.targetSessionId.slice(0,10):e.context.definition.action.type===`bash`?`Bash process`:`Task`,e.targetSessionId?`session`:e.context.definition.action.type===`bash`?`process`:`task`),r.push({from:t,to:n,run:e,kind:`invocation`}),e.callbackSessionId&&(i(e.callbackSessionId,e.callbackSessionId.slice(0,10),`session`),r.push({from:n,to:e.callbackSessionId,run:e,kind:`callback`}))}for(let e of h.messages){if(!e.fromSessionId||!e.toSessionId||e.fromSessionId===e.toSessionId)continue;let t=h.runs.find(t=>t.id===e.runId);if(t){for(let t of[e.fromSessionId,e.toSessionId])i(t,t===`console`?`Console`:t.slice(0,10),t===`console`?`console`:`session`);r.push({from:e.fromSessionId,to:e.toSessionId,run:t,kind:`message`})}}if(!n.size){e.append(t(`p`,`p-4 text-[13px] text-neutral-400`,m===`active`?`No active dependencies.`:`No dependencies in the last 24 hours.`));return}let a=[...n.values()],o=new Set(r.map(e=>e.to)),s=new Map,l=a.filter(e=>!o.has(e.id)).map(e=>e.id);l.length||l.push(a[0].id);for(let e of l)s.set(e,0);for(;l.length;){let e=l.shift();for(let t of r)t.from!==e||s.has(t.to)||(s.set(t.to,s.get(e)+1),l.push(t.to))}for(let e of a)s.has(e.id)||s.set(e.id,0);let p=new Map;for(let e of a){let t=s.get(e.id);p.set(t,[...p.get(t)??[],e])}let g=Math.max(...p.keys())+1,_=Math.max(...[...p.values()].map(e=>e.length)),v=r.some(e=>e.from!==e.to&&s.get(e.from)===s.get(e.to))?40:0,y=56+g*180+(g-1)*110+v,b=56+_*46+(_-1)*30,x=new Map;for(let[e,t]of p)t.forEach((t,n)=>x.set(t.id,{x:28+e*290+90,y:28+n*76+23}));let S=c(`svg`,{width:String(y),height:String(b),viewBox:`0 0 ${y} ${b}`,class:`block`}),C=c(`defs`),w=d();for(let[e,t]of[[`activity-arrow`,w.edge],[`activity-arrow-cb`,w.callback],[`activity-arrow-msg`,w.message]]){let n=c(`marker`,{id:e,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`6`,markerHeight:`6`,orient:`auto-start-reverse`});n.append(c(`path`,{d:`M 0 0 L 10 5 L 0 10 z`,fill:t})),C.append(n)}S.append(C);let T=new Set;for(let e of r){let t=`${e.from}→${e.to}:${e.kind}`;if(T.has(t))continue;T.add(t);let n=x.get(e.from),r=x.get(e.to),i=c(`path`,{d:n.x===r.x?`M ${n.x+90} ${n.y} C ${n.x+90+46} ${n.y}, ${r.x+90+46} ${r.y}, ${r.x+90} ${r.y}`:(()=>{let e=r.x>n.x,t=n.x+(e?90:-90),i=r.x+(e?-90:90),a=Math.max(36,Math.abs(i-t)*.45)*(e?1:-1);return`M ${t} ${n.y} C ${t+a} ${n.y}, ${i-a} ${r.y}, ${i} ${r.y}`})(),fill:`none`,stroke:e.kind===`callback`?w.callback:e.kind===`message`?w.message:w.edge,"stroke-width":`1.5`,"marker-end":e.kind===`callback`?`url(#activity-arrow-cb)`:e.kind===`message`?`url(#activity-arrow-msg)`:`url(#activity-arrow)`});e.kind===`callback`&&i.setAttribute(`stroke-dasharray`,`6 5`),e.kind===`message`&&i.setAttribute(`stroke-dasharray`,`2 5`),i.classList.add(`cursor-pointer`),i.onclick=()=>f(e.run.taskId),S.append(i)}let E=/[\u1100-\u11FF\u2E80-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6]/,D=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)if(n+=E.test(e[r])?2:1,n>t)return`${e.slice(0,r)}…`;return e};for(let e of a){let t=x.get(e.id),n=e.kind===`session`?e.state===`streaming`?w.streaming:w.idle:w[e.kind],r=c(`g`,{transform:`translate(${t.x},${t.y})`});e.kind===`session`&&r.classList.add(`cursor-pointer`),r.onclick=()=>{e.kind===`session`&&u(e.id)};let i=c(`rect`,{x:`-90`,y:`-23`,width:`180`,height:`46`,rx:`10`,fill:n.fill,stroke:n.stroke,"stroke-width":e.kind===`session`&&e.state===`streaming`?`1.5`:`1`});n.dash&&i.setAttribute(`stroke-dasharray`,n.dash),r.append(i);let a=-78;if(e.kind===`session`){let t=c(`circle`,{cx:`-75`,cy:`0`,r:`3.5`,fill:n.stroke});if(e.state===`streaming`){let e=c(`animate`,{attributeName:`opacity`,values:`1;0.3;1`,dur:`1.6s`,repeatCount:`indefinite`});t.append(e)}r.append(t),a=-64}let o=c(`text`,{x:String(a),"text-anchor":`start`,"dominant-baseline":`middle`,"font-size":`11.5`,"font-weight":e.kind===`session`?`500`:`400`,fill:n.text});o.textContent=D(e.label,e.kind===`session`?22:25);let s=c(`title`);s.textContent=e.label===e.id?e.id:`${e.label}\n${e.id}`,r.append(o,s),S.append(r)}let O=e=>t(`span`,`inline-block h-2 w-2 rounded-full ${e}`);e.append(t(`div`,`w-max p-4`,S),t(`div`,`flex flex-wrap gap-x-5 gap-y-1 border-t border-neutral-200 px-4 py-2 text-[11px] text-neutral-500`,t(`span`,``,`Solid: task invocation`),t(`span`,`text-cyan-700`,`Dashed: callback`),t(`span`,`text-amber-700`,`Dotted: supervisor/control`),t(`span`,`inline-flex items-center gap-1.5`,O(`bg-emerald-500`),`streaming`),t(`span`,`inline-flex items-center gap-1.5`,O(`bg-neutral-300`),`idle`)))}let x=r(e,e=>{e===`dependencies`?p=`dependencies`:e===`sessions`&&(p=`sessions`),_()},()=>{e.replaceChildren(),h={sessions:[],runs:[],messages:[]},g=``});return window.addEventListener(`pier:theme`,()=>{x.visible&&v()}),Object.assign(x,{refresh(){x.visible&&_()}})}export{f as createActivityView};