@nathanstephenson/flow 0.1.10-beta.4 → 0.1.10-beta.5

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 (82) hide show
  1. package/README.md +2 -2
  2. package/build/workflow-runtime.cjs +12 -12
  3. package/dist/backend/claude/workflow-parent.js +1 -1
  4. package/dist/backend/pi/model-auth.js +2 -2
  5. package/dist/backend/pi/workflow-parent.js +1 -1
  6. package/dist/backend/worker/index.js +4 -3
  7. package/dist/backend/worker/launcher.js +11 -4
  8. package/dist/build-id +1 -1
  9. package/dist/cli/application.js +5 -5
  10. package/dist/cli/bootstrap.js +1 -1
  11. package/dist/cli/host-control.js +1 -1
  12. package/dist/cli/install-guard.js +1 -1
  13. package/dist/cli/main.js +4 -4
  14. package/dist/cli/systemd-update.js +3 -3
  15. package/dist/cli/update.js +6 -6
  16. package/dist/cli/web-update.js +6 -6
  17. package/dist/daemon/changes.js +116 -0
  18. package/dist/daemon/commit.js +84 -0
  19. package/dist/daemon/config-store.js +3 -3
  20. package/dist/daemon/git-state.js +197 -0
  21. package/dist/daemon/github.js +54 -0
  22. package/dist/daemon/host-control-routes.js +1 -1
  23. package/dist/daemon/host.js +134 -76
  24. package/dist/daemon/log.js +3 -0
  25. package/dist/daemon/mcp-auth.js +1 -1
  26. package/dist/daemon/pi-model-cache.js +1 -1
  27. package/dist/daemon/pull-request.js +156 -129
  28. package/dist/daemon/push.js +43 -0
  29. package/dist/daemon/repository.js +106 -0
  30. package/dist/daemon/runtime.js +27 -20
  31. package/dist/daemon/secret-store.js +1 -1
  32. package/dist/daemon/server.js +11 -10
  33. package/dist/daemon/stack-metadata.js +12 -5
  34. package/dist/daemon/stack.js +127 -656
  35. package/dist/daemon/summariser.js +19 -8
  36. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  37. package/dist/daemon/workflow-authoring-scope.js +1 -1
  38. package/dist/daemon/workflow-builder-files.js +2 -2
  39. package/dist/daemon/workflow-builder-routes.js +2 -2
  40. package/dist/daemon/workflow-builder.js +5 -5
  41. package/dist/daemon/workflow-environment.js +5 -5
  42. package/dist/daemon/workflow-execution-launch.js +5 -5
  43. package/dist/daemon/workflow-execution-resources.js +3 -3
  44. package/dist/daemon/workflow-execution-routes.js +3 -3
  45. package/dist/daemon/workflow-execution-values.js +5 -5
  46. package/dist/daemon/workflow-executions.js +19 -19
  47. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  48. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  49. package/dist/daemon/workflow-mcp.js +1 -1
  50. package/dist/daemon/workflow-routes.js +3 -3
  51. package/dist/daemon/workflow-schedule-driver.js +8 -8
  52. package/dist/daemon/workflow-schedule-routes.js +5 -5
  53. package/dist/daemon/workflow-schedules.js +3 -3
  54. package/dist/isolation/toolchain-assets.js +1 -1
  55. package/dist/protocol/stack.js +1 -41
  56. package/dist/workflows/calls.js +2 -2
  57. package/dist/workflows/executors.js +3 -3
  58. package/dist/workflows/graph.js +6 -6
  59. package/dist/workflows/invocations.js +1 -1
  60. package/dist/workflows/mcp.js +1 -1
  61. package/dist/workflows/records.js +6 -6
  62. package/dist/workflows/recovery.js +2 -2
  63. package/dist/workflows/runtime-settings.js +1 -1
  64. package/dist/workflows/runtime.js +2 -2
  65. package/dist/workflows/schedule-store.js +2 -2
  66. package/dist/workflows/scheduler.js +9 -9
  67. package/dist/workflows/schema.js +1 -1
  68. package/dist/workflows/store.js +3 -3
  69. package/package.json +3 -2
  70. package/web/dist/assets/index-BqZ_iUmY.css +2 -0
  71. package/web/dist/assets/index-CxdSb7k0.js +51 -0
  72. package/web/dist/assets/{settings-mcp-bcNKV147.js → settings-mcp-BwOPXAfH.js} +1 -1
  73. package/web/dist/assets/settings-workflows-DocTa31_.js +23 -0
  74. package/web/dist/assets/{switch-DIogWclb.js → switch-B00FEUA7.js} +1 -1
  75. package/web/dist/assets/{workflows-DHG-CIo3.js → workflows-DJqUuGyg.js} +31 -31
  76. package/web/dist/assets/{workflows-pane-9u_hJvgQ.js → workflows-pane-oM1fO_BC.js} +1 -1
  77. package/web/dist/index.html +4 -4
  78. package/dist/daemon/publish.js +0 -289
  79. package/dist/protocol/publish.js +0 -1
  80. package/web/dist/assets/index-BWKZK5HD.css +0 -2
  81. package/web/dist/assets/index-nIc09tKZ.js +0 -40
  82. package/web/dist/assets/settings-workflows-C_TKOhVa.js +0 -23
@@ -1 +1 @@
1
- import{a as e}from"./rolldown-runtime-B0Z9INg1.js";import{Pn as t,kr as n,n as r,t as i,wr as a}from"./workflow-api-BfExddae.js";import{C as o,S as s,d as c,ft as l,gt as u,mt as d,u as f,x as p}from"./workflows-DHG-CIo3.js";import{a as m,c as h,n as g,r as _,s as v}from"./switch-DIogWclb.js";import{t as y}from"./index-nIc09tKZ.js";var b=e(n(),1),x=a();function S({sessionId:e,placement:n=`right`,mobileNavigation:a}){let S=i(`/api/workflows`),C=`/api/sessions/${encodeURIComponent(e)}/workflows`,w=i(C),[T,E]=(0,b.useState)(()=>u(e)),[D,O]=(0,b.useState)(T?.workflowId??``),[k,A]=(0,b.useState)(T?.input??{}),[j,M]=(0,b.useState)(``),[N,P]=(0,b.useState)(T?.error??``),[F,I]=(0,b.useState)(!1),[L,R]=(0,b.useState)(T!==void 0),z=i(j?`${C}/${j}`:void 0,1e3),{sessions:B}=l(),V=B.find(t=>t.id===e),H=S.data?.workflows.find(e=>e.id===D),U=z.data?.execution,W=!!(z.data?.enquiries.length||z.data?.permissions.length),G=[...w.data?.executions??[]].sort((e,t)=>t.startedAt-e.startedAt);(0,b.useEffect)(()=>{let t=u(e);E(t),O(t?.workflowId??``),A(t?.input??{}),M(``),P(t?.error??``),R(t!==void 0)},[e]),(0,b.useEffect)(()=>{if(j||!G.length)return;let e=G.find(e=>e.status===`running`||e.status===`recovery-required`);M((e??G[0]).id)},[j,w.data]);let K=``;try{H&&(s(H),o(H.inputSchema,k))}catch(e){K=p(e)}let q=H&&V&&H.backend!==V.backend,J=async(t,n)=>{I(!0);try{let i=await r(t,`POST`,n);i.execution&&(M(i.execution.id),R(!1),t===C&&(d(e),E(void 0))),P(`Request accepted`)}catch(e){P(p(e))}finally{I(!1)}};return(0,x.jsxs)(`section`,{className:`workflow-panel grid grid-cols-[minmax(0,1fr)] content-start gap-3 overflow-auto p-3 text-sm`,children:[(0,x.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,x.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Workflows`}),(0,x.jsx)(t,{size:`sm`,variant:`outline`,disabled:F||!w.data||w.data.occupied||V?.status===`ended`,onClick:()=>R(e=>!e),children:L?`Close`:`New workflow`})]}),(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Independent of parent chat. Steps share this Scope.`}),(S.error||w.error||z.error||N)&&(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,role:`status`,children:N||S.error||w.error||z.error}),T&&(0,x.jsxs)(`div`,{className:`rounded-lg border border-destructive/40 bg-destructive/5 p-3`,role:`alert`,children:[(0,x.jsx)(`p`,{className:`font-medium`,children:`Workflow did not start`}),(0,x.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`This Agent Session was kept. Review the preserved inputs below and retry here; retrying will not create another Agent Session.`})]}),L&&!w.data?.occupied&&(0,x.jsx)(`section`,{"aria-label":`New workflow`,children:(0,x.jsxs)(`div`,{className:`grid gap-3 pt-2`,children:[(0,x.jsxs)(g,{value:D,onValueChange:e=>{if(e===null)return;O(e);let t=S.data?.workflows.find(t=>t.id===e);A(t?c(t.inputSchema):{})},children:[(0,x.jsx)(v,{className:`w-full`,"aria-label":`Workflow`,children:(0,x.jsx)(h,{children:H?.name??`Select workflow`})}),(0,x.jsxs)(_,{children:[(0,x.jsx)(m,{value:``,children:`Select workflow`}),S.data?.workflows.map(e=>(0,x.jsx)(m,{value:e.id,children:e.name},e.id))]})]}),H&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(f,{schema:H.inputSchema,value:k,onChange:A}),q&&(0,x.jsxs)(`p`,{role:`alert`,children:[`This workflow requires Backend Adapter `,H.backend,`.`,` `,(0,x.jsx)(`a`,{className:`underline`,href:`#/new/${encodeURIComponent(H.backend)}`,children:`Create a matching Agent Session`}),`.`]}),K&&(0,x.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono text-xs text-destructive`,role:`alert`,children:K}),(0,x.jsx)(t,{size:`sm`,className:`justify-self-start`,disabled:F||!w.data||w.data.occupied||V?.status===`ended`||!!K||!!q,onClick:()=>void J(C,{workflowId:D,input:k,...T?{launchId:T.launchId,nameSession:!0}:{}}),children:T?`Retry workflow`:`Start workflow`})]})]})}),(0,x.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,x.jsx)(`span`,{className:`text-sm font-medium`,children:`Execution history`}),(0,x.jsxs)(g,{items:[{value:``,label:`Select execution`},...G.map(e=>({value:e.id,label:`${e.name} · ${e.status.replaceAll(`-`,` `)} · ${new Date(e.startedAt).toLocaleString()}${e.testStepId?` · step test`:``}`}))],disabled:F,value:j,onValueChange:e=>{e!==null&&(M(e),a?.onBack())},children:[(0,x.jsx)(v,{className:`w-full`,"aria-label":`Execution history`,children:(0,x.jsx)(h,{})}),(0,x.jsxs)(_,{children:[(0,x.jsx)(m,{value:``,children:`Select execution`}),G.map(e=>(0,x.jsxs)(m,{value:e.id,children:[e.name,` · `,e.status.replaceAll(`-`,` `),` · `,new Date(e.startedAt).toLocaleString(),e.testStepId?` · step test`:``]},e.id))]})]})]}),U&&(0,x.jsxs)(x.Fragment,{children:[[`running`,`recovery-required`].includes(U.status)&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Cancel stops work; it does not undo changes.`}),(0,x.jsx)(t,{size:`sm`,variant:`destructive`,className:`justify-self-start`,disabled:F,onClick:()=>void J(`${C}/${j}/cancel`),children:`Cancel execution`})]}),U.status===`recovery-required`&&(0,x.jsx)(`p`,{children:`Ask the parent in chat to diagnose and recover this execution.`}),W&&(0,x.jsxs)(`section`,{"aria-label":`Workflow input actions`,className:`grid gap-2`,children:[(0,x.jsx)(`h4`,{className:`font-medium`,children:`Input requested in parent chat`}),(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The parent relays one request at a time using the normal composer controls. This pane stays on the execution so management actions remain available.`}),(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:V?.status===`dormant`||V?.status===`settled`?`Revive the parent manually to continue. The request will remain pending here.`:V?.status===`running`||V?.status===`awaiting`?`The request is queued behind the parent’s current turn.`:`The parent is preparing the next request.`}),(0,x.jsx)(t,{size:`sm`,variant:`outline`,className:`justify-self-start`,onClick:()=>document.querySelector(`[data-pane] [data-composer-input]`)?.focus(),children:`Go to parent chat`})]}),z.data&&(0,x.jsx)(y,{view:z.data,detailBase:`${C}/${j}`,transcriptBase:`${C}/${j}`,placement:n,mobileNavigation:a},`${e}/${j}`)]})]})}export{S as default};
1
+ import{a as e}from"./rolldown-runtime-B0Z9INg1.js";import{Pn as t,kr as n,n as r,t as i,wr as a}from"./workflow-api-BfExddae.js";import{C as o,S as s,_t as c,d as l,ht as u,pt as d,u as f,x as p}from"./workflows-DJqUuGyg.js";import{a as m,c as h,n as g,r as _,s as v}from"./switch-B00FEUA7.js";import{t as y}from"./index-CxdSb7k0.js";var b=e(n(),1),x=a();function S({sessionId:e,placement:n=`right`,mobileNavigation:a}){let S=i(`/api/workflows`),C=`/api/sessions/${encodeURIComponent(e)}/workflows`,w=i(C),[T,E]=(0,b.useState)(()=>c(e)),[D,O]=(0,b.useState)(T?.workflowId??``),[k,A]=(0,b.useState)(T?.input??{}),[j,M]=(0,b.useState)(``),[N,P]=(0,b.useState)(T?.error??``),[F,I]=(0,b.useState)(!1),[L,R]=(0,b.useState)(T!==void 0),z=i(j?`${C}/${j}`:void 0,1e3),{sessions:B}=d(),V=B.find(t=>t.id===e),H=S.data?.workflows.find(e=>e.id===D),U=z.data?.execution,W=!!(z.data?.enquiries.length||z.data?.permissions.length),G=[...w.data?.executions??[]].sort((e,t)=>t.startedAt-e.startedAt);(0,b.useEffect)(()=>{let t=c(e);E(t),O(t?.workflowId??``),A(t?.input??{}),M(``),P(t?.error??``),R(t!==void 0)},[e]),(0,b.useEffect)(()=>{if(j||!G.length)return;let e=G.find(e=>e.status===`running`||e.status===`recovery-required`);M((e??G[0]).id)},[j,w.data]);let K=``;try{H&&(s(H),o(H.inputSchema,k))}catch(e){K=p(e)}let q=H&&V&&H.backend!==V.backend,J=async(t,n)=>{I(!0);try{let i=await r(t,`POST`,n);i.execution&&(M(i.execution.id),R(!1),t===C&&(u(e),E(void 0))),P(`Request accepted`)}catch(e){P(p(e))}finally{I(!1)}};return(0,x.jsxs)(`section`,{className:`workflow-panel grid grid-cols-[minmax(0,1fr)] content-start gap-3 overflow-auto p-3 text-sm`,children:[(0,x.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,x.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Workflows`}),(0,x.jsx)(t,{size:`sm`,variant:`outline`,disabled:F||!w.data||w.data.occupied||V?.status===`ended`,onClick:()=>R(e=>!e),children:L?`Close`:`New workflow`})]}),(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Independent of parent chat. Steps share this Scope.`}),(S.error||w.error||z.error||N)&&(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,role:`status`,children:N||S.error||w.error||z.error}),T&&(0,x.jsxs)(`div`,{className:`rounded-lg border border-destructive/40 bg-destructive/5 p-3`,role:`alert`,children:[(0,x.jsx)(`p`,{className:`font-medium`,children:`Workflow did not start`}),(0,x.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`This Agent Session was kept. Review the preserved inputs below and retry here; retrying will not create another Agent Session.`})]}),L&&!w.data?.occupied&&(0,x.jsx)(`section`,{"aria-label":`New workflow`,children:(0,x.jsxs)(`div`,{className:`grid gap-3 pt-2`,children:[(0,x.jsxs)(g,{value:D,onValueChange:e=>{if(e===null)return;O(e);let t=S.data?.workflows.find(t=>t.id===e);A(t?l(t.inputSchema):{})},children:[(0,x.jsx)(v,{className:`w-full`,"aria-label":`Workflow`,children:(0,x.jsx)(h,{children:H?.name??`Select workflow`})}),(0,x.jsxs)(_,{children:[(0,x.jsx)(m,{value:``,children:`Select workflow`}),S.data?.workflows.map(e=>(0,x.jsx)(m,{value:e.id,children:e.name},e.id))]})]}),H&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(f,{schema:H.inputSchema,value:k,onChange:A}),q&&(0,x.jsxs)(`p`,{role:`alert`,children:[`This workflow requires Backend Adapter `,H.backend,`.`,` `,(0,x.jsx)(`a`,{className:`underline`,href:`#/new/${encodeURIComponent(H.backend)}`,children:`Create a matching Agent Session`}),`.`]}),K&&(0,x.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono text-xs text-destructive`,role:`alert`,children:K}),(0,x.jsx)(t,{size:`sm`,className:`justify-self-start`,disabled:F||!w.data||w.data.occupied||V?.status===`ended`||!!K||!!q,onClick:()=>void J(C,{workflowId:D,input:k,...T?{launchId:T.launchId,nameSession:!0}:{}}),children:T?`Retry workflow`:`Start workflow`})]})]})}),(0,x.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,x.jsx)(`span`,{className:`text-sm font-medium`,children:`Execution history`}),(0,x.jsxs)(g,{items:[{value:``,label:`Select execution`},...G.map(e=>({value:e.id,label:`${e.name} · ${e.status.replaceAll(`-`,` `)} · ${new Date(e.startedAt).toLocaleString()}${e.testStepId?` · step test`:``}`}))],disabled:F,value:j,onValueChange:e=>{e!==null&&(M(e),a?.onBack())},children:[(0,x.jsx)(v,{className:`w-full`,"aria-label":`Execution history`,children:(0,x.jsx)(h,{})}),(0,x.jsxs)(_,{children:[(0,x.jsx)(m,{value:``,children:`Select execution`}),G.map(e=>(0,x.jsxs)(m,{value:e.id,children:[e.name,` · `,e.status.replaceAll(`-`,` `),` · `,new Date(e.startedAt).toLocaleString(),e.testStepId?` · step test`:``]},e.id))]})]})]}),U&&(0,x.jsxs)(x.Fragment,{children:[[`running`,`recovery-required`].includes(U.status)&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Cancel stops work; it does not undo changes.`}),(0,x.jsx)(t,{size:`sm`,variant:`destructive`,className:`justify-self-start`,disabled:F,onClick:()=>void J(`${C}/${j}/cancel`),children:`Cancel execution`})]}),U.status===`recovery-required`&&(0,x.jsx)(`p`,{children:`Ask the parent in chat to diagnose and recover this execution.`}),W&&(0,x.jsxs)(`section`,{"aria-label":`Workflow input actions`,className:`grid gap-2`,children:[(0,x.jsx)(`h4`,{className:`font-medium`,children:`Input requested in parent chat`}),(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The parent relays one request at a time using the normal composer controls. This pane stays on the execution so management actions remain available.`}),(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:V?.status===`dormant`||V?.status===`settled`?`Revive the parent manually to continue. The request will remain pending here.`:V?.status===`running`||V?.status===`awaiting`?`The request is queued behind the parent’s current turn.`:`The parent is preparing the next request.`}),(0,x.jsx)(t,{size:`sm`,variant:`outline`,className:`justify-self-start`,onClick:()=>document.querySelector(`[data-pane] [data-composer-input]`)?.focus(),children:`Go to parent chat`})]}),z.data&&(0,x.jsx)(y,{view:z.data,detailBase:`${C}/${j}`,transcriptBase:`${C}/${j}`,placement:n,mobileNavigation:a},`${e}/${j}`)]})]})}export{S as default};
@@ -26,13 +26,13 @@
26
26
  document.documentElement.style.colorScheme = "light";
27
27
  }
28
28
  </script>
29
- <script type="module" crossorigin src="/assets/index-nIc09tKZ.js"></script>
29
+ <script type="module" crossorigin src="/assets/index-CxdSb7k0.js"></script>
30
30
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-B0Z9INg1.js">
31
31
  <link rel="modulepreload" crossorigin href="/assets/workflow-api-BfExddae.js">
32
- <link rel="modulepreload" crossorigin href="/assets/switch-DIogWclb.js">
33
- <link rel="modulepreload" crossorigin href="/assets/workflows-DHG-CIo3.js">
32
+ <link rel="modulepreload" crossorigin href="/assets/switch-B00FEUA7.js">
33
+ <link rel="modulepreload" crossorigin href="/assets/workflows-DJqUuGyg.js">
34
34
  <link rel="stylesheet" crossorigin href="/assets/workflows-Bb90N0XJ.css">
35
- <link rel="stylesheet" crossorigin href="/assets/index-BWKZK5HD.css">
35
+ <link rel="stylesheet" crossorigin href="/assets/index-BqZ_iUmY.css">
36
36
  </head>
37
37
  <body><div id="root"></div></body>
38
38
  </html>
@@ -1,289 +0,0 @@
1
- import { execFile } from "node:child_process";
2
- import { createHash } from "node:crypto";
3
- import { lstat, readlink, access } from "node:fs/promises";
4
- import { createReadStream } from "node:fs";
5
- import { resolve } from "node:path";
6
- import { promisify } from "node:util";
7
- import { head, isRepository, run, GIT_READ_TIMEOUT_MS, GIT_WRITE_TIMEOUT_MS } from "./git.js";
8
- import { localStack, localStacks } from "./stack-metadata.js";
9
- const exec = promisify(execFile);
10
- export const gh = async (scope, args) => {
11
- try {
12
- return (await exec("gh", args, {
13
- cwd: scope,
14
- timeout: GIT_WRITE_TIMEOUT_MS,
15
- maxBuffer: 2 << 20,
16
- env: { ...process.env, GH_PROMPT_DISABLED: "1", GIT_TERMINAL_PROMPT: "0", ...(args[0] === "stack" ? { GIT_EDITOR: "true", GIT_SEQUENCE_EDITOR: "true" } : {}) },
17
- })).stdout;
18
- }
19
- catch (error) {
20
- const failure = error;
21
- if (failure.code === "ENOENT")
22
- throw new Error("GitHub CLI is missing. Install gh on the Session Host.");
23
- const detail = (args[0] === "stack" ? [failure.stdout, failure.stderr].filter(Boolean).join("\n").trim() : failure.stderr?.trim()) || failure.message || "Unknown error";
24
- const requestFailed = /HTTP (?:429|5\d\d)|connection|timed? out|network|TLS|certificate|could not resolve/i.test(detail);
25
- if ((failure.code === 4 && args[0] !== "stack") || (args[0] === "auth" && !requestFailed)) {
26
- throw new Error(`GitHub authentication failed. Run gh auth login on the Session Host. ${detail}`);
27
- }
28
- throw new Error(`GitHub request failed: ${detail}`);
29
- }
30
- };
31
- async function git(scope, args, write = false) {
32
- const result = await run(scope, args, write ? GIT_WRITE_TIMEOUT_MS : GIT_READ_TIMEOUT_MS);
33
- if (!result.ok) {
34
- if (result.failure.message.includes("ENOENT"))
35
- throw new Error("Git is missing. Install git on the Session Host.");
36
- throw new Error(`Git ${result.failure.attempted} failed: ${result.failure.message}`);
37
- }
38
- return result.value;
39
- }
40
- async function files(scope) {
41
- const raw = await git(scope, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"]);
42
- return raw.split("\0").filter(Boolean).map((line) => ({ status: line.slice(0, 2), path: line.slice(3) }));
43
- }
44
- export async function snapshot(scope) {
45
- if (!isRepository(scope))
46
- throw new Error("This Scope is not a Git repository.");
47
- const branch = await head(scope);
48
- if (!branch.ok)
49
- throw new Error(branch.failure.message.includes("ENOENT") ? "Git is missing. Install git on the Session Host." : branch.failure.message);
50
- if (branch.value.detached)
51
- throw new Error("HEAD is detached. Switch to a branch before publishing.");
52
- const commit = await run(scope, ["rev-parse", "--verify", "HEAD"], GIT_READ_TIMEOUT_MS);
53
- if (!commit.ok)
54
- throw new Error("This branch has no commits. Make the first commit before publishing.");
55
- const changed = await files(scope);
56
- if (changed.some((file) => file.status.includes("U") || ["AA", "DD"].includes(file.status))) {
57
- throw new Error("Resolve merge conflicts before publishing.");
58
- }
59
- const index = await git(scope, ["ls-files", "--stage", "-z"]);
60
- if (index.split("\0").some((entry) => entry.startsWith("160000 "))) {
61
- throw new Error("Publishing repositories with submodules is not supported. Use Git directly.");
62
- }
63
- for (const operation of ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD"]) {
64
- const active = await run(scope, ["rev-parse", "--verify", "-q", operation], GIT_READ_TIMEOUT_MS);
65
- if (active.ok)
66
- throw new Error("Finish the current Git operation before publishing.");
67
- }
68
- for (const operation of ["rebase-merge", "rebase-apply", "sequencer"]) {
69
- const path = (await git(scope, ["rev-parse", "--git-path", operation])).trim();
70
- const active = await access(resolve(scope, path)).then(() => true, () => false);
71
- if (active)
72
- throw new Error("Finish the current Git operation before publishing.");
73
- }
74
- const staged = await git(scope, ["diff", "--cached", "--binary", "--no-ext-diff", "--no-textconv"]);
75
- const working = await git(scope, ["diff", "--binary", "--no-ext-diff", "--no-textconv"]);
76
- const content = createHash("sha256");
77
- let untracked = "";
78
- for (const file of [...changed].sort((a, b) => a.path.localeCompare(b.path))) {
79
- const path = resolve(scope, file.path);
80
- const stat = await lstat(path).catch((error) => {
81
- if (error.code === "ENOENT" || error.code === "ENOTDIR")
82
- return undefined;
83
- throw error;
84
- });
85
- content.update(JSON.stringify({ path: file.path, mode: stat?.mode, size: stat?.size }));
86
- if (!stat)
87
- continue;
88
- if (!stat.isFile() && !stat.isSymbolicLink())
89
- throw new Error(`Cannot publish this file type: ${file.path}`);
90
- if (stat.isSymbolicLink())
91
- content.update(await readlink(path));
92
- else {
93
- let preview = "";
94
- for await (const chunk of createReadStream(path)) {
95
- content.update(chunk);
96
- if (file.status === "??" && preview.length < 4_000 && untracked.length < 8_000)
97
- preview += chunk.toString("utf8").slice(0, 4_000 - preview.length);
98
- }
99
- if (preview && !preview.includes("\0"))
100
- untracked += `\nUntracked ${JSON.stringify(file.path)}:\n${preview}`.slice(0, 8_000 - untracked.length);
101
- }
102
- }
103
- const contentFingerprint = content.digest("hex");
104
- const fingerprint = createHash("sha256").update(JSON.stringify({ commit: commit.value, changed, index, staged, working, contentFingerprint })).digest("hex");
105
- return {
106
- fingerprint, contentFingerprint, unstaged: working !== "", files: changed, branch: branch.value.name, commit: commit.value.trim(),
107
- input: `${JSON.stringify(changed)}\n${staged}\n${working}\n${untracked}`,
108
- };
109
- }
110
- export async function repositoryTarget(scope, github = gh) {
111
- const remotes = (await git(scope, ["remote"])).trim().split("\n").filter(Boolean);
112
- if (remotes.length === 0)
113
- throw new Error("No remote is configured. Add a GitHub remote before publishing.");
114
- if (remotes.length !== 1)
115
- throw new Error("Publish requires exactly one remote. Select and publish the remote with Git directly.");
116
- const remote = remotes[0];
117
- const urls = (await git(scope, ["remote", "get-url", "--all", remote])).trim().split("\n");
118
- const pushes = (await git(scope, ["remote", "get-url", "--push", "--all", remote])).trim().split("\n");
119
- if (urls.length !== 1 || pushes.length !== 1 || pushes[0] !== urls[0]) {
120
- throw new Error("Fetch and push remotes differ or are ambiguous. Publish with Git directly.");
121
- }
122
- const url = urls[0];
123
- const match = /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?$/.exec(url);
124
- if (!match)
125
- throw new Error("This remote is not a supported github.com repository URL.");
126
- const repo = match[1];
127
- await github(scope, ["auth", "status", "--hostname", "github.com"]);
128
- const info = JSON.parse(await github(scope, ["repo", "view", repo, "--json", "id,defaultBranchRef,isFork"]));
129
- if (info.isFork)
130
- throw new Error("Fork publishing is not supported. Publish with gh directly to select the base repository.");
131
- if (!info.defaultBranchRef?.name)
132
- throw new Error("GitHub has no default branch. Create it before publishing.");
133
- return { remote, url, repo, defaultBranch: info.defaultBranchRef.name, id: info.id };
134
- }
135
- export async function target(scope, branch, github = gh) {
136
- const { remote, url, repo, defaultBranch, id } = await repositoryTarget(scope, github);
137
- const prs = JSON.parse(await github(scope, ["pr", "list", "--repo", repo, "--head", branch, "--state", "open", "--json", "number,url,title,isDraft,reviewDecision,statusCheckRollup,headRepository"]));
138
- if (prs.length > 1)
139
- throw new Error("More than one pull request matches this branch. Publish with gh directly.");
140
- const pr = prs[0];
141
- if (pr && branch === defaultBranch)
142
- throw new Error("The default branch already heads a pull request. Publish with gh directly to select the intended branch.");
143
- if (pr)
144
- pr.statusCheckRollup ??= [];
145
- if (pr && (!id || !pr.headRepository?.id)) {
146
- throw new Error("Cannot verify PR source: GitHub did not return repository IDs. Publish with gh directly.");
147
- }
148
- if (pr && pr.headRepository?.id !== id) {
149
- throw new Error("The pull request uses a different head repository. Publish with gh directly.");
150
- }
151
- const stack = await localStack(scope, branch);
152
- let baseBranch;
153
- if (stack) {
154
- try {
155
- await github(scope, ["stack", "--help"]);
156
- }
157
- catch (error) {
158
- throw new Error(`This branch belongs to a stack. Install gh stack on the Session Host before publishing. ${error instanceof Error ? error.message : String(error)}`);
159
- }
160
- const index = stack.branches.findIndex(b => b.branch === branch);
161
- baseBranch = stack.branches.slice(0, index).filter(b => !b.pullRequest?.merged).at(-1)?.branch ?? stack.trunk.branch;
162
- }
163
- return { remote, url, repo, defaultBranch, ...(baseBranch ? { baseBranch } : {}), ...(pr ? { pr } : {}) };
164
- }
165
- async function remoteBranchExists(scope, destination, branch, github) {
166
- const refs = JSON.parse(await github(scope, ["api", `repos/${destination.repo}/git/matching-refs/heads/${branch.split("/").map(encodeURIComponent).join("/")}`]));
167
- return refs.some(ref => ref.ref === `refs/heads/${branch}`);
168
- }
169
- export async function canNameBranch(scope, branch, destination, github = gh) {
170
- if (branch === destination.defaultBranch)
171
- return true;
172
- if (destination.pr || (await localStacks(scope)).some(stack => stack.trunk.branch === branch || stack.branches.some(item => item.branch === branch)))
173
- return false;
174
- const tracked = await run(scope, ["show-ref", "--verify", "--quiet", `refs/remotes/${destination.remote}/${branch}`], GIT_READ_TIMEOUT_MS);
175
- if (tracked.ok || await remoteBranchExists(scope, destination, branch, github))
176
- return false;
177
- const prs = JSON.parse(await github(scope, ["pr", "list", "--repo", destination.repo, "--head", branch, "--state", "all", "--json", "number"]));
178
- return prs.length === 0;
179
- }
180
- export async function branchChanges(scope, destination) {
181
- let base = destination.baseBranch ? `refs/heads/${destination.baseBranch}` : `refs/remotes/${destination.remote}/${destination.defaultBranch}`;
182
- const remote = await run(scope, ["rev-parse", "--verify", base], GIT_READ_TIMEOUT_MS);
183
- if (!remote.ok)
184
- base = destination.baseBranch ? `refs/remotes/${destination.remote}/${destination.baseBranch}` : `refs/heads/${destination.defaultBranch}`;
185
- const known = await run(scope, ["rev-parse", "--verify", base], GIT_READ_TIMEOUT_MS);
186
- if (!known.ok)
187
- throw new Error(`Fetch the ${destination.baseBranch ? "stack parent" : "default"} branch before publishing so its changes can be reviewed.`);
188
- const range = `${base}...HEAD`;
189
- const raw = (await git(scope, ["diff", "--name-status", "-z", "--no-renames", range, "--"])).split("\0").filter(Boolean);
190
- const files = [];
191
- for (let index = 0; index < raw.length; index += 2)
192
- files.push({ status: raw[index], path: raw[index + 1] });
193
- const commits = (await git(scope, ["log", "--format=%h %s", `${base}..HEAD`, "--"])).trim().split("\n").filter(Boolean);
194
- const diff = await git(scope, ["diff", "--binary", "--no-ext-diff", "--no-textconv", range, "--"]);
195
- return { files, commits, input: `${commits.join("\n")}\n${diff}` };
196
- }
197
- export async function gitStatus(scope, github = gh) {
198
- if (!isRepository(scope))
199
- return { repository: false, files: [] };
200
- const status = { repository: true, files: [] };
201
- try {
202
- status.files = await files(scope);
203
- const branch = await head(scope);
204
- if (!branch.ok)
205
- throw new Error(branch.failure.message);
206
- status.branch = branch.value;
207
- if (branch.value.detached)
208
- throw new Error("HEAD is detached. Switch to a branch before publishing.");
209
- const destination = await target(scope, branch.value.name, github);
210
- if (destination.pr)
211
- status.pr = destination.pr;
212
- }
213
- catch (error) {
214
- status.problem = error instanceof Error ? error.message : String(error);
215
- }
216
- return status;
217
- }
218
- export async function publish(scope, reviewed, destination, input, github = gh) {
219
- const result = { pushed: false };
220
- try {
221
- const current = await snapshot(scope);
222
- if (current.branch !== reviewed.branch || current.fingerprint !== reviewed.fingerprint)
223
- throw new Error("Reviewed changes have changed. Open Publish again.");
224
- const freshTarget = await target(scope, current.branch, github);
225
- if (freshTarget.remote !== destination.remote || freshTarget.url !== destination.url || freshTarget.repo !== destination.repo || freshTarget.defaultBranch !== destination.defaultBranch || freshTarget.baseBranch !== destination.baseBranch || freshTarget.pr?.number !== destination.pr?.number)
226
- throw new Error("The remote, base branch, or pull request has changed. Open Publish again.");
227
- if (typeof input.commitMessage !== "string" || typeof input.title !== "string" || typeof input.body !== "string" || !input.title.trim() || (current.files.length > 0 && !input.commitMessage.trim())) {
228
- throw new Error("A commit message and pull request title are required.");
229
- }
230
- const checked = await snapshot(scope);
231
- if (checked.branch !== current.branch || checked.fingerprint !== current.fingerprint)
232
- throw new Error("Reviewed changes have changed. Open Publish again.");
233
- let branch = current.branch;
234
- const requestedBranch = typeof input.branch === "string" ? input.branch.trim() : "";
235
- const creating = branch === destination.defaultBranch;
236
- if (creating || (requestedBranch && requestedBranch !== branch)) {
237
- if (!requestedBranch || requestedBranch.startsWith("-") || requestedBranch === destination.defaultBranch || requestedBranch.includes("@{")) {
238
- throw new Error("Enter a valid new feature branch name before publishing.");
239
- }
240
- if (!await canNameBranch(scope, branch, freshTarget, github))
241
- throw new Error("This branch has a pull request, remote ref, or stack registration and cannot be renamed.");
242
- await git(scope, ["check-ref-format", "--branch", requestedBranch]);
243
- const local = await run(scope, ["show-ref", "--verify", "--quiet", `refs/heads/${requestedBranch}`], GIT_READ_TIMEOUT_MS);
244
- if (local.ok)
245
- throw new Error("That feature branch already exists locally. Choose a new branch name.");
246
- if (await remoteBranchExists(scope, destination, requestedBranch, github))
247
- throw new Error("That feature branch already exists on GitHub. Choose a new branch name or switch to the existing branch before publishing.");
248
- const beforeSwitch = await snapshot(scope);
249
- if (beforeSwitch.branch !== reviewed.branch || beforeSwitch.fingerprint !== reviewed.fingerprint)
250
- throw new Error("Reviewed changes have changed. Open Publish again.");
251
- await git(scope, creating ? ["switch", "-c", requestedBranch] : ["branch", "-m", requestedBranch], true);
252
- branch = requestedBranch;
253
- result.branch = branch;
254
- const afterSwitch = await snapshot(scope);
255
- if (afterSwitch.branch !== branch || afterSwitch.fingerprint !== reviewed.fingerprint) {
256
- throw new Error(`The branch was ${creating ? "created" : "renamed"}, but its changes differ after checkout hooks. Open Publish again.`);
257
- }
258
- }
259
- if (current.files.length > 0) {
260
- await git(scope, ["add", "--all", "--", "."], true);
261
- const tree = (await git(scope, ["write-tree"])).trim();
262
- const staged = await snapshot(scope);
263
- if (staged.unstaged || staged.contentFingerprint !== reviewed.contentFingerprint || staged.branch !== branch || staged.commit !== reviewed.commit)
264
- throw new Error("Changes moved while staging. Review the index and open Publish again.");
265
- await git(scope, ["commit", "-m", input.commitMessage], true);
266
- result.committed = (await git(scope, ["rev-parse", "HEAD"])).trim();
267
- if ((await git(scope, ["rev-parse", `${result.committed}^{tree}`])).trim() !== tree)
268
- throw new Error("Commit hooks changed the committed files. Review the commit before pushing.");
269
- if ((await git(scope, ["show", "--no-patch", "--format=%P", result.committed])).trim() !== reviewed.commit)
270
- throw new Error("The commit parents changed. Review the commit before pushing.");
271
- if ((await files(scope)).length > 0)
272
- throw new Error("Commit completed, but hooks or another process left changes. Review them before pushing.");
273
- }
274
- const finalHead = await head(scope);
275
- if (!finalHead.ok || finalHead.value.detached || finalHead.value.name !== branch)
276
- throw new Error("The branch changed before pushing. Open Publish again.");
277
- await git(scope, ["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential", "push", "--no-follow-tags", destination.url, `${result.committed ?? reviewed.commit}:refs/heads/${branch}`], true);
278
- result.pushed = true;
279
- if (destination.pr)
280
- result.url = destination.pr.url;
281
- else {
282
- result.url = (await github(scope, ["pr", "create", "--repo", destination.repo, "--base", destination.baseBranch ?? destination.defaultBranch, "--head", branch, "--title", input.title, "--body", input.body, ...(input.ready === true ? [] : ["--draft"])])).trim();
283
- }
284
- }
285
- catch (error) {
286
- result.error = error instanceof Error ? error.message : String(error);
287
- }
288
- return result;
289
- }
@@ -1 +0,0 @@
1
- export {};