@vpxa/aikit 0.1.32 → 0.1.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vpxa/aikit",
3
- "version": "0.1.32",
3
+ "version": "0.1.33",
4
4
  "type": "module",
5
5
  "description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
6
6
  "license": "MIT",
@@ -1,11 +1,19 @@
1
- import { FlowFormatAdapter, FlowManifest } from "../types.js";
1
+ import { FlowFormatAdapter, FlowManifest, FlowParseOptions } from "../types.js";
2
2
 
3
3
  //#region packages/flows/src/adapters/claude-plugin.d.ts
4
4
  declare class ClaudePluginAdapter implements FlowFormatAdapter {
5
5
  readonly format: "claude-plugin";
6
6
  detect(sourceDir: string): boolean;
7
- parse(sourceDir: string): Promise<FlowManifest>;
7
+ parse(sourceDir: string, options?: FlowParseOptions): Promise<FlowManifest>;
8
8
  private discoverSteps;
9
+ /**
10
+ * Copy supporting subdirectories (references/, assets/, scripts/) from
11
+ * skills/<step>/ to steps/<step>/ so that relative paths inside the
12
+ * step README.md resolve correctly at runtime.
13
+ *
14
+ * When `force` is true, existing copies are replaced (used during updates).
15
+ */
16
+ private syncStepAssets;
9
17
  private discoverAgents;
10
18
  }
11
19
  //#endregion
@@ -1 +1 @@
1
- import{existsSync as e,readFileSync as t,readdirSync as n}from"node:fs";import{basename as r,join as i}from"node:path";const a=[`spec`,`plan`,`task`,`execute`,`verify`];var o=class{format=`claude-plugin`;detect(t){return e(i(t,`.claude-plugin`,`plugin.json`))}async parse(e){let n=i(e,`.claude-plugin`,`plugin.json`),a=JSON.parse(t(n,`utf-8`)),o=this.discoverSteps(e),s=this.discoverAgents(e);return{name:a.name??r(e),version:a.version??`1.0.0`,description:a.description??``,author:a.author,steps:o,agents:s,artifacts_dir:`.spec`,install:[]}}discoverSteps(t){let r=i(t,`skills`);if(!e(r))return[];let o=n(r,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort((e,t)=>{let n=a.indexOf(e),r=a.indexOf(t);return n!==-1&&r!==-1?n-r:n===-1?r===-1?e.localeCompare(t):1:-1});return o.map((e,t)=>({id:e,name:e.charAt(0).toUpperCase()+e.slice(1),instruction:`steps/${e}/README.md`,produces:[`${e}.md`],requires:t>0?[o[t-1]]:[],agents:[],description:`${e} step`}))}discoverAgents(t){let r=i(t,`agents`);return e(r)?n(r,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>`agents/${e.name}`):[]}};export{o as ClaudePluginAdapter};
1
+ import{cpSync as e,existsSync as t,readFileSync as n,readdirSync as r,rmSync as i}from"node:fs";import{basename as a,join as o}from"node:path";const s=[`spec`,`plan`,`task`,`execute`,`verify`];var c=class{format=`claude-plugin`;detect(e){return t(o(e,`.claude-plugin`,`plugin.json`))}async parse(e,t){let r=o(e,`.claude-plugin`,`plugin.json`),i=JSON.parse(n(r,`utf-8`)),s=this.discoverSteps(e),c=this.discoverAgents(e);return this.syncStepAssets(e,s,t?.forceAssetSync),{name:i.name??a(e),version:i.version??`1.0.0`,description:i.description??``,author:i.author,steps:s,agents:c,artifacts_dir:`.spec`,install:[]}}discoverSteps(e){let n=o(e,`skills`);if(!t(n))return[];let i=r(n,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort((e,t)=>{let n=s.indexOf(e),r=s.indexOf(t);return n!==-1&&r!==-1?n-r:n===-1?r===-1?e.localeCompare(t):1:-1});return i.map((e,t)=>({id:e,name:e.charAt(0).toUpperCase()+e.slice(1),instruction:`steps/${e}/README.md`,produces:[`${e}.md`],requires:t>0?[i[t-1]]:[],agents:[],description:`${e} step`}))}syncStepAssets(n,r,a){let s=[`references`,`assets`,`scripts`];for(let c of r)for(let r of s){let s=o(n,`skills`,c.id,r),l=o(n,`steps`,c.id,r);if(t(s)){if(t(l)){if(!a)continue;i(l,{recursive:!0,force:!0})}e(s,l,{recursive:!0})}}}discoverAgents(e){let n=o(e,`agents`);return t(n)?r(n,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>`agents/${e.name}`):[]}};export{c as ClaudePluginAdapter};
@@ -28,6 +28,23 @@ declare class GitInstaller {
28
28
  * Processes the `install[]` field from flow.json.
29
29
  */
30
30
  runInstallDeps(installEntries: string[]): FlowResult;
31
+ /**
32
+ * Get the current HEAD commit SHA for a local git repo.
33
+ */
34
+ getLocalCommit(installPath: string): string | null;
35
+ /**
36
+ * Get the latest commit SHA on the remote default branch.
37
+ * Uses `git ls-remote` so it doesn't modify the working tree.
38
+ */
39
+ getRemoteCommit(installPath: string): string | null;
40
+ /**
41
+ * Check whether the remote has commits newer than the local HEAD.
42
+ */
43
+ hasUpdates(installPath: string): FlowResult<{
44
+ localCommit: string;
45
+ remoteCommit: string;
46
+ hasUpdates: boolean;
47
+ }>;
31
48
  /** Extract repo name from git URL */
32
49
  private repoNameFromUrl;
33
50
  private ensureFlowsDir;
@@ -1,2 +1,2 @@
1
1
  import{cpSync as e,existsSync as t,mkdirSync as n,rmSync as r}from"node:fs";import{basename as i,join as a}from"node:path";import{execSync as o,spawnSync as s}from"node:child_process";function c(e){if(!e||typeof e!=`object`||!(`stderr`in e))return``;let t=e.stderr;return Buffer.isBuffer(t)?t.toString().trim():typeof t==`string`?t.trim():``}function l(e){try{return new URL(e).hostname}catch{}return e.match(/^[^@]+@([^:]+):/)?.[1]??`<host>`}function u(e,t,n){let r=[`Git operation failed for: ${e}`],i=l(e),a=t.includes(`ETIMEDOUT`)||t.includes(`SIGTERM`)||t.toLowerCase().includes(`timed out`),o=n.includes(`Authentication failed`)||n.includes(`could not read Username`)||n.includes(`terminal prompts disabled`)||n.includes(`401`)||n.includes(`403`)||n.includes(`Permission denied`),s=n.includes(`SSL certificate`)||n.includes(`unable to access`)&&n.includes(`SSL`),c=n.includes(`Could not resolve host`)||n.includes(`Name or service not known`),u=n.includes(`SAML`)||n.includes(`single sign-on`);return o||u?(r.push(``),r.push(`Cause: Authentication required or credentials not configured.`),r.push(``),r.push(`To fix this, ensure git can access this repository:`),r.push(``),r.push(` Option 1 - SSH key:`),r.push(` 1. Generate an SSH key: ssh-keygen -t ed25519`),r.push(` 2. Add the public key to your Git hosting account`),r.push(` 3. Use the SSH URL instead: git@<host>:<org>/<repo>.git`),r.push(``),r.push(` Option 2 - Personal Access Token (PAT):`),r.push(` 1. Create a PAT in your Git hosting Settings > Developer settings > Tokens`),r.push(` 2. For GitHub Enterprise with SAML SSO, authorize the token for your org`),r.push(` 3. Configure git credentials:`),r.push(` git config --global credential.helper store`),r.push(` git clone ${e} (enter PAT as password)`),r.push(``),r.push(` Option 3 - Git Credential Manager:`),r.push(` 1. Install: https://github.com/git-ecosystem/git-credential-manager`),r.push(` 2. Run: git clone ${e}`),r.push(` 3. Follow the browser-based auth prompt`),r.push(``),r.push(`After configuring credentials, retry: aikit flow add ${e}`)):a?(r.push(``),r.push(`Cause: Connection timed out - the server did not respond within 60 seconds.`),r.push(``),r.push(`Possible reasons:`),r.push(` - The repository requires VPN access. Ensure your VPN is connected`),r.push(` - The host is behind a firewall or corporate proxy`),r.push(` - The URL may be incorrect`),r.push(``),r.push(`Diagnostics:`),r.push(` 1. Verify the URL is correct: ${e}`),r.push(` 2. Test connectivity: git ls-remote ${e}`),r.push(` 3. If behind a proxy, configure git:`),r.push(` git config --global http.proxy http://proxy:port`),r.push(``),r.push(`If this is a corporate/internal host, you may need to:`),r.push(` - Connect to the corporate VPN`),r.push(` - Add the host to your SSH config or git config`),r.push(` - Ask your IT team to allowlist your machine`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):s?(r.push(``),r.push(`Cause: SSL/TLS certificate verification failed.`),r.push(``),r.push(`This often happens with corporate proxies or self-signed certificates.`),r.push(``),r.push(`To fix:`),r.push(` 1. If your company uses a custom CA, add it:`),r.push(` git config --global http.sslCAInfo /path/to/ca-bundle.crt`),r.push(` 2. As a last resort (not recommended for production):`),r.push(` git config --global http.sslVerify false`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):c?(r.push(``),r.push(`Cause: Cannot resolve hostname.`),r.push(``),r.push(`Check:`),r.push(` 1. Is the URL correct? ${e}`),r.push(` 2. Are you connected to the internet/VPN?`),r.push(` 3. Can you resolve the host? ping ${i}`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):(r.push(``),r.push(`Error: ${t}`),n&&r.push(`Details: ${n}`),r.push(``),r.push(`Troubleshooting:`),r.push(` 1. Verify the URL is a valid git repository: git ls-remote ${e}`),r.push(` 2. Check your git credentials and network connectivity`),r.push(` 3. If the repo requires auth, configure credentials first (PAT or SSH key)`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)),r.join(`
2
- `)}function d(){try{return s(`git`,[`credential-manager`,`--version`],{stdio:`pipe`,timeout:5e3}).status===0}catch{return!1}}function f(e,t){let n=`${e}\n${t}`.toLowerCase();return n.includes(`authentication failed`)||n.includes(`could not read username`)||n.includes(`saml sso`)||n.includes(`terminal prompts disabled`)||n.includes(`host key verification failed`)||n.includes(`permission denied`)||n.includes(`403`)||n.includes(`401`)}var p=class{constructor(e){this.flowsDir=e}clone(e){let n=this.repoNameFromUrl(e),i=a(this.flowsDir,n);if(t(i))if(!t(a(i,`.git`)))r(i,{recursive:!0,force:!0});else return{success:!1,error:`Flow "${n}" already installed at ${i}. Use update instead.`};try{return this.ensureFlowsDir(),o(`git clone --depth 1 ${e} ${i}`,{stdio:`pipe`,timeout:6e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:``}}),{success:!0,data:i}}catch(n){t(i)&&r(i,{recursive:!0,force:!0});let a=c(n),o=n instanceof Error?n.message:String(n);if(f(o,a)&&d()){let n=l(e)||e;console.log(`\nAuthentication required for ${n}.\nGit Credential Manager detected - opening browser for login...\n(If a browser window does not open, check your terminal for a device code.)\n`);try{if(this.ensureFlowsDir(),s(`git`,[`clone`,`--depth`,`1`,e,i],{stdio:`inherit`,timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:`1`}}).status===0)return{success:!0,data:i};t(i)&&r(i,{recursive:!0,force:!0})}catch{t(i)&&r(i,{recursive:!0,force:!0})}}return{success:!1,error:u(e,o,a)}}}update(e){if(!t(e))return{success:!1,error:`Install path not found: ${e}`};try{return o(`git pull --ff-only`,{cwd:e,stdio:`pipe`,timeout:6e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:``}}),{success:!0}}catch(t){let n=e;try{n=o(`git remote get-url origin`,{cwd:e,stdio:`pipe`,timeout:1e4}).toString().trim()}catch{}let r=c(t),i=t instanceof Error?t.message:String(t);if(f(i,r)&&d()){let t=l(n)||n;console.log(`\nAuthentication required for ${t}.\nGit Credential Manager detected - opening browser for login...\n`);try{if(s(`git`,[`pull`,`--ff-only`],{cwd:e,stdio:`inherit`,timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:`1`}}).status===0)return{success:!0}}catch{}}return{success:!1,error:u(n,i,r)}}}copyLocal(n,r){let i=a(this.flowsDir,r);if(t(i))return{success:!1,error:`Flow "${r}" already installed at ${i}`};try{return this.ensureFlowsDir(),e(n,i,{recursive:!0}),{success:!0,data:i}}catch(e){return{success:!1,error:`Copy failed: ${e instanceof Error?e.message:String(e)}`}}}remove(e){if(!t(e))return{success:!0};try{return r(e,{recursive:!0,force:!0}),{success:!0}}catch(e){return{success:!1,error:`Remove failed: ${e instanceof Error?e.message:String(e)}`}}}runInstallDeps(e){for(let t of e)try{if(t.startsWith(`npm:`)){o(`npx skills add ${t.slice(4)} -g`,{stdio:`pipe`,timeout:12e4});continue}if(t.endsWith(`.git`)||t.includes(`github.com`)){o(`npx skills add ${t} -g`,{stdio:`pipe`,timeout:12e4});continue}return{success:!1,error:`Unknown install entry format: ${t}`}}catch(e){return{success:!1,error:`Install dependency failed for "${t}": ${e instanceof Error?e.message:String(e)}`}}return{success:!0}}repoNameFromUrl(e){return i(e).replace(/\.git$/,``)}ensureFlowsDir(){t(this.flowsDir)||n(this.flowsDir,{recursive:!0})}};export{p as GitInstaller};
2
+ `)}function d(){try{return s(`git`,[`credential-manager`,`--version`],{stdio:`pipe`,timeout:5e3}).status===0}catch{return!1}}function f(e,t){let n=`${e}\n${t}`.toLowerCase();return n.includes(`authentication failed`)||n.includes(`could not read username`)||n.includes(`saml sso`)||n.includes(`terminal prompts disabled`)||n.includes(`host key verification failed`)||n.includes(`permission denied`)||n.includes(`403`)||n.includes(`401`)}var p=class{constructor(e){this.flowsDir=e}clone(e){let n=this.repoNameFromUrl(e),i=a(this.flowsDir,n);if(t(i))if(!t(a(i,`.git`)))r(i,{recursive:!0,force:!0});else return{success:!1,error:`Flow "${n}" already installed at ${i}. Use update instead.`};try{return this.ensureFlowsDir(),o(`git clone --depth 1 ${e} ${i}`,{stdio:`pipe`,timeout:6e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:``}}),{success:!0,data:i}}catch(n){t(i)&&r(i,{recursive:!0,force:!0});let a=c(n),o=n instanceof Error?n.message:String(n);if(f(o,a)&&d()){let n=l(e)||e;console.log(`\nAuthentication required for ${n}.\nGit Credential Manager detected - opening browser for login...\n(If a browser window does not open, check your terminal for a device code.)\n`);try{if(this.ensureFlowsDir(),s(`git`,[`clone`,`--depth`,`1`,e,i],{stdio:`inherit`,timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:`1`}}).status===0)return{success:!0,data:i};t(i)&&r(i,{recursive:!0,force:!0})}catch{t(i)&&r(i,{recursive:!0,force:!0})}}return{success:!1,error:u(e,o,a)}}}update(e){if(!t(e))return{success:!1,error:`Install path not found: ${e}`};try{return o(`git pull --ff-only`,{cwd:e,stdio:`pipe`,timeout:6e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:``}}),{success:!0}}catch(t){let n=e;try{n=o(`git remote get-url origin`,{cwd:e,stdio:`pipe`,timeout:1e4}).toString().trim()}catch{}let r=c(t),i=t instanceof Error?t.message:String(t);if(f(i,r)&&d()){let t=l(n)||n;console.log(`\nAuthentication required for ${t}.\nGit Credential Manager detected - opening browser for login...\n`);try{if(s(`git`,[`pull`,`--ff-only`],{cwd:e,stdio:`inherit`,timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:`1`}}).status===0)return{success:!0}}catch{}}return{success:!1,error:u(n,i,r)}}}copyLocal(n,r){let i=a(this.flowsDir,r);if(t(i))return{success:!1,error:`Flow "${r}" already installed at ${i}`};try{return this.ensureFlowsDir(),e(n,i,{recursive:!0}),{success:!0,data:i}}catch(e){return{success:!1,error:`Copy failed: ${e instanceof Error?e.message:String(e)}`}}}remove(e){if(!t(e))return{success:!0};try{return r(e,{recursive:!0,force:!0}),{success:!0}}catch(e){return{success:!1,error:`Remove failed: ${e instanceof Error?e.message:String(e)}`}}}runInstallDeps(e){for(let t of e)try{if(t.startsWith(`npm:`)){o(`npx skills add ${t.slice(4)} -g`,{stdio:`pipe`,timeout:12e4});continue}if(t.endsWith(`.git`)||t.includes(`github.com`)){o(`npx skills add ${t} -g`,{stdio:`pipe`,timeout:12e4});continue}return{success:!1,error:`Unknown install entry format: ${t}`}}catch(e){return{success:!1,error:`Install dependency failed for "${t}": ${e instanceof Error?e.message:String(e)}`}}return{success:!0}}getLocalCommit(e){try{return o(`git rev-parse HEAD`,{cwd:e,stdio:`pipe`,timeout:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}}).toString().trim()||null}catch{return null}}getRemoteCommit(e){try{return o(`git ls-remote origin HEAD`,{cwd:e,stdio:`pipe`,timeout:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}}).toString().trim().split(/\s+/)[0]||null}catch{return null}}hasUpdates(e){let t=this.getLocalCommit(e);if(!t)return{success:!1,error:`Could not determine local commit (not a git repo?)`};let n=this.getRemoteCommit(e);return n?{success:!0,data:{localCommit:t,remoteCommit:n,hasUpdates:t!==n}}:{success:!1,error:`Could not reach remote to check for updates`}}repoNameFromUrl(e){return i(e).replace(/\.git$/,``)}ensureFlowsDir(){t(this.flowsDir)||n(this.flowsDir,{recursive:!0})}};export{p as GitInstaller};
@@ -1,4 +1,4 @@
1
- import { FlowFormat, FlowFormatAdapter, FlowManifest, FlowRegistry, FlowRegistryEntry, FlowResult, FlowSourceType, FlowState, FlowStatus, FlowStep, StepAction } from "./types.js";
1
+ import { FlowFormat, FlowFormatAdapter, FlowManifest, FlowParseOptions, FlowRegistry, FlowRegistryEntry, FlowResult, FlowSourceType, FlowState, FlowStatus, FlowStep, StepAction } from "./types.js";
2
2
  import { ClaudePluginAdapter } from "./adapters/claude-plugin.js";
3
3
  import { CopilotAdapter } from "./adapters/copilot.js";
4
4
  import { NativeAdapter } from "./adapters/native.js";
@@ -9,4 +9,4 @@ import { FlowLoader } from "./loader.js";
9
9
  import { FlowRegistryManager } from "./registry.js";
10
10
  import { FlowStateMachine } from "./state-machine.js";
11
11
  import { SymlinkManager } from "./symlinks.js";
12
- export { type BuiltinFlow, ClaudePluginAdapter, CopilotAdapter, type FlowFormat, type FlowFormatAdapter, FlowLoader, type FlowManifest, type FlowRegistry, type FlowRegistryEntry, FlowRegistryManager, type FlowResult, type FlowSourceType, type FlowState, FlowStateMachine, type FlowStatus, type FlowStep, FoundationIntegration, GitInstaller, NativeAdapter, type StepAction, SymlinkManager, getBuiltinFlows };
12
+ export { type BuiltinFlow, ClaudePluginAdapter, CopilotAdapter, type FlowFormat, type FlowFormatAdapter, FlowLoader, type FlowManifest, type FlowParseOptions, type FlowRegistry, type FlowRegistryEntry, FlowRegistryManager, type FlowResult, type FlowSourceType, type FlowState, FlowStateMachine, type FlowStatus, type FlowStep, FoundationIntegration, GitInstaller, NativeAdapter, type StepAction, SymlinkManager, getBuiltinFlows };
@@ -1,12 +1,12 @@
1
- import { FlowFormat, FlowManifest, FlowResult } from "./types.js";
1
+ import { FlowFormat, FlowManifest, FlowParseOptions, FlowResult } from "./types.js";
2
2
 
3
3
  //#region packages/flows/src/loader.d.ts
4
4
  declare class FlowLoader {
5
- load(sourceDir: string): Promise<FlowResult<{
5
+ load(sourceDir: string, options?: FlowParseOptions): Promise<FlowResult<{
6
6
  manifest: FlowManifest;
7
7
  format: FlowFormat;
8
8
  }>>;
9
- loadWithFormat(sourceDir: string, format: FlowFormat): Promise<FlowResult<FlowManifest>>;
9
+ loadWithFormat(sourceDir: string, format: FlowFormat, options?: FlowParseOptions): Promise<FlowResult<FlowManifest>>;
10
10
  validate(manifest: FlowManifest): FlowResult;
11
11
  }
12
12
  //#endregion
@@ -1,2 +1,2 @@
1
- import{getAdapter as e,getAdapterForSource as t}from"./adapters/index.js";import{existsSync as n}from"node:fs";var r=class{async load(e){if(!n(e))return{success:!1,error:`Source directory not found: ${e}`};let r=t(e);if(!r)return{success:!1,error:`No format adapter matches source: ${e}`};try{let t=await r.parse(e),n=this.validate(t);return n.success?{success:!0,data:{manifest:t,format:r.format}}:n}catch(e){return{success:!1,error:`Failed to parse flow: ${e instanceof Error?e.message:String(e)}`}}}async loadWithFormat(t,n){let r=e(n);try{let e=await r.parse(t),n=this.validate(e);return n.success?{success:!0,data:e}:n}catch(e){return{success:!1,error:`Failed to parse flow: ${e instanceof Error?e.message:String(e)}`}}}validate(e){let t=[];e.name?.trim()||t.push(`Missing flow name`),e.version?.trim()||t.push(`Missing flow version`),e.steps?.length||t.push(`Flow must have at least one step`);let n=new Set(e.steps.map(e=>e.id));for(let r of e.steps??[]){r.id?.trim()||t.push(`Step missing id`),r.instruction?.trim()||t.push(`Step "${r.id}" missing instruction path`);for(let e of r.requires??[])n.has(e)||t.push(`Step "${r.id}" requires unknown step "${e}"`)}return n.size!==(e.steps?.length??0)&&t.push(`Duplicate step IDs found`),t.length>0?{success:!1,error:`Validation failed:\n${t.join(`
1
+ import{getAdapter as e,getAdapterForSource as t}from"./adapters/index.js";import{existsSync as n}from"node:fs";var r=class{async load(e,r){if(!n(e))return{success:!1,error:`Source directory not found: ${e}`};let i=t(e);if(!i)return{success:!1,error:`No format adapter matches source: ${e}`};try{let t=await i.parse(e,r),n=this.validate(t);return n.success?{success:!0,data:{manifest:t,format:i.format}}:n}catch(e){return{success:!1,error:`Failed to parse flow: ${e instanceof Error?e.message:String(e)}`}}}async loadWithFormat(t,n,r){let i=e(n);try{let e=await i.parse(t,r),n=this.validate(e);return n.success?{success:!0,data:e}:n}catch(e){return{success:!1,error:`Failed to parse flow: ${e instanceof Error?e.message:String(e)}`}}}validate(e){let t=[];e.name?.trim()||t.push(`Missing flow name`),e.version?.trim()||t.push(`Missing flow version`),e.steps?.length||t.push(`Flow must have at least one step`);let n=new Set(e.steps.map(e=>e.id));for(let r of e.steps??[]){r.id?.trim()||t.push(`Step missing id`),r.instruction?.trim()||t.push(`Step "${r.id}" missing instruction path`);for(let e of r.requires??[])n.has(e)||t.push(`Step "${r.id}" requires unknown step "${e}"`)}return n.size!==(e.steps?.length??0)&&t.push(`Duplicate step IDs found`),t.length>0?{success:!1,error:`Validation failed:\n${t.join(`
2
2
  `)}`}:{success:!0}}};export{r as FlowLoader};
@@ -62,6 +62,8 @@ interface FlowRegistryEntry {
62
62
  updatedAt: string;
63
63
  /** Parsed manifest (cached) */
64
64
  manifest: FlowManifest;
65
+ /** Git commit SHA of the installed version (git sources only) */
66
+ commitSha?: string;
65
67
  }
66
68
  /** The flow registry file structure */
67
69
  interface FlowRegistry {
@@ -93,6 +95,16 @@ interface FlowState {
93
95
  }
94
96
  /** Step action for state machine transitions */
95
97
  type StepAction = 'next' | 'skip' | 'redo';
98
+ /** Options passed to format adapter parse */
99
+ interface FlowParseOptions {
100
+ /** When true, force-refresh supporting assets (e.g. on update) */
101
+ forceAssetSync?: boolean;
102
+ }
103
+ /** Options passed to format adapter parse */
104
+ interface FlowParseOptions {
105
+ /** When true, force-refresh supporting assets (e.g. on update) */
106
+ forceAssetSync?: boolean;
107
+ }
96
108
  /** Format adapter interface — converts external formats to FlowManifest */
97
109
  interface FlowFormatAdapter {
98
110
  /** Format name */
@@ -100,7 +112,7 @@ interface FlowFormatAdapter {
100
112
  /** Check if a directory matches this format */
101
113
  detect(sourceDir: string): boolean;
102
114
  /** Parse the source directory into a FlowManifest */
103
- parse(sourceDir: string): Promise<FlowManifest>;
115
+ parse(sourceDir: string, options?: FlowParseOptions): Promise<FlowManifest>;
104
116
  }
105
117
  /** Result of a flow operation */
106
118
  interface FlowResult<T = void> {
@@ -109,4 +121,4 @@ interface FlowResult<T = void> {
109
121
  error?: string;
110
122
  }
111
123
  //#endregion
112
- export { FlowFormat, FlowFormatAdapter, FlowManifest, FlowRegistry, FlowRegistryEntry, FlowResult, FlowSourceType, FlowState, FlowStatus, FlowStep, StepAction };
124
+ export { FlowFormat, FlowFormatAdapter, FlowManifest, FlowParseOptions, FlowRegistry, FlowRegistryEntry, FlowResult, FlowSourceType, FlowState, FlowStatus, FlowStep, StepAction };
@@ -1 +1 @@
1
- import{getToolMeta as e}from"../tool-metadata.js";import{existsSync as t}from"node:fs";import{basename as n,join as r,resolve as i}from"node:path";import{z as a}from"zod";import{readFile as o}from"node:fs/promises";import{createLogger as s,getGlobalDataDir as c,serializeError as l}from"../../../core/dist/index.js";import{homedir as u}from"node:os";const d=s(`flow-tools`);function f(e){return{content:[{type:`text`,text:e}]}}function p(e){return e instanceof Error?e.message:String(e)}function m(s,m){function h(){return m.sources?.[0]?.path??process.cwd()}function g(){return r(c(),`flows`,`registry.json`)}function _(){return r(m.stateDir??r(h(),`.aikit-state`),`flows`,`state.json`)}function v(e,n){let r=i(u(),`.copilot`,`flows`,e).replaceAll(`\\`,`/`);if(t(r))return r;let a=i(u(),`.claude`,`flows`,e).replaceAll(`\\`,`/`);return t(a)?a:n?.installPath?n.installPath.replaceAll(`\\`,`/`):null}function y(e,t){let n=v(e.name,e);return n?i(n,t).replaceAll(`\\`,`/`):t}async function b(){let{FlowRegistryManager:e,FlowStateMachine:t,FlowLoader:n,GitInstaller:i}=await import(`../../../flows/dist/index.js`),a=r(m.stateDir??r(h(),`.aikit-state`),`flows`,`installed`);return{registry:new e(g()),stateMachine:new t(_()),loader:new n,installer:new i(a)}}let x=e(`flow_list`);s.registerTool(`flow_list`,{title:x.title,description:`List all installed flows and their steps`,annotations:x.annotations,inputSchema:{}},async()=>{try{let{registry:e,stateMachine:t}=await b(),n=e.list(),r=t.getStatus(),i={flows:n.map(e=>({name:e.name,version:e.version,source:e.source,sourceType:e.sourceType,format:e.format,steps:e.manifest.steps.map(e=>e.id)})),activeFlow:r.success&&r.data?{flow:r.data.flow,status:r.data.status,currentStep:r.data.currentStep}:null};return f(JSON.stringify(i,null,2))}catch(e){return d.error(`flow_list failed`,l(e)),f(`Error: ${p(e)}`)}});let S=e(`flow_info`);s.registerTool(`flow_info`,{title:S.title,description:`Show detailed information about a specific flow`,annotations:S.annotations,inputSchema:{name:a.string().describe(`Flow name to get info for`)}},async({name:e})=>{try{let{registry:t}=await b(),n=t.get(e);if(!n)return f(`Flow "${e}" not found. Use flow_list to see available flows.`);let r={name:n.name,version:n.version,description:n.manifest.description,source:n.source,sourceType:n.sourceType,format:n.format,installPath:v(n.name,n),registeredAt:n.registeredAt,updatedAt:n.updatedAt,steps:n.manifest.steps.map(e=>({id:e.id,name:e.name,instruction:y(n,e.instruction),produces:e.produces,requires:e.requires,description:e.description})),agents:n.manifest.agents,artifactsDir:n.manifest.artifacts_dir,install:n.manifest.install};return f(JSON.stringify(r,null,2))}catch(e){return d.error(`flow_info failed`,l(e)),f(`Error: ${p(e)}`)}});let C=e(`flow_start`);s.registerTool(`flow_start`,{title:C.title,description:`Start a flow. Sets the active flow and positions at the first step.`,annotations:C.annotations,inputSchema:{flow:a.string().describe(`Flow name to start (use flow_list to see options)`)}},async({flow:e})=>{try{let{registry:t,stateMachine:n}=await b(),r=t.get(e);if(!r)return f(`Flow "${e}" not found. Use flow_list to see available flows.`);let i=n.start(r.name,r.manifest);if(!i.success||!i.data)return f(`Cannot start: ${i.error}`);let a=i.data,o=r.manifest.steps.find(e=>e.id===a.currentStep),s={started:!0,flow:a.flow,currentStep:a.currentStep,currentStepInstruction:r&&o?y(r,o.instruction):null,currentStepDescription:o?.description??null,totalSteps:r.manifest.steps.length,stepSequence:r.manifest.steps.map(e=>e.id),artifactsDir:r.manifest.artifacts_dir};return f(JSON.stringify(s,null,2))}catch(e){return d.error(`flow_start failed`,l(e)),f(`Error: ${p(e)}`)}});let w=e(`flow_step`);s.registerTool(`flow_step`,{title:w.title,description:`Advance the active flow: complete current step and move to next, skip current step, or redo current step.`,annotations:w.annotations,inputSchema:{action:a.enum([`next`,`skip`,`redo`]).describe(`next: mark current step done and advance. skip: skip current step. redo: repeat current step.`)}},async({action:e})=>{try{let{registry:t,stateMachine:n}=await b(),r=n.load();if(!r)return f(`No active flow. Use flow_start first.`);let i=t.get(r.flow);if(!i)return f(`Flow "${r.flow}" not found in registry.`);let a=n.step(e,i.manifest);if(!a.success||!a.data)return f(`Cannot ${e}: ${a.error}`);let o=a.data,s=o.currentStep?i.manifest.steps.find(e=>e.id===o.currentStep):null,c={flow:o.flow,status:o.status,action:e,currentStep:o.currentStep,currentStepInstruction:i&&s?y(i,s.instruction):null,currentStepDescription:s?.description??null,completedSteps:o.completedSteps,skippedSteps:o.skippedSteps,totalSteps:i.manifest.steps.length,remaining:i.manifest.steps.filter(e=>!o.completedSteps.includes(e.id)&&!o.skippedSteps.includes(e.id)&&e.id!==o.currentStep).map(e=>e.id)};return f(JSON.stringify(c,null,2))}catch(e){return d.error(`flow_step failed`,l(e)),f(`Error: ${p(e)}`)}});let T=e(`flow_status`);s.registerTool(`flow_status`,{title:T.title,description:`Show the current flow execution state — which flow is active, current step, completed steps, and artifacts.`,annotations:T.annotations,inputSchema:{}},async()=>{try{let{registry:e,stateMachine:t}=await b(),n=t.getStatus();if(!n.success||!n.data)return f(`No active flow. Use flow_start to begin one, or flow_list to see available flows.`);let r=n.data,i=e.get(r.flow),a=i?.manifest.steps.find(e=>e.id===r.currentStep),o=i&&a?y(i,a.instruction):null,s={flow:r.flow,status:r.status,currentStep:r.currentStep,currentStepInstruction:o,instructionPath:o,currentStepDescription:a?.description??null,completedSteps:r.completedSteps,skippedSteps:r.skippedSteps,artifacts:r.artifacts,startedAt:r.startedAt,updatedAt:r.updatedAt,totalSteps:i?.manifest.steps.length??0,progress:i?`${r.completedSteps.length+r.skippedSteps.length}/${i.manifest.steps.length}`:`unknown`};return f(JSON.stringify(s,null,2))}catch(e){return d.error(`flow_status failed`,l(e)),f(`Error: ${p(e)}`)}});let E=e(`flow_read_instruction`);s.registerTool(`flow_read_instruction`,{title:E.title===`flow_read_instruction`?`Flow Read Instruction`:E.title,description:`Read the instruction content for a flow step. If step is omitted, reads the current step.`,annotations:E.title===`flow_read_instruction`?{readOnlyHint:!0,idempotentHint:!0}:E.annotations,inputSchema:{step:a.string().optional().describe(`Step id or name to read. Defaults to the current step.`)}},async({step:e})=>{try{let{registry:t,stateMachine:n}=await b(),r=n.getStatus();if(!r.success||!r.data)return f(`No active flow. Use flow_start to begin one, or flow_list to see available flows.`);let i=r.data,a=t.get(i.flow);if(!a)return f(`Flow "${i.flow}" not found in registry.`);let s=e??i.currentStep;if(!s)return f(`No current step is available for the active flow.`);let c=a.manifest.steps.find(e=>e.id===s||e.name===s);return f(c?await o(y(a,c.instruction),`utf-8`):`Step "${s}" not found in flow "${i.flow}".`)}catch(e){return d.error(`flow_read_instruction failed`,l(e)),e instanceof Error&&`code`in e&&e.code===`ENOENT`?f(`Could not read instruction file: ${e.message}`):f(`Error: ${p(e)}`)}});let D=e(`flow_reset`);s.registerTool(`flow_reset`,{title:D.title,description:`Reset the active flow, clearing all state. Use to start over or switch to a different flow.`,annotations:D.annotations,inputSchema:{}},async()=>{try{let{stateMachine:e}=await b(),t=e.reset();return t.success?f(`Flow state reset. Use flow_start to begin a new flow.`):f(`Reset failed: ${t.error}`)}catch(e){return d.error(`flow_reset failed`,l(e)),f(`Error: ${p(e)}`)}});let O=e(`flow_add`);s.registerTool(`flow_add`,{title:O.title,description:`Install a new development flow from a git repository URL or local directory path. Use when the user wants to add, install, import, or onboard a new workflow — for example: "use this as a flow", "add this flow", "add this flow URL", "install a flow", or "onboard a flow". Accepts git URLs (https://..., git@...) and local filesystem paths.`,annotations:O.annotations,inputSchema:{source:a.string().describe(`Git repository URL (https://... or git@...) or absolute/local directory path containing a flow definition.`),name:a.string().optional().describe(`Optional override for the installed flow name. If omitted, the name comes from the flow manifest.`)}},async({source:e,name:t})=>{try{let{registry:r,loader:a,installer:o}=await b(),s=/^https?:\/\/|^git@/.test(e),c;if(s){let t=o.clone(e);if(!t.success||!t.data)return f(`Failed to clone flow: ${t.error}`);c=t.data}else{let r=i(e),a=t||n(r)||`custom-flow`,s=o.copyLocal(r,a);if(!s.success||!s.data)return f(`Failed to copy flow: ${s.error}`);c=s.data}let l=await a.load(c);if(!l.success||!l.data)return o.remove(c),f(`Failed to load flow manifest: ${l.error}`);let{manifest:u,format:d}=l.data,p=t||u.name;if(r.has(p))return o.remove(c),f(`Flow "${p}" is already installed. Use flow_update to update it, or flow_remove then flow_add to replace.`);if(u.install.length>0){let e=o.runInstallDeps(u.install);if(!e.success)return o.remove(c),f(`Dependency install failed: ${e.error}`)}let m=new Date().toISOString(),h=r.register({name:p,version:u.version,source:e,sourceType:s?`git`:`local`,installPath:c,format:d,registeredAt:m,updatedAt:m,manifest:u});if(!h.success)return o.remove(c),f(`Failed to register flow: ${h.error}`);let g=u.steps.length;return f(`Flow "${p}" installed successfully (${g} steps). Use flow_start({ flow: "${p}" }) to begin.`)}catch(e){return d.error(`flow_add failed`,l(e)),f(`Error: ${p(e)}`)}});let k=e(`flow_remove`);s.registerTool(`flow_remove`,{title:k.title,description:`Remove an installed flow by name. Unregisters it and deletes its files when applicable. Builtin flows cannot be removed.`,annotations:k.annotations,inputSchema:{name:a.string().describe(`Name of the flow to remove.`)}},async({name:e})=>{try{let{registry:t,installer:n}=await b();if(!t.has(e))return f(`Flow "${e}" is not installed.`);let r=t.get(e);if(!r)return f(`Flow "${e}" is not installed.`);if(r.sourceType===`builtin`)return f(`Cannot remove builtin flow "${e}".`);let i=n.remove(r.installPath);if(!i.success)return f(`Failed to remove flow files: ${i.error}`);let a=t.unregister(e);return a.success?f(`Flow "${e}" removed successfully.`):f(`Failed to unregister flow: ${a.error}`)}catch(e){return d.error(`flow_remove failed`,l(e)),f(`Error: ${p(e)}`)}});let A=e(`flow_update`);s.registerTool(`flow_update`,{title:A.title,description:`Update an installed git-based flow to its latest version by pulling changes. Only works for flows installed from git repositories.`,annotations:A.annotations,inputSchema:{name:a.string().describe(`Name of the flow to update.`)}},async({name:e})=>{try{let{registry:t,loader:n,installer:r}=await b();if(!t.has(e))return f(`Flow "${e}" is not installed.`);let i=t.get(e);if(!i||i.sourceType!==`git`)return f(`Flow "${e}" was not installed from git — cannot update. Remove and re-add instead.`);let a=r.update(i.installPath);if(!a.success)return f(`Update failed: ${a.error}`);let o=await n.load(i.installPath),s=o.success&&o.data?o.data.manifest:null,c=o.success&&o.data?o.data.format:i.format;if(s){let e=t.register({...i,version:s.version,format:c,manifest:s,updatedAt:new Date().toISOString()});if(!e.success)return f(`Failed to refresh flow registry entry: ${e.error}`)}let l=s?.install??i.manifest.install;if(l.length>0){let e=r.runInstallDeps(l);if(!e.success)return f(`Dependency install failed: ${e.error}`)}return f(`Flow "${e}" updated successfully.`)}catch(e){return d.error(`flow_update failed`,l(e)),f(`Error: ${p(e)}`)}})}export{m as registerFlowTools};
1
+ import{getToolMeta as e}from"../tool-metadata.js";import{existsSync as t}from"node:fs";import{basename as n,join as r,resolve as i}from"node:path";import{z as a}from"zod";import{readFile as o}from"node:fs/promises";import{createLogger as s,getGlobalDataDir as c,serializeError as l}from"../../../core/dist/index.js";import{homedir as u}from"node:os";const d=s(`flow-tools`);function f(e){return{content:[{type:`text`,text:e}]}}function p(e){return e instanceof Error?e.message:String(e)}function m(s,m){function h(){return m.sources?.[0]?.path??process.cwd()}function g(){return r(c(),`flows`,`registry.json`)}function _(){return r(m.stateDir??r(h(),`.aikit-state`),`flows`,`state.json`)}function v(e,n){let r=i(u(),`.copilot`,`flows`,e).replaceAll(`\\`,`/`);if(t(r))return r;let a=i(u(),`.claude`,`flows`,e).replaceAll(`\\`,`/`);return t(a)?a:n?.installPath?n.installPath.replaceAll(`\\`,`/`):null}function y(e,t){let n=v(e.name,e);return n?i(n,t).replaceAll(`\\`,`/`):t}async function b(){let{FlowRegistryManager:e,FlowStateMachine:t,FlowLoader:n,GitInstaller:i}=await import(`../../../flows/dist/index.js`),a=r(m.stateDir??r(h(),`.aikit-state`),`flows`,`installed`);return{registry:new e(g()),stateMachine:new t(_()),loader:new n,installer:new i(a)}}let x=e(`flow_list`);s.registerTool(`flow_list`,{title:x.title,description:`List all installed flows and their steps`,annotations:x.annotations,inputSchema:{}},async()=>{try{let{registry:e,stateMachine:t,installer:n}=await b(),r=e.list(),i=t.getStatus(),a={flows:r.map(e=>{let t={name:e.name,version:e.version,source:e.source,sourceType:e.sourceType,format:e.format,steps:e.manifest.steps.map(e=>e.id)};if(e.sourceType===`git`&&e.commitSha){let r=n.hasUpdates(e.installPath);return{...t,commitSha:e.commitSha,updateAvailable:r.success&&r.data?r.data.hasUpdates:void 0}}return t}),activeFlow:i.success&&i.data?{flow:i.data.flow,status:i.data.status,currentStep:i.data.currentStep}:null};return f(JSON.stringify(a,null,2))}catch(e){return d.error(`flow_list failed`,l(e)),f(`Error: ${p(e)}`)}});let S=e(`flow_info`);s.registerTool(`flow_info`,{title:S.title,description:`Show detailed information about a specific flow`,annotations:S.annotations,inputSchema:{name:a.string().describe(`Flow name to get info for`)}},async({name:e})=>{try{let{registry:t,installer:n}=await b(),r=t.get(e);if(!r)return f(`Flow "${e}" not found. Use flow_list to see available flows.`);let i=r.commitSha??null,a;if(r.sourceType===`git`&&r.installPath){let e=n.hasUpdates(r.installPath);a=e.success&&e.data?e.data.hasUpdates:void 0}let o={name:r.name,version:r.version,description:r.manifest.description,source:r.source,sourceType:r.sourceType,format:r.format,commitSha:i,updateAvailable:a,installPath:v(r.name,r),registeredAt:r.registeredAt,updatedAt:r.updatedAt,steps:r.manifest.steps.map(e=>({id:e.id,name:e.name,instruction:y(r,e.instruction),produces:e.produces,requires:e.requires,description:e.description})),agents:r.manifest.agents,artifactsDir:r.manifest.artifacts_dir,install:r.manifest.install};return f(JSON.stringify(o,null,2))}catch(e){return d.error(`flow_info failed`,l(e)),f(`Error: ${p(e)}`)}});let C=e(`flow_start`);s.registerTool(`flow_start`,{title:C.title,description:`Start a flow. Sets the active flow and positions at the first step.`,annotations:C.annotations,inputSchema:{flow:a.string().describe(`Flow name to start (use flow_list to see options)`)}},async({flow:e})=>{try{let{registry:t,stateMachine:n}=await b(),r=t.get(e);if(!r)return f(`Flow "${e}" not found. Use flow_list to see available flows.`);let i=n.start(r.name,r.manifest);if(!i.success||!i.data)return f(`Cannot start: ${i.error}`);let a=i.data,o=r.manifest.steps.find(e=>e.id===a.currentStep),s={started:!0,flow:a.flow,currentStep:a.currentStep,currentStepInstruction:r&&o?y(r,o.instruction):null,currentStepDescription:o?.description??null,totalSteps:r.manifest.steps.length,stepSequence:r.manifest.steps.map(e=>e.id),artifactsDir:r.manifest.artifacts_dir};return f(JSON.stringify(s,null,2))}catch(e){return d.error(`flow_start failed`,l(e)),f(`Error: ${p(e)}`)}});let w=e(`flow_step`);s.registerTool(`flow_step`,{title:w.title,description:`Advance the active flow: complete current step and move to next, skip current step, or redo current step.`,annotations:w.annotations,inputSchema:{action:a.enum([`next`,`skip`,`redo`]).describe(`next: mark current step done and advance. skip: skip current step. redo: repeat current step.`)}},async({action:e})=>{try{let{registry:t,stateMachine:n}=await b(),r=n.load();if(!r)return f(`No active flow. Use flow_start first.`);let i=t.get(r.flow);if(!i)return f(`Flow "${r.flow}" not found in registry.`);let a=n.step(e,i.manifest);if(!a.success||!a.data)return f(`Cannot ${e}: ${a.error}`);let o=a.data,s=o.currentStep?i.manifest.steps.find(e=>e.id===o.currentStep):null,c={flow:o.flow,status:o.status,action:e,currentStep:o.currentStep,currentStepInstruction:i&&s?y(i,s.instruction):null,currentStepDescription:s?.description??null,completedSteps:o.completedSteps,skippedSteps:o.skippedSteps,totalSteps:i.manifest.steps.length,remaining:i.manifest.steps.filter(e=>!o.completedSteps.includes(e.id)&&!o.skippedSteps.includes(e.id)&&e.id!==o.currentStep).map(e=>e.id)};return f(JSON.stringify(c,null,2))}catch(e){return d.error(`flow_step failed`,l(e)),f(`Error: ${p(e)}`)}});let T=e(`flow_status`);s.registerTool(`flow_status`,{title:T.title,description:`Show the current flow execution state — which flow is active, current step, completed steps, and artifacts.`,annotations:T.annotations,inputSchema:{}},async()=>{try{let{registry:e,stateMachine:t}=await b(),n=t.getStatus();if(!n.success||!n.data)return f(`No active flow. Use flow_start to begin one, or flow_list to see available flows.`);let r=n.data,i=e.get(r.flow),a=i?.manifest.steps.find(e=>e.id===r.currentStep),o=i&&a?y(i,a.instruction):null,s={flow:r.flow,status:r.status,currentStep:r.currentStep,currentStepInstruction:o,instructionPath:o,currentStepDescription:a?.description??null,completedSteps:r.completedSteps,skippedSteps:r.skippedSteps,artifacts:r.artifacts,startedAt:r.startedAt,updatedAt:r.updatedAt,totalSteps:i?.manifest.steps.length??0,progress:i?`${r.completedSteps.length+r.skippedSteps.length}/${i.manifest.steps.length}`:`unknown`};return f(JSON.stringify(s,null,2))}catch(e){return d.error(`flow_status failed`,l(e)),f(`Error: ${p(e)}`)}});let E=e(`flow_read_instruction`);s.registerTool(`flow_read_instruction`,{title:E.title===`flow_read_instruction`?`Flow Read Instruction`:E.title,description:`Read the instruction content for a flow step. If step is omitted, reads the current step.`,annotations:E.title===`flow_read_instruction`?{readOnlyHint:!0,idempotentHint:!0}:E.annotations,inputSchema:{step:a.string().optional().describe(`Step id or name to read. Defaults to the current step.`)}},async({step:e})=>{try{let{registry:t,stateMachine:n}=await b(),r=n.getStatus();if(!r.success||!r.data)return f(`No active flow. Use flow_start to begin one, or flow_list to see available flows.`);let i=r.data,a=t.get(i.flow);if(!a)return f(`Flow "${i.flow}" not found in registry.`);let s=e??i.currentStep;if(!s)return f(`No current step is available for the active flow.`);let c=a.manifest.steps.find(e=>e.id===s||e.name===s);return f(c?await o(y(a,c.instruction),`utf-8`):`Step "${s}" not found in flow "${i.flow}".`)}catch(e){return d.error(`flow_read_instruction failed`,l(e)),e instanceof Error&&`code`in e&&e.code===`ENOENT`?f(`Could not read instruction file: ${e.message}`):f(`Error: ${p(e)}`)}});let D=e(`flow_reset`);s.registerTool(`flow_reset`,{title:D.title,description:`Reset the active flow, clearing all state. Use to start over or switch to a different flow.`,annotations:D.annotations,inputSchema:{}},async()=>{try{let{stateMachine:e}=await b(),t=e.reset();return t.success?f(`Flow state reset. Use flow_start to begin a new flow.`):f(`Reset failed: ${t.error}`)}catch(e){return d.error(`flow_reset failed`,l(e)),f(`Error: ${p(e)}`)}});let O=e(`flow_add`);s.registerTool(`flow_add`,{title:O.title,description:`Install a new development flow from a git repository URL or local directory path. Use when the user wants to add, install, import, or onboard a new workflow — for example: "use this as a flow", "add this flow", "add this flow URL", "install a flow", or "onboard a flow". Accepts git URLs (https://..., git@...) and local filesystem paths.`,annotations:O.annotations,inputSchema:{source:a.string().describe(`Git repository URL (https://... or git@...) or absolute/local directory path containing a flow definition.`),name:a.string().optional().describe(`Optional override for the installed flow name. If omitted, the name comes from the flow manifest.`)}},async({source:e,name:t})=>{try{let{registry:r,loader:a,installer:o}=await b(),s=/^https?:\/\/|^git@/.test(e),c;if(s){let t=o.clone(e);if(!t.success||!t.data)return f(`Failed to clone flow: ${t.error}`);c=t.data}else{let r=i(e),a=t||n(r)||`custom-flow`,s=o.copyLocal(r,a);if(!s.success||!s.data)return f(`Failed to copy flow: ${s.error}`);c=s.data}let l=await a.load(c);if(!l.success||!l.data)return o.remove(c),f(`Failed to load flow manifest: ${l.error}`);let{manifest:u,format:d}=l.data,p=t||u.name;if(r.has(p))return o.remove(c),f(`Flow "${p}" is already installed. Use flow_update to update it, or flow_remove then flow_add to replace.`);if(u.install.length>0){let e=o.runInstallDeps(u.install);if(!e.success)return o.remove(c),f(`Dependency install failed: ${e.error}`)}let m=new Date().toISOString(),h=s?o.getLocalCommit(c):void 0,g=r.register({name:p,version:u.version,source:e,sourceType:s?`git`:`local`,installPath:c,format:d,registeredAt:m,updatedAt:m,manifest:u,...h?{commitSha:h}:{}});if(!g.success)return o.remove(c),f(`Failed to register flow: ${g.error}`);let _=u.steps.length;return f(`Flow "${p}" installed successfully (${_} steps). Use flow_start({ flow: "${p}" }) to begin.`)}catch(e){return d.error(`flow_add failed`,l(e)),f(`Error: ${p(e)}`)}});let k=e(`flow_remove`);s.registerTool(`flow_remove`,{title:k.title,description:`Remove an installed flow by name. Unregisters it and deletes its files when applicable. Builtin flows cannot be removed.`,annotations:k.annotations,inputSchema:{name:a.string().describe(`Name of the flow to remove.`)}},async({name:e})=>{try{let{registry:t,installer:n}=await b();if(!t.has(e))return f(`Flow "${e}" is not installed.`);let r=t.get(e);if(!r)return f(`Flow "${e}" is not installed.`);if(r.sourceType===`builtin`)return f(`Cannot remove builtin flow "${e}".`);let i=n.remove(r.installPath);if(!i.success)return f(`Failed to remove flow files: ${i.error}`);let a=t.unregister(e);return a.success?f(`Flow "${e}" removed successfully.`):f(`Failed to unregister flow: ${a.error}`)}catch(e){return d.error(`flow_remove failed`,l(e)),f(`Error: ${p(e)}`)}});let A=e(`flow_update`);s.registerTool(`flow_update`,{title:A.title,description:`Update an installed git-based flow to its latest version by pulling changes. Only works for flows installed from git repositories.`,annotations:A.annotations,inputSchema:{name:a.string().describe(`Name of the flow to update.`)}},async({name:e})=>{try{let{registry:t,loader:n,installer:r}=await b();if(!t.has(e))return f(`Flow "${e}" is not installed.`);let i=t.get(e);if(!i||i.sourceType!==`git`)return f(`Flow "${e}" was not installed from git — cannot update. Remove and re-add instead.`);let a=r.update(i.installPath);if(!a.success)return f(`Update failed: ${a.error}`);let o=await n.load(i.installPath,{forceAssetSync:!0}),s=o.success&&o.data?o.data.manifest:null,c=o.success&&o.data?o.data.format:i.format;if(s){let e=r.getLocalCommit(i.installPath),n=t.register({...i,version:s.version,format:c,manifest:s,updatedAt:new Date().toISOString(),...e?{commitSha:e}:{}});if(!n.success)return f(`Failed to refresh flow registry entry: ${n.error}`)}let l=s?.install??i.manifest.install;if(l.length>0){let e=r.runInstallDeps(l);if(!e.success)return f(`Dependency install failed: ${e.error}`)}return f(`Flow "${e}" updated successfully.`)}catch(e){return d.error(`flow_update failed`,l(e)),f(`Error: ${p(e)}`)}})}export{m as registerFlowTools};