@culvii/cli 0.0.5 → 0.0.6
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/COMMANDS.md +4 -4
- package/README.md +15 -6
- package/USAGE.md +7 -7
- package/dist/DeployView-I4Y55LV4.js +2 -0
- package/dist/DevView-GPKSSOLA.js +2 -0
- package/dist/EnvView-3ZURMIZS.js +2 -0
- package/dist/{HelpView-IV4PD2JG.js → HelpView-ZMOAJNYC.js} +1 -1
- package/dist/WhoamiView-VHDXFFLX.js +2 -0
- package/dist/chunk-LD5ISISS.js +3 -0
- package/dist/index.js +34 -35
- package/dist/lib/evaluator.js +2 -2
- package/dist/{login-DFT7D637.js → login-4VBBCK4V.js} +1 -1
- package/dist/{logout-OZBKJPQM.js → logout-VOWHM2QB.js} +1 -1
- package/package.json +1 -1
- package/dist/DeployView-GEJNL26A.js +0 -2
- package/dist/DevView-SOPAMSZ4.js +0 -2
- package/dist/EnvView-MCZC2NBO.js +0 -2
- package/dist/WhoamiView-67HV2L5J.js +0 -2
- package/dist/chunk-MPKGJC7N.js +0 -2
- package/dist/chunk-WB3426JN.js +0 -3
package/COMMANDS.md
CHANGED
|
@@ -12,7 +12,7 @@ All commands can be run as `culvii <command>` or `node dist/index.js <command>`.
|
|
|
12
12
|
| `culvii logout` | Clear stored tokens. |
|
|
13
13
|
| `culvii auth login` | Alias for `culvii login` |
|
|
14
14
|
| `culvii auth logout` | Alias for `culvii logout` |
|
|
15
|
-
| `culvii whoami [--json]
|
|
15
|
+
| `culvii whoami [--json]` | Show current user, active tenant, workspace, and scoped access. `--json` outputs machine-readable JSON. |
|
|
16
16
|
|
|
17
17
|
---
|
|
18
18
|
|
|
@@ -65,7 +65,7 @@ Note: `culvii dev` accepts no flags. The `--workspace` flag shown in older docs
|
|
|
65
65
|
|
|
66
66
|
| Command | Flags | Description |
|
|
67
67
|
|---------|-------|-------------|
|
|
68
|
-
| `culvii deploy` | `--env <sandbox\|prod> --workspace-slug <slug
|
|
68
|
+
| `culvii deploy` | `--env <sandbox\|prod> --workspace-slug <slug>` | Deploy agents and workflows to sandbox or prod. Displays created, versioned, and deleted resources, then requires one confirmation. |
|
|
69
69
|
|
|
70
70
|
---
|
|
71
71
|
|
|
@@ -86,7 +86,7 @@ Note: `culvii dev` accepts no flags. The `--workspace` flag shown in older docs
|
|
|
86
86
|
|
|
87
87
|
| Command | Flags | Description |
|
|
88
88
|
|---------|-------|-------------|
|
|
89
|
-
| `culvii rename <old-slug> <new-slug>` | `--resource-type
|
|
89
|
+
| `culvii rename <old-slug> <new-slug>` | `--resource-type agent [--workspace-slug <slug>] [--env]` | Rename an agent while preserving its UUID and execution history. |
|
|
90
90
|
|
|
91
91
|
---
|
|
92
92
|
|
|
@@ -116,4 +116,4 @@ Commands including `deploy`, `rename`, `workspace`, `key`, `dev`, and `init` ren
|
|
|
116
116
|
| `culvii audit query/verify` | Audit trail viewer (UI shell only, not yet wired to API). (currently disabled, pending public release) |
|
|
117
117
|
| `culvii policy validate/check` | Policy commands (UI shell only, not yet wired to API). (currently disabled, pending public release) |
|
|
118
118
|
| `culvii approve list/<id>` | Approval commands (UI shell only, not yet wired to API). (currently disabled, pending public release) |
|
|
119
|
-
| `culvii errors` | Error viewer (UI shell only, not yet wired to API). (currently disabled, pending public release) |
|
|
119
|
+
| `culvii errors` | Error viewer (UI shell only, not yet wired to API). (currently disabled, pending public release) |
|
package/README.md
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
The Culvii CLI is the local development and deployment tool for the Culvii agent platform. It manages authentication, local file watching, WebSocket-based dev synchronization, and Terraform-style declarative deployments.
|
|
4
4
|
|
|
5
5
|
## Prerequisites
|
|
6
|
+
|
|
6
7
|
- Node.js (v22+)
|
|
7
8
|
- pnpm (part of the monorepo)
|
|
8
9
|
|
|
@@ -23,39 +24,46 @@ Once built, you can run the CLI locally using `node dist/index.js` or via the mo
|
|
|
23
24
|
## Getting Started
|
|
24
25
|
|
|
25
26
|
### 1. Authenticate
|
|
27
|
+
|
|
26
28
|
Before running any commands, authenticate your machine.
|
|
27
29
|
|
|
28
30
|
```bash
|
|
29
31
|
culvii auth login
|
|
30
32
|
```
|
|
31
|
-
|
|
33
|
+
|
|
34
|
+
This opens your browser to log in via OAuth. Upon success, your credentials, tenants, and active context are stored locally in `~/.culvii/`.
|
|
32
35
|
|
|
33
36
|
### 2. Local Development
|
|
37
|
+
|
|
34
38
|
The `dev` command starts a local watcher that hot-syncs your local agent and workflow definitions to a development workspace over WebSockets.
|
|
35
39
|
|
|
36
40
|
```bash
|
|
37
41
|
culvii dev
|
|
38
42
|
```
|
|
43
|
+
|
|
39
44
|
- **Auto-provisioning:** The CLI automatically creates a developer workspace (`dev-<user-id>`) and a developer API key for you.
|
|
40
45
|
- **Watching:** It watches for changes in `**/*.ts` files (ignoring `node_modules`, `dist`).
|
|
41
46
|
- **Syncing:** Whenever a change is detected, it evaluates your agent definitions and streams the updates to the cloud in real-time.
|
|
42
47
|
|
|
43
48
|
### 3. Deployment
|
|
49
|
+
|
|
44
50
|
Deploys your agents and workflows to a specific environment using a declarative plan/apply flow.
|
|
45
51
|
|
|
46
52
|
```bash
|
|
47
53
|
culvii deploy --env sandbox --workspace-slug <workspace-slug>
|
|
48
54
|
```
|
|
55
|
+
|
|
49
56
|
- **Targeting:** Requires both `--env` (`sandbox` or `prod`) and `--workspace-slug <slug>`.
|
|
50
57
|
- **Validation:** Checks for missing definitions or dangling agent references.
|
|
51
58
|
- **Plan/Apply:** Displays a diff plan (Created, Updated, Destroyed). Requires manual `[y/N]` confirmation.
|
|
52
|
-
- **
|
|
59
|
+
- **Reconciliation:** Resources missing from the submitted definitions are listed in the plan and deleted after the overall confirmation.
|
|
53
60
|
|
|
54
61
|
---
|
|
55
62
|
|
|
56
63
|
## File Discovery
|
|
57
64
|
|
|
58
65
|
To determine what to evaluate and sync, the CLI looks in your current working directory:
|
|
66
|
+
|
|
59
67
|
1. **`culvii.yaml`**: If present, it reads the `entrypoints` array.
|
|
60
68
|
2. **Fallback Globbing**: If no configuration file exists, it recursively finds all `*.culvii.ts` files in your project.
|
|
61
69
|
|
|
@@ -74,18 +82,19 @@ To determine what to evaluate and sync, the CLI looks in your current working di
|
|
|
74
82
|
| `culvii key` | Manage API keys. |
|
|
75
83
|
| `culvii switch` | Switch active tenant/context. |
|
|
76
84
|
| `culvii whoami` | View your current authenticated identity and active context. Supports --json and --env. |
|
|
77
|
-
| `culvii rename` |
|
|
85
|
+
| `culvii rename` | Rename a deployed agent. `--resource-type agent` is required. |
|
|
78
86
|
| `culvii skill install` | Install the Culvii SDK skill for your AI coding agent. No auth required. |
|
|
79
87
|
|
|
80
|
-
|
|
88
|
+
_Coming soon: audit, policy, approve, logs_
|
|
81
89
|
|
|
82
|
-
|
|
90
|
+
_(Run `culvii --help` for the full list of available commands and flags)_
|
|
83
91
|
|
|
84
92
|
---
|
|
85
93
|
|
|
86
94
|
## Local State & Configuration
|
|
87
95
|
|
|
88
96
|
The CLI manages state securely in your home directory (`~/.culvii/`):
|
|
97
|
+
|
|
89
98
|
- **`config`**: Active contexts, workspace mappings, environment targets, and auto-generated API keys.
|
|
90
99
|
- **`tokens.json`**: Active OAuth access and refresh tokens.
|
|
91
100
|
- **`.lock`**: Lockfile ensuring atomic concurrent reads/writes when multiple CLI instances run.
|
|
@@ -102,4 +111,4 @@ export CULVII_TELEMETRY=false
|
|
|
102
111
|
|
|
103
112
|
## Interactive UI
|
|
104
113
|
|
|
105
|
-
Most commands render a rich terminal UI when running in a supported TTY. They automatically fall back to plain text output in CI/CD environments, pipes, or terminals without color/unicode support. Set `CI=1` to force non-interactive mode.
|
|
114
|
+
Most commands render a rich terminal UI when running in a supported TTY. They automatically fall back to plain text output in CI/CD environments, pipes, or terminals without color/unicode support. Set `CI=1` to force non-interactive mode.
|
package/USAGE.md
CHANGED
|
@@ -45,9 +45,9 @@ culvii auth logout # alias
|
|
|
45
45
|
|
|
46
46
|
### Who am I
|
|
47
47
|
```bash
|
|
48
|
-
culvii whoami [--json]
|
|
48
|
+
culvii whoami [--json]
|
|
49
49
|
```
|
|
50
|
-
Displays current user, active tenant,
|
|
50
|
+
Displays current user, active tenant, workspace, and scoped access. `--json` outputs machine-readable JSON.
|
|
51
51
|
|
|
52
52
|
---
|
|
53
53
|
|
|
@@ -112,7 +112,7 @@ entrypoints:
|
|
|
112
112
|
## Deploy
|
|
113
113
|
|
|
114
114
|
```bash
|
|
115
|
-
culvii deploy --env <env> --workspace-slug <slug>
|
|
115
|
+
culvii deploy --env <env> --workspace-slug <slug>
|
|
116
116
|
```
|
|
117
117
|
|
|
118
118
|
`--env` is required and must be `sandbox` or `prod` (not `dev` — use `culvii dev` for local iteration).
|
|
@@ -122,8 +122,8 @@ culvii deploy --env <env> --workspace-slug <slug> [--allow-destroy]
|
|
|
122
122
|
1. Evaluates all `*.culvii.ts` files in the current directory
|
|
123
123
|
2. Calls the plan API to compute a diff against what's currently deployed
|
|
124
124
|
3. Displays the plan (CREATED / UPDATED / DESTROYED)
|
|
125
|
-
4.
|
|
126
|
-
5. Applies the plan
|
|
125
|
+
4. Shows every missing resource that will be deleted
|
|
126
|
+
5. Applies the plan after one overall confirmation
|
|
127
127
|
|
|
128
128
|
**Example:**
|
|
129
129
|
```bash
|
|
@@ -151,10 +151,10 @@ culvii key revoke <fingerprint> [--env <env>]
|
|
|
151
151
|
## Rename
|
|
152
152
|
|
|
153
153
|
```bash
|
|
154
|
-
culvii rename <old-slug> <new-slug> --resource-type
|
|
154
|
+
culvii rename <old-slug> <new-slug> --resource-type agent [--workspace-slug <slug>] [--env <env>]
|
|
155
155
|
```
|
|
156
156
|
|
|
157
|
-
Renames
|
|
157
|
+
Renames an agent while preserving its UUID and execution history. Workflow IDs are reconciled by deploy/dev instead of renamed.
|
|
158
158
|
|
|
159
159
|
---
|
|
160
160
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {a as a$4}from'./chunk-5NBKYMD7.js';import {a}from'./chunk-R67TA4FU.js';import {a as a$3}from'./chunk-FQVHJUX4.js';import {a as a$1}from'./chunk-JYNOILCD.js';import'./chunk-57XLDHK6.js';import {o,l,c,a as a$2,e,w}from'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import {useEffect}from'react';import {useApp,useInput,Box,Text}from'ink';import {jsxs,jsx}from'react/jsx-runtime';function I(e){let c=e.versionCount??1,p=e.activeVersion??e.previousVersion;return `Deletes all ${c} ${c===1?"version":"versions"}${p?`; active is v${p}`:""}.`}function D(e){if(e.type==="surface"){let d=e.activeVersion??e.previousVersion;return d?`active v${d}`:"active"}let c=e.executions??0,p=e.activeExecutions??0,o=e.activeVersion??e.previousVersion;return `${c} total, active${o?` v${o}`:""}: ${p} executions`}function A({state:e$1,onConfirm:c$1}){let{exit:p}=useApp();return useEffect(()=>{if(e$1.type==="success"||e$1.type==="no_changes"||e$1.type==="aborted"||e$1.type==="error"){let o=setTimeout(()=>p(),100);return ()=>clearTimeout(o)}},[e$1.type,p]),useInput((o,d)=>{e$1.type==="confirming"&&(o.toLowerCase()==="y"?c$1?.(true):(o.toLowerCase()==="n"||d.escape)&&c$1?.(false));}),jsxs(Box,{flexDirection:"column",children:[jsx(a,{command:"culvii",subcommand:"deploy"}),e$1.type==="planning"&&jsx(Box,{paddingLeft:2,children:jsx(a$1,{label:"Planning deploy\u2026"})}),e$1.type==="confirming"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,gap:1,children:[jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{color:o,children:["Plan for ",jsx(Text,{color:l,bold:true,children:e$1.env}),":"]}),jsxs(Box,{flexDirection:"column",marginTop:1,children:[e$1.plan.created.map(o$1=>jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:c,children:"+"}),jsx(Text,{color:l,children:o$1.slug}),jsx(Text,{color:o,children:"CREATED"})]},o$1.slug)),e$1.plan.versioned.map(o$1=>jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:a$2,children:"~"}),jsx(Text,{color:l,children:o$1.slug}),jsxs(Text,{color:o,children:["VERSIONED (",D(o$1),")"]})]},o$1.slug)),e$1.plan.destroyed.map(o$1=>jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:e,children:"-"}),jsx(Text,{color:l,children:o$1.slug}),jsxs(Text,{color:o,children:["DELETE (",D(o$1),")"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{color:e,children:I(o$1)})})]},o$1.slug))]})]}),jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:o,children:"Deploy to "}),jsx(Text,{color:l,bold:true,children:e$1.env}),jsx(Text,{color:o,children:"?"}),jsx(Text,{color:a$2,bold:true,children:"[y/N]"})]})]}),e$1.type==="applying"&&jsx(Box,{paddingLeft:2,children:jsx(a$1,{label:"Applying\u2026"})}),e$1.type==="no_changes"&&jsx(Box,{paddingLeft:2,children:jsx(a$3.Dim,{children:"Nothing to deploy. All resources are up to date."})}),e$1.type==="aborted"&&e$1.reason==="user_cancelled"&&jsx(Box,{paddingLeft:2,children:jsx(a$3.Dim,{children:"Deployment cancelled."})}),e$1.type==="error"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,children:[jsx(a$3.Err,{children:e$1.message}),e$1.detail&&jsx(a$3.Dim,{children:e$1.detail})]}),e$1.type==="success"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,gap:1,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:c,children:w}),jsxs(Text,{color:l,bold:true,children:["Deployed to ",e$1.env]})]}),jsx(a$4,{variant:"ok",content:[{k:"created",v:jsxs(Text,{color:l,children:[e$1.created," resource(s)"]})},{k:"versioned",v:jsxs(Text,{color:l,children:[e$1.versioned," resource(s)"]})},{k:"destroyed",v:jsxs(Text,{color:l,children:[e$1.destroyed," resource(s)"]})}]}),jsxs(Box,{flexDirection:"column",children:[(e$1.createdItems||[]).map(o=>jsxs(Text,{color:c,children:["+ ",o.slug]},`created-${o.slug}`)),(e$1.versionedItems||[]).map(o=>jsxs(Text,{color:a$2,children:["~ ",o.slug]},`versioned-${o.slug}`)),(e$1.destroyedItems||[]).map(o=>jsxs(Text,{color:e,children:["- ",o.slug]},`destroyed-${o.slug}`))]})]})]})}export{A as DeployView};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {a}from'./chunk-R67TA4FU.js';import {a as a$2}from'./chunk-FQVHJUX4.js';import {a as a$1}from'./chunk-JYNOILCD.js';import'./chunk-57XLDHK6.js';import {o,a as a$3,w,c,y,d}from'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import {useEffect}from'react';import {useApp,Box,Text}from'ink';import {jsxs,jsx}from'react/jsx-runtime';function h({state:r}){let{exit:d$1}=useApp();return useEffect(()=>{if(r.type==="error"||r.type==="disconnected"){let o=setTimeout(()=>d$1(),100);return ()=>clearTimeout(o)}},[r.type,d$1]),jsxs(Box,{flexDirection:"column",children:[jsx(a,{command:"culvii",subcommand:"dev"}),r.type==="provisioning"&&jsx(Box,{paddingLeft:2,children:jsx(a$1,{label:r.message})}),r.type==="error"&&jsx(Box,{flexDirection:"column",paddingLeft:2,children:jsx(a$2.Err,{children:r.message})}),r.type==="disconnected"&&jsx(Box,{paddingLeft:2,children:jsx(a$2.Dim,{children:"Disconnected. Draft state discarded."})}),r.type==="connected"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,gap:1,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:o,children:"You can access your dev session here:"}),jsx(Text,{color:a$3,children:r.consoleUrl})]}),jsx(a$2.Dim,{children:"Watching ./..."}),jsx(Box,{flexDirection:"column",gap:0,children:r.log.map((o$1,D)=>jsxs(Box,{flexDirection:"row",gap:1,children:[o$1.type==="synced"&&jsx(Text,{color:c,children:w}),o$1.type==="orphaned"&&jsx(Text,{color:c,children:w}),(o$1.type==="warning"||o$1.type==="error")&&jsx(Text,{color:d,children:y}),o$1.type==="info"&&jsx(Text,{color:o,children:"\xB7"}),o$1.timestamp&&jsxs(Text,{color:o,children:["[",o$1.timestamp,"]"]}),jsx(Text,{color:o$1.type==="warning"||o$1.type==="error"?d:o,children:o$1.message})]},D))})]})]})}export{h as DevView};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {a}from'./chunk-R67TA4FU.js';import {a as a$1}from'./chunk-FQVHJUX4.js';import {l,e,o,w,c,x,p,j,f,k,a as a$2,h as h$1,d,i,g}from'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import {useEffect}from'react';import {useApp,Box,Text}from'ink';import {jsxs,jsx}from'react/jsx-runtime';var h={allow:{color:c,backgroundColor:g},healthy:{color:c,backgroundColor:g},deny:{color:e,backgroundColor:i},blocked:{color:e,backgroundColor:i},warn:{color:d,backgroundColor:h$1},throttled:{color:d,backgroundColor:h$1},accent:{color:a$2,backgroundColor:k},info:{color:f,backgroundColor:j},draft:{color:o,backgroundColor:p}};function R({variant:o,children:i}){let g=h[o];return jsx(Box,{flexDirection:"row",children:jsx(Box,{paddingX:1,backgroundColor:g.backgroundColor,children:jsx(Text,{color:g.color,bold:true,children:i})})})}function A(o){return o==="prod"?"allow":o==="sandbox"?"warn":"info"}function T({env:o}){return jsx(R,{variant:A(o),children:o})}function L({envs:o$1}){return o$1.length===0?jsx(Text,{color:o,children:"none"}):jsx(Box,{flexDirection:"row",gap:1,children:o$1.map(i=>jsx(T,{env:i},i))})}function q({state:o$1}){let{exit:i}=useApp();return useEffect(()=>{let g=setTimeout(()=>i(),100);return ()=>clearTimeout(g)},[i]),jsxs(Box,{flexDirection:"column",children:[jsx(a,{command:"culvii",subcommand:"env"}),o$1.type==="show"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,gap:1,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:l,children:"current"}),jsx(T,{env:o$1.current}),!o$1.accessible.includes(o$1.current)&&jsx(Text,{color:e,children:"(no access)"})]}),jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:o,children:"tenant:"}),jsx(Text,{color:l,children:o$1.tenant})]}),jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:o,children:"available:"}),jsx(L,{envs:o$1.accessible})]}),!o$1.accessible.includes(o$1.current)&&o$1.accessible.length>0&&jsxs(a$1.Dim,{children:["To switch, run: culvii env ",o$1.accessible[0]]})]}),o$1.type==="success"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,gap:1,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:c,children:w}),jsx(Text,{color:l,bold:true,children:"Switched environment to"}),jsx(T,{env:o$1.env})]}),jsxs(a$1.Dim,{children:["tenant: ",o$1.tenant]})]}),o$1.type==="error"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:e,children:x}),jsx(Text,{color:l,children:o$1.message})]}),o$1.detail&&jsx(Box,{paddingLeft:2,children:jsx(a$1.Dim,{children:o$1.detail})})]})]})}export{q as EnvView};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {p as p$1}from'./chunk-
|
|
2
|
+
import {p as p$1}from'./chunk-LD5ISISS.js';import'./chunk-HX54IFSD.js';import {a}from'./chunk-FQVHJUX4.js';import {q,r as r$1}from'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import {useEffect}from'react';import {useApp,Box,Text}from'ink';import {jsxs,jsx}from'react/jsx-runtime';function p({children:i}){return jsx(Text,{color:q,children:i})}function s({children:i}){return jsx(Text,{color:r$1,children:i})}var r={Flag:p,Arg:s};function P(){let{exit:i}=useApp();return useEffect(()=>{i();},[i]),jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(a.OutStrong,{children:"culvii"}),jsx(a.Dim,{children:"\u2014 the operating system for governed agents"})]}),jsxs(a.Dim,{children:["0.0.6"," \xB7 https://culvii.dev"]}),jsx(a.Sep,{}),jsxs(Box,{paddingBottom:1,children:[jsx(a.OutStrong,{children:"USAGE"}),jsxs(a.Out,{children:[" culvii ","<command>"," [subcommand] [flags]"]})]}),jsxs(Box,{paddingBottom:1,flexDirection:"column",children:[jsx(a.OutStrong,{children:"CORE COMMANDS"}),jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:15,children:jsx(Text,{children:jsx(r.Flag,{children:" auth"})})}),jsx(a.Out,{children:"login, rotate keys, inspect identity"})]}),jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:15,children:jsx(Text,{children:jsx(r.Flag,{children:" init"})})}),jsx(a.Out,{children:"scaffold a new agent from a template"})]}),jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:15,children:jsx(Text,{children:jsx(r.Flag,{children:" deploy"})})}),jsx(a.Out,{children:"push an agent to an environment"})]})]})]}),jsxs(Box,{paddingBottom:1,flexDirection:"column",children:[jsx(a.OutStrong,{children:"FLAGS"}),jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:26,children:jsxs(Text,{children:[jsx(r.Flag,{children:" --env "}),jsx(r.Arg,{children:"<name>"})]})}),jsxs(a.Out,{children:["target environment (default: ",p$1,")"]})]}),jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:26,children:jsx(Text,{children:jsx(r.Flag,{children:" --json"})})}),jsx(a.Out,{children:"machine-readable output"})]}),jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:26,children:jsx(Text,{children:jsx(r.Flag,{children:" --no-color"})})}),jsx(a.Out,{children:"disable ANSI colors"})]}),jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:26,children:jsx(Text,{children:jsx(r.Flag,{children:" -h, --help"})})}),jsx(a.Out,{children:"help for any command"})]})]})]}),jsxs(a.Dim,{children:["Run `culvii ","<command>"," --help` for more. Everything here respects your policy bundle."]})]})}
|
|
3
3
|
export{P as HelpView};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {a as a$3}from'./chunk-5NBKYMD7.js';import {a}from'./chunk-R67TA4FU.js';import {a as a$2}from'./chunk-FQVHJUX4.js';import {a as a$1}from'./chunk-JYNOILCD.js';import'./chunk-57XLDHK6.js';import {x,e,l,w,c,o}from'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import {useEffect}from'react';import {useApp,Box,Text}from'ink';import {jsxs,jsx}from'react/jsx-runtime';function R({state:e$1}){let{exit:a$4}=useApp();return useEffect(()=>{if(e$1.type!=="loading"){let m=setTimeout(()=>a$4(),100);return ()=>clearTimeout(m)}},[e$1.type,a$4]),jsxs(Box,{flexDirection:"column",children:[jsx(a,{command:"culvii",subcommand:"whoami"}),e$1.type==="loading"&&jsx(Box,{paddingLeft:2,children:jsx(a$1,{label:"Fetching identity\u2026"})}),e$1.type==="error"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:e,children:x}),jsx(Text,{color:l,children:e$1.message})]}),e$1.detail&&jsx(Box,{paddingLeft:2,children:jsx(a$2.Dim,{children:e$1.detail})})]}),e$1.type==="success"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:c,children:w}),jsx(Text,{color:l,children:e$1.email})]}),jsx(a$3,{variant:"default",compact:true,content:[{k:"tenant",v:jsxs(Text,{color:l,children:[e$1.tenantName," ",jsxs(Text,{color:o,children:["(",e$1.tenant,")"]})]})},{k:"workspace",v:jsx(Text,{color:l,children:e$1.workspace||jsx(Text,{color:o,children:"none"})})},{k:"access",v:e$1.access.length>0?jsx(Box,{flexDirection:"column",children:e$1.access.map((m,T)=>jsx(Text,{color:l,children:m},T))}):jsx(Text,{color:o,children:"none"})}]})]})]})}export{R as WhoamiView};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {a}from'./chunk-HX54IFSD.js';import {Analytics}from'@segment/analytics-node';var P={CLI_INSTALLED:"cli_installed",CLI_VERSION_VIEWED:"cli_version_viewed",CLI_HELP_VIEWED:"cli_help_viewed",CLI_UNHANDLED_ERROR:"cli_unhandled_error",LOGIN_STARTED:"login_started",LOGIN_SUCCEEDED:"login_succeeded",LOGIN_FAILED:"login_failed",LOGOUT:"logout",DEV_STARTED:"dev_started",DEV_STOPPED:"dev_stopped",DEV_FAILED:"dev_failed",DEPLOY_STARTED:"deploy_started",DEPLOY_SUCCEEDED:"deploy_succeeded",DEPLOY_FAILED:"deploy_failed",DEPLOY_ABORTED:"deploy_aborted",API_KEY_CREATED:"api_key_created",API_KEY_LISTED:"api_key_listed",API_KEY_REVOKED:"api_key_revoked",API_KEY_ROTATED:"api_key_rotated",API_KEY_CREATE_FAILED:"api_key_create_failed",API_KEY_LIST_FAILED:"api_key_list_failed",API_KEY_ROTATE_FAILED:"api_key_rotate_failed",API_KEY_REVOKE_FAILED:"api_key_revoke_failed",TENANT_SWITCHED:"tenant_switched",ENV_SWITCHED:"env_switched",ENV_SWITCH_FAILED:"env_switch_failed",WORKSPACE_CREATED:"workspace_created",WORKSPACE_LISTED:"workspace_listed",TENANT_SWITCH_FAILED:"tenant_switch_failed",WORKSPACE_CREATE_FAILED:"workspace_create_failed",WORKSPACE_LIST_FAILED:"workspace_list_failed",WHOAMI_VIEWED:"whoami_viewed",RENAME_STARTED:"rename_started",RENAME_SUCCEEDED:"rename_succeeded",RENAME_FAILED:"rename_failed",INIT_STARTED:"init_started",INIT_SUCCEEDED:"init_succeeded",INIT_FAILED:"init_failed"},D="byn3jQco5axUIlfeohbQYYPGrZgGpw7A",w=process.env.CULVII_TELEMETRY!=="false",o=w?new Analytics({writeKey:D,flushAt:1,flushInterval:0}):null;function m(){return {surface:"cli",cli_version:"0.0.6",node_version:process.version,os:process.platform,arch:process.arch}}var c=null;async function x(){if(c)return c;try{let{ConfigStore:n}=await import('./config-store-WSXGIIJ4.js');c=(await new n().read({exitOnError:!1})).anonymousId??"unknown";}catch{c="unknown";}return c}var d=null,E=null,f=false;function U(){f=false;}async function y(){if(f)return {userId:d,tenantId:E};try{let{ConfigStore:n}=await import('./config-store-WSXGIIJ4.js'),e=await new n().read({exitOnError:!1}),i=e.contexts[e.active];E=i?.tenant_id??null,d=i?.user_id??e.anonymousId??null;}catch{d=null,E=null;}finally{f=true;}return {userId:d,tenantId:E}}async function C(n,t={},e,i){if(o)try{let r=await y(),a=e??r.userId,s=i!==void 0?i:r.tenantId,_=await x();a?o.track({userId:a,event:n,properties:{...m(),...s?{tenant_id:s}:{},...t}}):o.track({anonymousId:_,event:n,properties:{...m(),...t}});}catch{}}async function V(n,t,e,i={}){await C(n,i,t,e);}async function F(n,t={}){if(o)try{o.identify({userId:n,traits:t});}catch{}}async function K(n,t){if(o)try{o.alias({userId:n,previousId:t});}catch{}}async function Y(n,t,e={}){if(o)try{o.group({userId:n,groupId:t,traits:e});}catch{}}var l=null;async function p(){if(o)return l||(l=o.flush({timeout:3e3}).catch(()=>{}).finally(()=>{l=null;}),l)}var u={dev:"development",sandbox:"sandbox",prod:"production"};function L(n){let t=Object.entries(u).find(([,e])=>e===n);return t?t[0]:null}var R=["dev","sandbox","prod"];function W(n){let t=new Set(n.map(L).filter(e=>e!==null));return R.find(e=>t.has(e))??null}var v;function G(n){v=n&&n in u?n:void 0;}function H(){return v}var k="https://api.platform.culvii.com",S={apiBaseUrl:k,clientId:"4h45e9ljrr7qjv9olag0c80fhh",cognitoDomain:"eu-west-21iv4il5iq.auth.eu-west-2.amazoncognito.com"},I=process.env.CULVII_ENV,h=I&&I in u?I:"dev",N={...S,logicalEnvironment:h,scopes:["openid","email","profile"],callbackPorts:[52700,52701,52702,52703,52704,52705,52706,52707,52708,52709],callbackPath:"/callback"};async function M(n){let e=await new a().read(),i=e.contexts[e.active];i||(console.error("Error: Active context key not found in contexts in ~/.culvii/config."),console.error("Please run `culvii login` to authenticate and configure your active context."),await p(),process.exit(1));let r={...i},a$1=n?.env??v;a$1&&(r.environment=a$1);let s=r.environment||"dev";r.environment_id=r.environment_ids?.[s]??r.environment_id,r.workspace_ids&&s in r.workspace_ids&&(r.workspace_id=r.workspace_ids[s]??null),r.workspace_slugs&&s in r.workspace_slugs&&(r.workspace_slug=r.workspace_slugs[s]??null),n?.workspace&&(r.workspace_id=n.workspace);let _=N.apiBaseUrl;return _||(console.error("Error: No API URL found for the configured platform."),await p(),process.exit(1)),{apiUrl:_,context:r}}function j(n){let t=n.environment||"dev",e=n.environment_ids?.[t]??n.environment_id;return {...n.tenant_id?{"x-tenant-id":n.tenant_id}:{},...e?{"x-environment-id":e}:{"x-environment-slug":u[t]}}}
|
|
3
|
+
export{P as a,x as b,U as c,y as d,C as e,V as f,F as g,K as h,Y as i,p as j,u as k,L as l,W as m,G as n,H as o,h as p,N as q,M as r,j as s};
|
package/dist/index.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a as a$5}from'./chunk-JFIFRAAR.js';import {a as a$4,b as b$1,c as c$1}from'./chunk-KZG5CFSB.js';import {n,e,a as a$2,j as j$1,d,f,c,q,r,s,o,k,l}from'./chunk-WB3426JN.js';import {a as a$3}from'./chunk-HX54IFSD.js';import'./chunk-57XLDHK6.js';import {x,w,y,z}from'./chunk-YKFGEPLO.js';import {a as a$1}from'./chunk-YPLDPHHD.js';import {a,b}from'./chunk-7UWDMECF.js';import {Command}from'commander';import Ee,{realpathSync,existsSync}from'fs';import {fileURLToPath}from'url';import ge from'react';import {render}from'ink';import tt from'ws';import X,{dirname,join}from'path';import ne from'fs/promises';import {createHash}from'crypto';import {spawn}from'child_process';import hn from'chokidar';import {createRequire}from'module';import Ut from'readline';import ut from'os';import {createInterface}from'readline/promises';import {stdout,stdin}from'process';import {jsx}from'react/jsx-runtime';var Tt=a(F=>{Object.defineProperty(F,"__esModule",{value:true});F.SINGLE_CHILD_SURFACE_COMPONENTS=F.SURFACE_COMPONENT_TYPES=F.SURFACE_COMPONENT_CATALOG=F.SURFACE_SLOTS=F.SURFACE_SLOT_POLICY=void 0;F.getSurfaceBindingPaths=_t;F.validateSurfaceDefinition=It;F.validateSurfaceResource=yn;F.SURFACE_SLOT_POLICY={output:{actions:["navigate"],form:false},wait:{actions:["navigate","node.resume","node.stop"],form:true}};F.SURFACE_SLOTS=Object.keys(F.SURFACE_SLOT_POLICY);F.SURFACE_COMPONENT_CATALOG={Stack:{children:"list"},Row:{children:"list"},Grid:{children:"list"},Card:{children:"single"},Section:{children:"single"},Tabs:{children:"list"},Accordion:{children:"single"},Divider:{children:"none"},Spacer:{children:"none"},Text:{children:"none"},Heading:{children:"none"},Markdown:{children:"none"},Badge:{children:"none"},KeyValue:{children:"none"},Stat:{children:"none"},Avatar:{children:"none"},Icon:{children:"none"},Image:{children:"none"},Code:{children:"none"},Timestamp:{children:"none"},Duration:{children:"none"},Money:{children:"none"},Table:{children:"none"},List:{children:"list"},Tree:{children:"none"},JsonInspector:{children:"none"},FileChip:{children:"none",interaction:"single-action"},StatusPill:{children:"none"},ProgressBar:{children:"none"},Spinner:{children:"none"},ErrorPanel:{children:"none"},Timeline:{children:"list"},Button:{children:"none",interaction:"single-action"},TextField:{children:"none",interaction:"input"},TextArea:{children:"none",interaction:"input"},Select:{children:"none",interaction:"input"},Checkbox:{children:"none",interaction:"input"},RadioGroup:{children:"none",interaction:"input"},DatePicker:{children:"none",interaction:"input"},Form:{children:"list"},DiffView:{children:"none"},ApproveRejectBar:{children:"none",interaction:"multi-action"},EmailMessageCard:{children:"none"},SlackMessageCard:{children:"none"},SlackThread:{children:"list"},CalendarEventCard:{children:"none"},AgentRunPanel:{children:"none"},ToolCallCard:{children:"none"}};F.SURFACE_COMPONENT_TYPES=Object.keys(F.SURFACE_COMPONENT_CATALOG);F.SINGLE_CHILD_SURFACE_COMPONENTS=F.SURFACE_COMPONENT_TYPES.filter(e=>F.SURFACE_COMPONENT_CATALOG[e].children==="single");var Et=300,At=12,dn=new Set(F.SURFACE_COMPONENT_TYPES),un=new Set(["$output","$input","$binary"]),pn=new Set(["text","number","date","datetime","json"]),fn=new Set(["text","textarea","number","email","url","checkbox","select","file"]);function gn(e){return (e.startsWith("/")?e.slice(1):e).split("/",1)[0]}function Ce(e,t){if(Array.isArray(e))for(let n of e)Ce(n,t);else if(e&&typeof e=="object"){let n=e;if(typeof n.path=="string")t.push(n.path);else for(let r of Object.values(n))Ce(r,t);}}function Re(e,t){if(Array.isArray(e)){for(let r of e)Re(r,t);return}if(!e||typeof e!="object")return;let n=e;if("path"in n){typeof n.path!="string"&&t.push("Surface binding path must be a string."),n.format!==void 0&&!pn.has(String(n.format))&&t.push(`Unknown surface binding format "${String(n.format)}".`);return}for(let r of Object.values(n))Re(r,t);}function _t(e){let t=[];for(let n of e.components??[])!n||typeof n!="object"||(Ce(n.props,t),Ce(n.actions,t));return Ce(e.form,t),Array.from(new Set(t))}function It(e,t){let n=[];try{new TextEncoder().encode(JSON.stringify(e)).byteLength>256*1024&&n.push("Surface definition exceeds 256 KiB.");}catch{return ["Surface definition must be JSON serializable."]}if(e?.schema!=="kit.ui/v1"&&n.push('Surface schema must be "kit.ui/v1".'),!Array.isArray(e?.components)||e.components.length===0)return [...n,"Surface requires at least one component."];e.components.length>Et&&n.push(`Surface cannot exceed ${Et} components.`);let r=new Map;for(let o of e.components){if(!o||typeof o!="object"||Array.isArray(o)){n.push("Every surface component must be an object.");continue}let a=o;if(typeof a.id!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(a.id)||typeof a.type!="string"){n.push("Every surface component requires id and type.");continue}r.has(a.id)&&n.push(`Duplicate component id "${a.id}".`),r.set(a.id,a),dn.has(a.type)||n.push(`Unknown component type "${a.type}".`);let l=F.SURFACE_COMPONENT_CATALOG[a.type];a.props!==void 0&&(!a.props||typeof a.props!="object"||Array.isArray(a.props))&&n.push(`Component "${a.id}" props must be an object.`),a.children!==void 0&&!Array.isArray(a.children)?n.push(`Component "${a.id}" children must be an array.`):a.children?.length&&l?.children==="none"?n.push(`Component "${a.id}" cannot have children.`):a.children&&a.children.length>1&&l?.children==="single"&&n.push(`Component "${a.id}" can have at most one child.`);let c=a.props?.bind;if(c!==void 0&&(l?.interaction!=="input"?n.push(`Component "${a.id}" cannot bind form state.`):(!F.SURFACE_SLOT_POLICY[t].form||typeof c!="string"||!(c==="/$form"||c.startsWith("/$form/")||c.startsWith("$form.")))&&n.push(`Component "${a.id}" requires a wait-surface $form binding.`)),a.actions!==void 0&&(!a.actions||typeof a.actions!="object"||Array.isArray(a.actions))){n.push(`Component "${a.id}" actions must be an object.`);continue}let w=Object.keys(a.actions??{}).length;w&&!["single-action","multi-action"].includes(l?.interaction??"")?n.push(`Component "${a.id}" cannot have actions.`):w>1&&l?.interaction==="single-action"&&n.push(`Component "${a.id}" can have at most one action.`),Re(a.props,n);for(let p of Object.values(a.actions??{})){if(!p||typeof p!="object"||Array.isArray(p)){n.push(`Component "${a.id}" has an invalid action.`);continue}let y=p;if(!["navigate","node.resume","node.stop"].includes(y.type)){n.push(`Unknown surface action "${String(y.type)}".`);continue}F.SURFACE_SLOT_POLICY[t].actions.includes(y.type)||n.push(`Action "${y.type}" is not allowed on "${t}" surfaces.`),y.type==="navigate"&&(!y.href||typeof y.href!="object"||typeof y.href.path!="string")&&n.push("Navigate actions require an href binding."),Re(y,n);}}(typeof e.root!="string"||!r.has(e.root))&&n.push(`Surface root "${String(e.root)}" is missing.`);let i=new Set,s=new Set,u=(o,a)=>{if(a>At)return void n.push(`Surface component depth exceeds ${At}.`);if(s.has(o))return void n.push(`Surface component cycle includes "${o}".`);if(i.has(o))return;let l=r.get(o);if(l){s.add(o);for(let c of Array.isArray(l.children)?l.children:[]){if(typeof c!="string"){n.push(`Component "${o}" has a non-string child reference.`);continue}r.has(c)?u(c,a+1):n.push(`Component "${o}" references missing child "${c}".`);}s.delete(o),i.add(o);}};typeof e.root=="string"&&u(e.root,1);for(let o of r.keys())i.has(o)||n.push(`Component "${o}" is unreachable from root.`);for(let o of _t(e)){let a=gn(o);a==="$form"&&!F.SURFACE_SLOT_POLICY[t].form?n.push(`Binding "${o}" is only allowed on wait surfaces.`):a!=="$form"&&!un.has(a)&&n.push(`Invalid surface binding path "${o}".`);}if(e.form!==void 0)if(F.SURFACE_SLOT_POLICY[t].form||n.push("Forms are only allowed on wait surfaces."),!Array.isArray(e.form?.fields))n.push("Surface form fields must be an array.");else {let o=new Set;for(let a of e.form.fields){if(!a||typeof a!="object"||Array.isArray(a)){n.push("Every surface form field must be an object.");continue}let l=a,c=l?.name,w=l?.type;typeof c!="string"||!c||o.has(c)?n.push(`Surface form field name "${String(c)}" is invalid or duplicated.`):o.add(c),fn.has(String(w))||n.push(`Unknown surface form field type "${String(w)}".`),(typeof l.label!="string"||!l.label.trim())&&n.push(`Surface form field "${String(c)}" requires a label.`),w==="file"&&"default"in l&&n.push(`File field "${String(c)}" cannot have a default binding.`),w==="file"&&(l.maxFiles!==void 0&&(!Number.isInteger(l.maxFiles)||Number(l.maxFiles)<1||Number(l.maxFiles)>5)&&n.push(`File field "${String(c)}" maxFiles must be between 1 and 5.`),l.maxBytes!==void 0&&(!Number.isInteger(l.maxBytes)||Number(l.maxBytes)<1||Number(l.maxBytes)>10*1024*1024)&&n.push(`File field "${String(c)}" maxBytes exceeds platform limits.`),l.accept!==void 0&&(!Array.isArray(l.accept)||l.accept.some(p=>typeof p!="string"||!/^[a-z0-9.+-]+\/(?:[a-z0-9.+-]+|\*)$/i.test(p)))&&n.push(`File field "${String(c)}" has invalid MIME types.`)),w==="select"&&(!Array.isArray(l.options)||l.options.length===0?n.push(`Select field "${String(c)}" requires options.`):l.options.some(p=>!p||typeof p!="object"||typeof p.label!="string"||typeof p.value!="string")&&n.push(`Select field "${String(c)}" has invalid options.`));}Re(e.form,n);}return Array.from(new Set(n))}function yn(e){let t=e;if(!t||typeof t!="object")return ["Surface must be an object."];let n=[];return (typeof t.id!="string"||!/^[a-z0-9][a-z0-9-]{0,62}$/.test(t.id))&&n.push("Surface requires a kebab-case id."),(typeof t.name!="string"||!t.name.trim())&&n.push("Surface requires a name."),F.SURFACE_SLOTS.includes(t.slot)?n.push(...It(t.definition,t.slot)):n.push(`Surface requires slot ${F.SURFACE_SLOTS.map(r=>`"${r}"`).join(" or ")}.`),Array.from(new Set(n))}});var St=a(ke=>{var wn=ke&&ke.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:true,get:function(){return t[n]}}),Object.defineProperty(e,r,i);}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n];})),mn=ke&&ke.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&wn(t,e,n);};Object.defineProperty(ke,"__esModule",{value:true});mn(Tt(),ke);});var Ue=class extends Error{constructor(){super("401 Unauthorized"),this.name="UnauthorizedError";}};function ln(e,t=Date.now()){return e-t<3e4}async function B(e$1){let t=new a$4,r=await(async()=>await t.withLock(async()=>{b$1.info("Tokens read from disk for auth check");let i=await t.get();if(i||(b$1.error("No tokens found on disk"),render(ge.createElement(c$1,{state:{type:"login_error",message:"Not logged in",detail:"run `culvii login`"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1)),!ln(i.expiresAt))return b$1.info("Access token valid, skipping refresh"),i.accessToken;b$1.info("Access token expired, attempting refresh");let s=`https://${q.cognitoDomain}/oauth2/token`,u=new URLSearchParams;u.set("grant_type","refresh_token"),u.set("refresh_token",i.refreshToken),u.set("client_id",q.clientId);let o;try{o=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:u.toString()});}catch(w){b$1.error("Network error during refresh",{error:w.message}),render(ge.createElement(c$1,{state:{type:"login_error",message:"Refresh failed",detail:"Cannot reach auth server \u2014 check your connection"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1);}let a=await o.json();(!o.ok||a.error==="invalid_grant")&&(b$1.warn("Refresh failed with invalid_grant"),await t.delete(),render(ge.createElement(c$1,{state:{type:"login_error",message:"Session expired",detail:"run `culvii login` to authenticate"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1));let l=Date.now(),c=l+a.expires_in*1e3;return b$1.info("Refresh succeeded",{expiresAt:c}),await t.set({accessToken:a.access_token,refreshToken:a.refresh_token||i.refreshToken,idToken:a.id_token||i.idToken,expiresAt:c,tokenType:"Bearer",scope:i.scope,issuedAt:l,issuer:i.issuer}),a.access_token}))();try{await e$1(r);}catch(i){if(!(i instanceof Ue))throw i;b$1.info("Mid-session 401 detected, attempting refresh");let s=await t.withLock(async()=>{b$1.info("Tokens read from disk for retry");let u=await t.get();u||(b$1.error("No tokens found on disk during retry"),render(ge.createElement(c$1,{state:{type:"login_error",message:"Not logged in",detail:"run `culvii login`"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1)),b$1.info("Access token expired (forced by 401), attempting refresh");let o=`https://${q.cognitoDomain}/oauth2/token`,a=new URLSearchParams;a.set("grant_type","refresh_token"),a.set("refresh_token",u.refreshToken),a.set("client_id",q.clientId);let l;try{l=await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a.toString()});}catch(y){b$1.error("Network error during refresh retry",{error:y.message}),render(ge.createElement(c$1,{state:{type:"login_error",message:"Refresh failed",detail:"Cannot reach auth server \u2014 check your connection"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1);}let c=await l.json();(!l.ok||c.error==="invalid_grant")&&(b$1.warn("Refresh retry failed with invalid_grant"),await t.delete(),render(ge.createElement(c$1,{state:{type:"login_error",message:"Session expired",detail:"run `culvii login` to authenticate"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1));let w=Date.now(),p=w+c.expires_in*1e3;return b$1.info("Refresh retry succeeded",{expiresAt:p}),await t.set({accessToken:c.access_token,refreshToken:c.refresh_token||u.refreshToken,idToken:c.id_token||u.idToken,expiresAt:p,tokenType:"Bearer",scope:u.scope,issuedAt:w,issuer:u.issuer}),c.access_token});try{b$1.info("Retry after refresh succeeded"),await e$1(s);}catch(u){throw u instanceof Ue&&(b$1.error("Retry after refresh failed (still 401)"),await t.withLock(async()=>{await t.delete();}),render(ge.createElement(c$1,{state:{type:"login_error",message:"Session invalidated",detail:"run `culvii login` to authenticate"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1)),u}}}async function et(){let e=new a$4;return e.withLock(async()=>{let t=await e.get();if(!t)return null;let n=`https://${q.cognitoDomain}/oauth2/token`,r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",t.refreshToken),r.set("client_id",q.clientId);let i;try{i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(a){return b$1.error("Network error during silent refresh",{error:a.message}),null}let s=await i.json();if(!i.ok||s.error==="invalid_grant")return b$1.warn("Silent refresh failed",{error:s.error}),null;let u=Date.now(),o=u+s.expires_in*1e3;return await e.set({accessToken:s.access_token,refreshToken:s.refresh_token||t.refreshToken,idToken:s.id_token||t.idToken,expiresAt:o,tokenType:"Bearer",scope:t.scope,issuedAt:u,issuer:t.issuer}),s.access_token})}async function Y(e){let t=await e.text();try{let n=JSON.parse(t);if(n.error)return n.error}catch{}return t}async function j(e,t,n={}){let{skipEnvironmentHeader:r,...i}=n,u=await new a$3().read({exitOnError:false}),o$1=u.contexts[u.active],a=o$1?.tenant_id,l=o$1?.environment||"dev",c=o()??l,w=o$1?.environment_ids?.[c]??(c===l?o$1?.environment_id:void 0),p=k[c],y=r?{}:w?{"x-environment-id":w}:{"x-environment-slug":p},k$1={Authorization:`Bearer ${t}`,...a?{"x-tenant-id":a}:{},...y,...i.headers||{}};return fetch(e,{...i,headers:k$1})}function kt(){let e=a$1();return e.isTTY&&!e.isCI&&e.supportsColor&&e.supportsUnicode}function ht(e$1){let t=e$1.command("workspace").description("Workspace commands").option("--env <env>","Target environment (sandbox or prod)");t.command("create").description("Create a new workspace").requiredOption("--name <name>","Workspace name").requiredOption("--slug <slug>","Workspace slug").action(async n=>{if(kt()){let u=function(){let[o,a]=ge.useState({type:"loading"});return ge.useEffect(()=>(s$1=a,()=>{s$1=null;}),[]),ge.createElement(i,{state:o})};let{WorkspaceCreateView:i}=await import('./WorkspaceView-RNFALIPM.js'),s$1=null;await V(Promise.resolve(ge.createElement(u))),await B(async o=>{let{apiUrl:a,context:l}=await r({env:t.opts().env}),c=s(l);try{let w=await j(`${a}/api/workspaces`,o,{method:"POST",headers:{...c,"Content-Type":"application/json"},body:JSON.stringify({name:n.name,slug:n.slug,tenantId:l.tenant_id})});if(!w.ok){let A=await Y(w);s$1?.({type:"error",message:"Failed to create workspace",detail:`Server responded with ${w.status}: ${A}`});let{userId:v,tenantId:D}=await d();v?await f(a$2.WORKSPACE_CREATE_FAILED,v,D,{error_class:"ApiError",slug:n.slug,env:l.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:"ApiError",slug:n.slug,env:l.environment}),await j$1();return}let p=await w.json();s$1?.({type:"success",id:p?.data?.workspaceId,slug:p?.data?.workspaceSlug||n.slug,name:n.name});let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_CREATED,y,k,{slug:n.slug,env:l.environment}):await e(a$2.WORKSPACE_CREATED,{slug:n.slug,env:l.environment}),await j$1();}catch(w){s$1?.({type:"error",message:"Unexpected error",detail:w.message});let{userId:p,tenantId:y}=await d();p?await f(a$2.WORKSPACE_CREATE_FAILED,p,y,{error_class:w?.constructor?.name,env:l.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:w?.constructor?.name,env:l.environment}),await j$1();}});return}await B(async i=>{let{apiUrl:s$1,context:u}=await r({env:t.opts().env}),o=s(u);console.log(`tenant: ${u.tenant_slug} | workspace: N/A | env: ${u.environment}`);try{let a=await j(`${s$1}/api/workspaces`,i,{method:"POST",headers:{...o,"Content-Type":"application/json"},body:JSON.stringify({name:n.name,slug:n.slug,tenantId:u.tenant_id})});if(!a.ok){let p=await Y(a);console.error(`Error: Failed to create workspace. Server responded with ${a.status}: ${p}`);let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_CREATE_FAILED,y,k,{error_class:"ApiError",slug:n.slug,env:u.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:"ApiError",slug:n.slug,env:u.environment}),await j$1(),process.exit(1);}let l=await a.json();console.log(`${w} Workspace created successfully.`),console.log(` ID: ${l?.data?.workspaceId}`),l?.data?.workspaceSlug&&console.log(` Slug: ${l?.data?.workspaceSlug}`);let{userId:c,tenantId:w$1}=await d();c?await f(a$2.WORKSPACE_CREATED,c,w$1,{slug:n.slug,env:u.environment}):await e(a$2.WORKSPACE_CREATED,{slug:n.slug,env:u.environment}),await j$1();}catch(a){console.error(`Error: Network or unexpected error: ${a.message}`);let{userId:l,tenantId:c}=await d();l?await f(a$2.WORKSPACE_CREATE_FAILED,l,c,{error_class:a?.constructor?.name,env:u.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:a?.constructor?.name,env:u.environment}),await j$1(),process.exit(1);}});}),t.command("list").description("List workspaces").action(async()=>{if(kt()){let s$1=function(){let[u,o]=ge.useState({type:"loading"});return ge.useEffect(()=>(i=o,()=>{i=null;}),[]),ge.createElement(r$1,{state:u})};let{WorkspaceListView:r$1}=await import('./WorkspaceView-RNFALIPM.js'),i=null;await V(Promise.resolve(ge.createElement(s$1))),await B(async u=>{let{apiUrl:o,context:a}=await r({env:t.opts().env}),l=s(a);try{let c=await j(`${o}/api/workspaces?tenantId=${a.tenant_id}`,u,{headers:l});if(!c.ok){let A=await Y(c);i?.({type:"error",message:"Failed to list workspaces",detail:`Server responded with ${c.status}: ${A}`});let{userId:v,tenantId:D}=await d();v?await f(a$2.WORKSPACE_LIST_FAILED,v,D,{error_class:"ApiError",env:a.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"ApiError",env:a.environment}),await j$1();return}let p=(await c.json())?.data?.workspaces;if(!Array.isArray(p)){i?.({type:"error",message:"Unexpected response format"});let{userId:A,tenantId:v}=await d();A?await f(a$2.WORKSPACE_LIST_FAILED,A,v,{error_class:"UnexpectedResponse",env:a.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"UnexpectedResponse",env:a.environment}),await j$1();return}i?.({type:"success",workspaces:p.map(A=>({id:A.id,name:A.name,slug:A.slug??""}))});let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_LISTED,y,k,{env:a.environment}):await e(a$2.WORKSPACE_LISTED,{env:a.environment}),await j$1();}catch(c){i?.({type:"error",message:"Unexpected error",detail:c.message});let{userId:w,tenantId:p}=await d();w?await f(a$2.WORKSPACE_LIST_FAILED,w,p,{error_class:c?.constructor?.name,env:a.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:c?.constructor?.name,env:a.environment}),await j$1();}});return}await B(async r$1=>{let{apiUrl:i,context:s$1}=await r({env:t.opts().env}),u=s(s$1);console.log(`tenant: ${s$1.tenant_slug} | workspace: N/A | env: ${s$1.environment}`);try{let o=await j(`${i}/api/workspaces?tenantId=${s$1.tenant_id}`,r$1,{headers:u});if(!o.ok){let p=await Y(o);console.error(`Error: Failed to list workspaces. Server responded with ${o.status}: ${p}`);let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_LIST_FAILED,y,k,{error_class:"ApiError",env:s$1.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"ApiError",env:s$1.environment}),await j$1(),process.exit(1);}let l=(await o.json())?.data?.workspaces;if(!Array.isArray(l)){console.error("Error: Unexpected response format");let{userId:p,tenantId:y}=await d();p?await f(a$2.WORKSPACE_LIST_FAILED,p,y,{error_class:"UnexpectedResponse",env:s$1.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"UnexpectedResponse",env:s$1.environment}),await j$1(),process.exit(1);}for(let p of l)console.log(`${p.id} ${p.name} ${p.slug}`);let{userId:c,tenantId:w}=await d();c?await f(a$2.WORKSPACE_LISTED,c,w,{env:s$1.environment}):await e(a$2.WORKSPACE_LISTED,{env:s$1.environment}),await j$1();}catch(o){console.error(`Error: Network or unexpected error: ${o.message}`);let{userId:a,tenantId:l}=await d();a?await f(a$2.WORKSPACE_LIST_FAILED,a,l,{error_class:o?.constructor?.name,env:s$1.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:o?.constructor?.name,env:s$1.environment}),await j$1(),process.exit(1);}});});}function nt(e,t,n){let r=null,i=0,s=false,u=[],o=new Map,a=null,l=null,c=0,w=[1e3,2e3,4e3,8e3,16e3];function p(){a&&(clearInterval(a),a=null),l&&(clearTimeout(l),l=null),c=0;}function y(){p(),a=setInterval(()=>{if(!r||r.readyState!==tt.OPEN)return;let R=Date.now().toString()+"-"+Math.random().toString();r.send(JSON.stringify({type:"client-ping",requestId:R})),l=setTimeout(()=>{c++,c>=2&&(b$1.warn("devSync WebSocket dead (missed 2 pongs), terminating"),p(),r?.terminate());},5e3);},2e4);}function k(R){R.removeAllListeners(),R.on("error",()=>{});try{R.terminate();}catch(L){b$1.warn("devSync error terminating stale socket",{error:L.message});}}let A=0;async function v(){if(s)return;let R=++A,L;try{L=await t();}catch(I){b$1.error("devSync failed to obtain headers for connection",{error:I.message}),R===A&&D();return}if(s||R!==A)return;r&&k(r);let f=new tt(e,{headers:L});r=f,f.on("open",()=>{if(r===f){i=0,b$1.info("devSync WebSocket connected",{url:e}),n.onOpen();for(let I of u)f.send(JSON.stringify(I));u=[],y();}}),f.on("message",I=>{if(r!==f)return;let E=Buffer.isBuffer(I)?I.toString("utf-8"):I instanceof ArrayBuffer?Buffer.from(I).toString("utf-8"):Buffer.concat(I).toString("utf-8"),g;try{g=JSON.parse(E);}catch{b$1.warn("Received invalid JSON from devSync",{raw:E});return}if(g.ok===true&&g.slug&&typeof g.warning=="string"){n.onWarning?.(g.slug,g.warning);return}if(g.type==="session-probe"&&typeof g.requestId=="string"){f.send(JSON.stringify({type:"session-pong",requestId:g.requestId}));return}if(g.type==="client-pong"){l&&(clearTimeout(l),l=null),c=0;return}if(g.ok===true&&g.slug&&g.type==="validation-error"){n.onValidationErrorAck?.(g.slug);return}if(g.ok===true&&g.slug){g.resourceId&&o.set(g.slug,g.resourceId),n.onAck(g.slug,g.resourceId,g.orphaned===true);return}if(g.ok===false&&g.slug){n.onError(g.slug,g.error||"Unknown error");return}if(g.ok===false&&!g.slug){n.onFatal(g.error||"Fatal error from server"),s=true,p(),f.close();return}}),f.on("unexpected-response",(I,E)=>{if(r===f){if(E.statusCode===401){b$1.error("devSync credentials rejected (401)"),s=true,p(),f.terminate(),n.onAuthFailure?n.onAuthFailure():n.onFatal("Credentials rejected by server (401)");return}b$1.warn("devSync unexpected handshake response",{statusCode:E.statusCode}),p(),f.terminate(),D();}}),f.on("close",I=>{r!==f||s||(b$1.warn("devSync WebSocket closed",{code:I}),p(),D());}),f.on("error",I=>{r===f&&b$1.error("devSync WebSocket error",{error:I.message});});}function D(){if(p(),s)return;if(i>=w.length){let f=`devSync PERMANENT FAILURE: giving up after ${w.length} retries`;b$1.error(f,{retryCount:i,retryDelaysMs:w}),n.onFatal(f),s=true;return}let R=w[i];i++;let L=w.length-i;b$1.info(`devSync reconnecting in ${R}ms (attempt ${i}/${w.length}, ${L} left before permanent failure)`),setTimeout(()=>{v();},R);}function $(R){r&&r.readyState===tt.OPEN?r.send(JSON.stringify(R)):u.push(R);}function M(){s=true,p(),r&&k(r),b$1.info("devSync WebSocket closed by client");}function S(){s||(p(),i=0,r&&k(r),v());}return v(),{send:$,close:M,reconnectNow:S}}var Ct=b(St(),1);var Tn=fileURLToPath(import.meta.url),Sn=dirname(Tn),Dn=join(Sn,"lib","evaluator.js"),Cn=createRequire(import.meta.url),Rn=Cn.resolve("tsx/cli");function Pe(e){return (0, Ct.validateSurfaceResource)(e)}function st(e){if(Array.isArray(e))return e.map(st);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=st(e[n]);return t}return e}function xn(e){if(!e||typeof e!="object")return e;let t={...e};return Array.isArray(t.nodes)&&(t.nodes=t.nodes.map(({id:n,...r})=>r)),t}function Ln(e){return createHash("sha256").update(JSON.stringify(st(xn(e)))).digest("hex")}function ye(e){return (Array.isArray(e?.nodes)?e.nodes:[]).filter(n=>n?.type==="core.agent").map(n=>n?.nodeParams?.agentReferenceKey??n?.nodeParams?.agentId).filter(n=>typeof n=="string"&&!n.startsWith("agt_"))}function Fe(e){return (Array.isArray(e?.nodes)?e.nodes:[]).flatMap(n=>["output","wait"].map(r=>n?.ui?.[r]).filter(r=>r?.kind==="custom"&&typeof r.surfaceKey=="string").map(r=>({surfaceKey:r.surfaceKey,...Number.isInteger(r.version)?{version:r.version}:{}})))}function $n(e){return Array.isArray(e)?e:e&&typeof e=="object"?Object.entries(e).map(([t,n])=>n&&typeof n=="object"&&!Array.isArray(n)?{name:t,...n}:n):[]}function Ie(e){return $n(e?.tools).filter(t=>t&&typeof t=="object"&&!Array.isArray(t)).map(t=>({referenceKey:t.workflowReferenceKey??t.workflowId,toolName:t.name,triggerNodeName:t.triggerNodeName})).filter(t=>typeof t.referenceKey=="string"&&!t.referenceKey.startsWith("wfl_"))}function Te(e){return Ie(e).map(t=>t.referenceKey)}function bn(e){return typeof e?.type=="string"&&e.type!=="manualTrigger"&&e.type.endsWith("Trigger")}function On(e,t){return e.get(t)??e.get(W(t))}function Rt(e){let t=new Set,n=[];for(let r of e.values())t.has(r.id)||(t.add(r.id),n.push(r));return n}function xt(e,t){let n=typeof e?.id=="string"?e.id:"unknown";if(Ie(e).length>0)return {id:n,definition:e};let r=n==="unknown"?void 0:On(t,n);return r?{id:n,definition:r.definition}:e&&typeof e=="object"&&!Array.isArray(e)?{id:n,definition:e}:null}function at(e,t){let n=[e];for(let r of e.definition?.secondaryAgents??[]){let i=xt(r,t);i&&n.push(i);}return n}function We(e){let t=new Map,n=new Map;for(let s of e){let u=s.definition?.id;typeof u=="string"&&(s.type==="agent"?(t.set(u,{id:u,definition:s.definition}),t.set(W(u),{id:u,definition:s.definition})):s.type==="workflow"&&(n.set(u,s.definition),n.set(W(u),s.definition)));}let r=new Set;for(let s of Rt(t))for(let u of at(s,t))for(let o of Te(u.definition))r.add(W(o));let i=new Set;for(let s of r){let u=n.get(s);if(u)for(let o of ye(u))i.add(W(o));}for(let s of i){let u=t.get(s);if(u){if(Ie(u.definition).length>0)return `agent '${u.id}' cannot define workflow tools when invoked by an agent workflow tool.`;for(let o of u.definition?.secondaryAgents??[]){let a=xt(o,t);if(a&&Ie(a.definition).length>0)return `secondary agent '${a.id}' referenced by agent '${u.id}' cannot define workflow tools when '${u.id}' is invoked by an agent workflow tool.`}}}return null}function Me(e){let t=new Map,n=new Map;for(let i of e){let s=i.definition?.id;typeof s=="string"&&(i.type==="agent"?(t.set(s,{id:s,definition:i.definition}),t.set(W(s),{id:s,definition:i.definition})):i.type==="workflow"&&(n.set(s,i.definition),n.set(W(s),i.definition)));}let r=new Set;for(let i of n.values())for(let s of ye(i))r.add(W(s));for(let i of r){let s=t.get(i);if(!s)continue;let u=at(s,t);for(let o of u)for(let a of Ie(o.definition)){let l=n.get(a.referenceKey)??n.get(W(a.referenceKey));if(!(!l||ye(l).length===0))return `workflow tool '${a.toolName??"unknown"}' on agent '${o.id}' cannot reference workflow '${a.referenceKey}' because '${s.id}' is invoked by a workflow and the target workflow contains an agent node.`}}return null}function je(e){let t=new Map,n=new Map;for(let r of e){let i=r.definition?.id;typeof i=="string"&&(r.type==="agent"?(t.set(i,{id:i,definition:r.definition}),t.set(W(i),{id:i,definition:r.definition})):r.type==="workflow"&&(n.set(i,r.definition),n.set(W(i),r.definition)));}for(let r of Rt(t))for(let i of at(r,t))for(let s of Ie(i.definition)){let u=n.get(s.referenceKey)??n.get(W(s.referenceKey));if(!u)continue;let o=Array.isArray(u.nodes)?u.nodes:[],a=o.find(bn);if(a)return `workflow tool '${s.toolName??"unknown"}' on agent '${i.id}' references workflow '${s.referenceKey}' with non-manual trigger '${a.name??a.type}'.`;if(s.triggerNodeName){if(o.find(w=>w?.name===s.triggerNodeName)?.type==="manualTrigger")continue;return `workflow tool '${s.toolName??"unknown"}' on agent '${i.id}' must use a manual trigger in workflow '${s.referenceKey}'.`}let l=o.filter(c=>c?.type==="manualTrigger");if(l.length!==1)return l.length===0?`workflow tool '${s.toolName??"unknown"}' on agent '${i.id}' references workflow '${s.referenceKey}' without a manual trigger.`:`workflow tool '${s.toolName??"unknown"}' on agent '${i.id}' must specify triggerNodeName because workflow '${s.referenceKey}' has multiple manual triggers.`}return null}function Ve(e){let t=[],n=(r,i)=>{let s=i&&typeof i=="object"&&!Array.isArray(i)?i.credentialId:void 0;(typeof s!="string"||!s.trim())&&t.push(`agent '${r}' model must include a credentialId \u2014 use model: { provider, modelId, credentialId }.`);};e?.modelConfig!==void 0&&e?.modelConfig!==null&&n(e?.id,e.modelConfig);for(let r of e?.secondaryAgents??[])r?.modelConfig!==void 0&&r?.modelConfig!==null&&n(r?.id??e?.id,r.modelConfig);return t}function Ke(e){let t=new Map;for(let i of e){let s=i.definition?.id;if(!s)continue;let u=i.type==="agent"?Te(i.definition).map(o=>`workflow:${o}`):i.type==="workflow"?ye(i.definition).map(o=>`agent:${o}`):[];t.set(`${i.type}:${s}`,u);}let n=null;function r(i,s){if(!n)for(let u of t.get(i)??[]){if(!t.has(u))continue;let o=[...s,u];if(s.length>=3){n=`Unsupported nested SDK reference chain: ${o.join(" -> ")}. Only workflow -> agent -> workflow or agent -> workflow -> agent is supported.`;return}r(u,o);}}for(let i of t.keys())r(i,[i]);return n}async function Nn(e){try{let r=X.join(e,"culvii.yaml"),s=(await ne.readFile(r,"utf-8")).split(`
|
|
3
|
-
`),
|
|
4
|
-
`).filter(w=>w.includes("__culvii_dev_definitions__"));if(
|
|
5
|
-
`);}async function
|
|
6
|
-
Run: culvii rename ${N} ${G.slug} --resource-type ${x}`,"warn"):(e.onOrphan(N,x),n.delete(g),I++);}let E=[...k.entries()].sort(([,g],[,C])=>+(C.type==="surface")-+(g.type==="surface"));for(let[g,{slug:C,type:x,definition:N,hash:G}]of E){let re=n.get(g);(!re||re.hash!==G)&&(n.set(g,{hash:G,type:x}),e.onSync({type:x,slug:C,definition:N,configHash:G}),I++);}I===0&&a(z,"No changes to sync.","info");}let c=hn.watch(t,{ignored:p=>p.includes("node_modules")||p.includes("/dist/")||p.includes("/.git/"),ignoreInitial:true,persistent:true});c.on("all",(p,y)=>{y.endsWith(".ts")&&(r&&clearTimeout(r),r=setTimeout(()=>{o();},500));});let w=false;return {close:()=>c.close(),triggerFullSync:()=>{if(w){o();return}if(w=true,i){u=true,s=true;return}n.clear(),o();}}}function Pn(){let e=a$1();return e.isTTY&&!e.isCI&&e.supportsColor&&e.supportsUnicode}var Se="https://console.culvii.com/";function Lt(){let e=new Date,t=n=>String(n).padStart(2,"0");return `${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}async function Fn(){let{DevView:e$1}=await import('./DevView-SOPAMSZ4.js'),t=null;function n(){let[r,i]=ge.useState({type:"provisioning",message:"Starting dev server\u2026"});return ge.useEffect(()=>(t=i,()=>{t=null;}),[]),ge.createElement(e$1,{state:r})}await V(Promise.resolve(ge.createElement(n))),await B(async r$1=>{let i=new a$3,s$1=await i.read({exitOnError:!1}),u=Date.now();if(!s$1.active||!s$1.contexts[s$1.active]){t?.({type:"error",message:"No active context. Run culvii login first."});let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEV_FAILED,f$1,I,{error_class:"NoActiveContext",workspace:a?.workspace_slug,env:a?.environment}):await e(a$2.DEV_FAILED,{error_class:"NoActiveContext",workspace:a?.workspace_slug,env:a?.environment}),await j$1();return}let{apiUrl:o,context:a}=await r({env:"dev"}),l=s(a),c=a.workspace_id,w=a.workspace_slug;t?.({type:"provisioning",message:"Provisioning dev workspace\u2026"});try{let f$1=await j(`${o}/api/workspaces`,r$1,{method:"POST",headers:{...l,"Content-Type":"application/json"},body:JSON.stringify({name:`dev-${a.user_id.slice(0,12)}`,slug:`dev-${a.user_id.slice(0,12)}`,tenantId:a.tenant_id})});if(!f$1.ok){let E=await Y(f$1);t?.({type:"error",message:`Failed to auto-provision workspace: ${E}`});let{userId:g,tenantId:C}=await d();g?await f(a$2.DEV_FAILED,g,C,{error_class:"WorkspaceProvisionError",workspace:a?.workspace_slug,env:a?.environment}):await e(a$2.DEV_FAILED,{error_class:"WorkspaceProvisionError",workspace:a?.workspace_slug,env:a?.environment}),await j$1();return}let I=await f$1.json();await i.withLock(async()=>{s$1=await i.read();let E=s$1.contexts[s$1.active];E.workspace_ids={...E.workspace_ids||{},dev:I?.data?.workspaceId},E.workspace_slugs={...E.workspace_slugs||{},dev:I?.data?.workspaceSlug},E.workspace_id=I?.data?.workspaceId,E.workspace_slug=I?.data?.workspaceSlug,await i.write(s$1);}),a={...s$1.contexts[s$1.active],environment:"dev"},c=a.workspace_id,w=a.workspace_slug;}catch(f$1){t?.({type:"error",message:`Failed to auto-provision workspace: ${f$1.message}`});let{userId:I,tenantId:E}=await d();I?await f(a$2.DEV_FAILED,I,E,{error_class:f$1?.constructor?.name,workspace:a?.workspace_slug,env:a?.environment}):await e(a$2.DEV_FAILED,{error_class:f$1?.constructor?.name,workspace:a?.workspace_slug,env:a?.environment}),await j$1();return}let{userId:p,tenantId:y}=await d();p?await f(a$2.DEV_STARTED,p,y,{workspace:a.workspace_slug,env:a.environment}):await e(a$2.DEV_STARTED,{workspace:a.workspace_slug,env:a.environment});let k=[];function A(f){return {Authorization:`Bearer ${f}`,...l}}let v=r$1;async function D(){let f=await et();return f&&(v=f),A(v)}let $=o.replace(/^http/,"ws")+"/api/dev/sync?workspaceId="+encodeURIComponent(c),M,S=nt($,D,{onOpen:()=>{t?.({type:"connected",workspace:w??`dev-${a.user_id.slice(0,12)}`,env:"dev",log:[...k],consoleUrl:Se}),M?.triggerFullSync();},onAck:(f,I,E)=>{let g={type:E?"orphaned":"synced",message:`${E?"orphaned":"synced"} ${f}`,timestamp:Lt()};k.push(g),t?.({type:"connected",workspace:w??`dev-${a.user_id.slice(0,12)}`,env:"dev",log:[...k],consoleUrl:Se});},onValidationErrorAck:()=>{},onWarning:(f,I)=>{let E={type:"warning",message:I};k.push(E),t?.({type:"connected",workspace:w??`dev-${a.user_id.slice(0,12)}`,env:"dev",log:[...k],consoleUrl:Se});},onError:(f,I)=>{let E={type:"error",message:`Sync failed for ${f}: ${I}`};k.push(E),t?.({type:"connected",workspace:w??`dev-${a.user_id.slice(0,12)}`,env:"dev",log:[...k],consoleUrl:Se});},onFatal:async f$1=>{clearInterval(L);let I=`Fatal error: ${f$1}. Shutting down...`;t?.({type:"error",message:I});let{userId:E,tenantId:g}=await d();E?await f(a$2.DEV_FAILED,E,g,{error_class:"FatalWebSocketError",workspace:a.workspace_slug,workspace:a?.workspace_slug,env:a?.environment}):await e(a$2.DEV_FAILED,{error_class:"FatalWebSocketError",workspace:a.workspace_slug,workspace:a?.workspace_slug,env:a?.environment}),M?.close(),S?.close(),he(1,I);},onAuthFailure:async()=>{clearInterval(L);let f$1="Your session was rejected by the server. Run `culvii login` to re-authenticate. Shutting down...";t?.({type:"error",message:f$1});let{userId:I,tenantId:E}=await d();I?await f(a$2.DEV_FAILED,I,E,{error_class:"ApiKeyRejected",workspace:a.workspace_slug,workspace:a?.workspace_slug,env:a?.environment}):await e(a$2.DEV_FAILED,{error_class:"ApiKeyRejected",workspace:a.workspace_slug,workspace:a?.workspace_slug,env:a?.environment}),M?.close(),S?.close(),he(1,f$1);}});M=ot({workspaceId:c,onSync:f=>{S.send({type:"sync",slug:f.slug,resourceType:f.type,definition:f.definition,workspaceId:c});},onOrphan:(f,I)=>{S.send({type:"orphan",slug:f,resourceType:I,workspaceId:c});},onValidationError:({resourceType:f,slug:I,missingReferenceId:E,message:g})=>{S.send({type:"validation-error",slug:I,resourceType:f,workspaceId:c,missingReferenceId:E,message:g});},onLog:(f,I)=>{let E={type:I==="error"?"error":I==="warn"?"warning":"info",message:f};k.push(E),t?.({type:"connected",workspace:w??`dev-${a.user_id.slice(0,12)}`,env:"dev",log:[...k],consoleUrl:Se});}});let R=3e3*1e3,L=setInterval(()=>{S.reconnectNow();},R);process.on("SIGINT",async()=>{clearInterval(L),S.close(),M.close(),t?.({type:"disconnected"});let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEV_STOPPED,f$1,I,{duration_ms:Date.now()-u,workspace:a.workspace_slug,env:a.environment}):await e(a$2.DEV_STOPPED,{duration_ms:Date.now()-u,workspace:a.workspace_slug,env:a.environment}),await j$1(),process.exit(0);});});}function $t(e$1){e$1.command("dev").description("Start the development server and file watcher").action(async()=>{if(Pn()){await Fn();return}await B(async t=>{let n=new a$3,r$1=await n.read({exitOnError:!1});if(!r$1.active||!r$1.contexts[r$1.active]){console.error("No active context. Run culvii login first.");let{userId:S,tenantId:R}=await d();S?await f(a$2.DEV_FAILED,S,R,{error_class:"NoActiveContext",workspace:s$1?.workspace_slug,env:s$1?.environment}):await e(a$2.DEV_FAILED,{error_class:"NoActiveContext",workspace:s$1?.workspace_slug,env:s$1?.environment}),await j$1(),process.exit(1);}let{apiUrl:i,context:s$1}=await r({env:"dev"}),u=s(s$1),o=Date.now(),a=s$1.workspace_id,l=s$1.workspace_slug;try{let S=await j(`${i}/api/workspaces`,t,{method:"POST",headers:{...u,"Content-Type":"application/json"},body:JSON.stringify({name:`dev-${s$1.user_id.slice(0,12)}`,slug:`dev-${s$1.user_id.slice(0,12)}`,tenantId:s$1.tenant_id})});if(!S.ok){let L=await Y(S);console.error(`Failed to auto-provision workspace: ${L}`);let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEV_FAILED,f$1,I,{error_class:"WorkspaceProvisionError",workspace:s$1.workspace_slug,workspace:s$1?.workspace_slug,env:s$1?.environment}):await e(a$2.DEV_FAILED,{error_class:"WorkspaceProvisionError",workspace:s$1.workspace_slug,workspace:s$1?.workspace_slug,env:s$1?.environment}),await j$1(),process.exit(1);}let R=await S.json();await n.withLock(async()=>{r$1=await n.read();let L=r$1.contexts[r$1.active];L.workspace_ids={...L.workspace_ids||{},dev:R?.data?.workspaceId},L.workspace_slugs={...L.workspace_slugs||{},dev:R?.data?.workspaceSlug},L.workspace_id=R?.data?.workspaceId,L.workspace_slug=R?.data?.workspaceSlug,await n.write(r$1);}),s$1={...r$1.contexts[r$1.active],environment:"dev"},a=s$1.workspace_id,l=s$1.workspace_slug;}catch(S){console.error(`Failed to auto-provision workspace: ${S.message}`);let{userId:R,tenantId:L}=await d();R?await f(a$2.DEV_FAILED,R,L,{error_class:S?.constructor?.name,workspace:s$1.workspace_slug,workspace:s$1?.workspace_slug,env:s$1?.environment}):await e(a$2.DEV_FAILED,{error_class:S?.constructor?.name,workspace:s$1.workspace_slug,workspace:s$1?.workspace_slug,env:s$1?.environment}),await j$1(),process.exit(1);}console.log(`tenant: ${s$1.tenant_slug} | workspace: ${l||"unknown"} | env: dev`);let{userId:c,tenantId:w$1}=await d();c?await f(a$2.DEV_STARTED,c,w$1,{workspace:s$1.workspace_slug,env:s$1.environment}):await e(a$2.DEV_STARTED,{workspace:s$1.workspace_slug,env:s$1.environment});function p(S){return {Authorization:`Bearer ${S}`,...u}}let y$1=t;async function k(){let S=await et();return S&&(y$1=S),p(y$1)}let A=i.replace(/^http/,"ws")+"/api/dev/sync?workspaceId="+encodeURIComponent(a),v,D=nt(A,k,{onOpen:()=>{console.log(`Watching ./... Connected to ${l??`dev-${s$1.user_id.slice(0,12)}`} (dev)`),console.log(`Console: ${Se}`),v?.triggerFullSync();},onAck:(S,R,L)=>{let f=Lt();console.log(L?`${w} [${f}] orphaned ${S}`:`${w} [${f}] synced ${S}`);},onValidationErrorAck:()=>{},onWarning:(S,R)=>{console.log(`${y} ${R}`);},onError:(S,R)=>{console.log(`${y} Sync failed for ${S}: ${R}`);},onFatal:async S=>{clearInterval(M),console.error(`Fatal error: ${S}. Shutting down...`);let{userId:R,tenantId:L}=await d();R?await f(a$2.DEV_FAILED,R,L,{error_class:"FatalWebSocketError",workspace:s$1.workspace_slug,workspace:s$1?.workspace_slug,env:s$1?.environment}):await e(a$2.DEV_FAILED,{error_class:"FatalWebSocketError",workspace:s$1.workspace_slug,workspace:s$1?.workspace_slug,env:s$1?.environment}),await j$1(),v?.close(),D?.close(),process.exit(1);},onAuthFailure:async()=>{clearInterval(M),console.error(`${x} Your session was rejected by the server. Run \`culvii login\` to re-authenticate. Shutting down...`);let{userId:S,tenantId:R}=await d();S?await f(a$2.DEV_FAILED,S,R,{error_class:"ApiKeyRejected",workspace:s$1.workspace_slug,workspace:s$1?.workspace_slug,env:s$1?.environment}):await e(a$2.DEV_FAILED,{error_class:"ApiKeyRejected",workspace:s$1.workspace_slug,workspace:s$1?.workspace_slug,env:s$1?.environment}),await j$1(),v?.close(),D?.close(),process.exit(1);}});v=ot({workspaceId:a,onSync:S=>{let R={type:"sync",slug:S.slug,resourceType:S.type,definition:S.definition,workspaceId:a};D.send(R);},onOrphan:(S,R)=>{let L={type:"orphan",slug:S,resourceType:R,workspaceId:a};D.send(L);},onValidationError:({resourceType:S,slug:R,missingReferenceId:L,message:f})=>{let I={type:"validation-error",slug:R,resourceType:S,workspaceId:a,missingReferenceId:L,message:f};D.send(I);}});let $=3e3*1e3,M=setInterval(()=>{D.reconnectNow();},$);process.on("SIGINT",async()=>{clearInterval(M),D.close(),v.close(),console.log("Disconnected. Draft state discarded.");let{userId:S,tenantId:R}=await d();S?await f(a$2.DEV_STOPPED,S,R,{duration_ms:Date.now()-o,workspace:s$1.workspace_slug,env:s$1.environment}):await e(a$2.DEV_STOPPED,{duration_ms:Date.now()-o,workspace:s$1.workspace_slug,env:s$1.environment}),await j$1(),process.exit(0);});});});}function Hn(){let e=a$1();return e.isTTY&&!e.isCI&&e.supportsColor&&e.supportsUnicode}function ct(e){if(Array.isArray(e))return e.map(ct);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=ct(e[n]);return t}return e}function Bn(e){if(!e||typeof e!="object")return e;let t={...e};return Array.isArray(t.nodes)&&(t.nodes=t.nodes.map(({id:n,...r})=>r)),t}function Pt(e){return createHash("sha256").update(JSON.stringify(ct(Bn(e)))).digest("hex")}async function Ft(e){try{let r=X.join(e,"culvii.yaml"),s=(await ne.readFile(r,"utf-8")).split(`
|
|
7
|
-
`),
|
|
8
|
-
`).filter(k=>k.includes("__culvii_dev_definitions__")),p=[],y=new Set;for(let k of w)try{let A=JSON.parse(k);for(let v of A.__culvii_dev_definitions__||[]){let D=v?.definition?.id,$=v?.type&&D?`${v.type}:${D}`:null;if($){if(y.has($))continue;y.add($);}p.push(v);}}catch{}n(p);});})}function qn(e){return new Promise(t=>{let n=Ut.createInterface({input:process.stdin,output:process.stdout});n.question(e,r=>{n.close(),t(r.toLowerCase()==="y"||r.toLowerCase()==="yes");});})}function Gn(e,t){return new Promise(n=>{let r=Ut.createInterface({input:process.stdin,output:process.stdout});r.question(e,i=>{r.close();let s=i.trim().toLowerCase();n(t.includes(s)?s:t[0]);});})}function Jn(e){if(e.type==="surface")return ` - ${e.slug}: marks inactive; published versions are retained`;let t=e.versionCount??1,n=e.activeVersion??e.previousVersion;return ` - ${e.slug}: deletes all ${t} ${t===1?"version":"versions"}${n?`; active is v${n}`:""}`}function Ot(e){console.log(`${y} Selected removals:`);for(let t of e)console.log(Jn(t));}function Nt(e){let t=e.executions??0,n=e.activeExecutions??0,r=e.activeVersion??e.previousVersion;return `${t} total, active${r?` v${r}`:""}: ${n} executions`}async function zn(e){return e.destroyed.length===0?{deleteMissing:false}:e.allowDestroy?(Ot(e.destroyed),{deleteMissing:true}):(console.log(""),console.log(`${y} ${e.destroyed.length} missing resource(s) found in ${e.env}.`),console.log(" k: keep them active"),console.log(" d: delete all missing resources"),await Gn("Delete missing resources? [k/d] ",["k","d"])==="d"?(Ot(e.destroyed),{deleteMissing:false,deleteMissingReferences:e.destroyed.map(n=>({type:n.type,referenceKey:n.referenceKey??n.slug}))}):{deleteMissing:false})}async function Xn(e$1){let{DeployView:t}=await import('./DeployView-GEJNL26A.js'),n=null,r$1=null;function i(){let[s,u]=ge.useState({type:"planning"});return ge.useEffect(()=>(n=u,()=>{n=null;}),[]),ge.createElement(t,{state:s,onConfirm:(o,a=false)=>{r$1?.({confirmed:o,deleteMissing:a});}})}await V(Promise.resolve(ge.createElement(i))),await B(async s$1=>{if(e$1.env==="dev"){n?.({type:"error",message:"Use culvii dev for local iteration"}),await j$1();return}if(e$1.env!=="sandbox"&&e$1.env!=="prod"){n?.({type:"error",message:"Environment must be sandbox or prod"}),await j$1();return}let{apiUrl:u,context:o}=await r({env:e$1.env}),a=s(o);if(!e$1.workspaceSlug){n?.({type:"error",message:"--workspace-slug <slug> is required for deploy",detail:"Run `culvii workspace list` to see available workspaces."});let{userId:E,tenantId:g}=await d();E?await f(a$2.DEPLOY_FAILED,E,g,{error_class:"NoWorkspace",workspace:e$1.workspaceSlug}):await e(a$2.DEPLOY_FAILED,{error_class:"NoWorkspace",workspace:e$1.workspaceSlug}),await j$1();return}let l=await j(`${u}/api/workspaces?tenantId=${o.tenant_id}`,s$1,{headers:a});if(!l.ok){n?.({type:"error",message:"Failed to fetch workspaces",detail:await Y(l)});let{userId:E,tenantId:g}=await d();E?await f(a$2.DEPLOY_FAILED,E,g,{env:e$1.env,error_class:"WorkspaceFetchError",workspace:e$1.workspaceSlug}):await e(a$2.DEPLOY_FAILED,{env:e$1.env,error_class:"WorkspaceFetchError",workspace:e$1.workspaceSlug}),await j$1();return}let p=((await l.json())?.data?.workspaces||[]).find(E=>E.slug===e$1.workspaceSlug);if(!p){n?.({type:"error",message:`Workspace not found: ${e$1.workspaceSlug}`});let{userId:E,tenantId:g}=await d();E?await f(a$2.DEPLOY_FAILED,E,g,{env:e$1.env,workspace:e$1.workspaceSlug,error_class:"WorkspaceNotFound"}):await e(a$2.DEPLOY_FAILED,{env:e$1.env,workspace:e$1.workspaceSlug,error_class:"WorkspaceNotFound"}),await j$1();return}let y=p.id,k=process.cwd(),A=await Ft(k),v=(await Wt(A,{})).sort((E,g)=>+(g.type==="surface")-+(E.type==="surface")),D=[],$=new Set,M=new Set(v.filter(E=>E.type==="surface").map(E=>W(E.definition.id??"")).filter(Boolean)),S=async E=>{n?.({type:"error",message:E});let{userId:g,tenantId:C}=await d();g?await f(a$2.DEPLOY_FAILED,g,C,{env:e$1.env,workspace:p?.slug,error_class:"ValidationError"}):await e(a$2.DEPLOY_FAILED,{env:e$1.env,workspace:p?.slug,error_class:"ValidationError"}),await j$1();};for(let E of v){let g=E.definition.id;g&&$.add(typeof g=="string"?W(g):String(g));}for(let E of v){let g=E.definition.id;if(!g){n?.({type:"error",message:`Deploy failed: ${E.type} is missing an explicit id.`}),await j$1();return}let C=typeof g=="string"?W(g):String(g);if(E.type==="surface"){let x=Pe(E.definition);if(x.length)return S(`Deploy failed: surface '${C}' ${x.join("; ")}.`)}if(E.type==="agent"){for(let N of Ve(E.definition))return S(`Deploy failed: ${N}`);let x=E.definition.secondaryAgents||[];for(let N of x){let G=N.id,re=!!(N?.systemPrompt||N?.modelConfig);if(G&&!re&&!$.has(G))return S(`Deploy failed: agent '${C}' references secondary agent '${G}' which is not defined.`)}for(let N of Te(E.definition))if(!$.has(W(N)))return S(`Deploy failed: agent '${C}' references workflow '${N}' which is not defined.`)}if(E.type==="workflow"){for(let x of ye(E.definition))if(!$.has(W(x)))return S(`Deploy failed: workflow '${C}' references agent '${x}' which is not defined.`);for(let x of Fe(E.definition))if(x.version===void 0&&!M.has(W(x.surfaceKey)))return S(`Deploy failed: workflow '${C}' references local surface '${x.surfaceKey}' which is not defined. Pin a published version or define the surface.`)}D.push({type:E.type,slug:C,definition:E.definition,configHash:Pt(E.definition)});}let R=We(v);if(R)return S(`Deploy failed: ${R}`);let L=je(v);if(L)return S(`Deploy failed: ${L}`);let f$1=Me(v);if(f$1)return S(`Deploy failed: ${f$1}`);let I=Ke(v);if(I)return S(`Deploy failed: ${I}`);try{let{userId:E,tenantId:g}=await d();E?await f(a$2.DEPLOY_STARTED,E,g,{env:e$1.env,workspace:p.slug}):await e(a$2.DEPLOY_STARTED,{env:e$1.env,workspace:p.slug});let C=await j(`${u}/api/workspaces/${y}/deploys/plan`,s$1,{method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify({environment:e$1.env,definitions:D})});if(!C.ok){let z=await Y(C);n?.({type:"error",message:"Failed to plan deploy",detail:z});let{userId:ce,tenantId:Ze}=await d();ce?await f(a$2.DEPLOY_FAILED,ce,Ze,{env:e$1.env,workspace:p?.slug,error_class:"PlanError"}):await e(a$2.DEPLOY_FAILED,{env:e$1.env,workspace:p?.slug,error_class:"PlanError"}),await j$1();return}let x=await C.json(),N=x.plan,G=x.planToken;if(!((N.created||[]).length>0||(N.versioned||[]).length>0||(N.destroyed||[]).length>0)){n?.({type:"no_changes"}),await j$1();return}let pe=await new Promise(z=>{r$1=z,n?.({type:"confirming",plan:{created:N.created||[],versioned:N.versioned||[],destroyed:(N.destroyed||[]).map(ce=>({...ce,renameHint:ce.renameHint?.suggestedCommand}))},env:e$1.env,allowDestroy:!!e$1.allowDestroy});});if(!pe.confirmed){n?.({type:"aborted",reason:"user_cancelled"});let{userId:z,tenantId:ce}=await d();z?await f(a$2.DEPLOY_ABORTED,z,ce,{env:e$1.env,workspace:p?.slug,reason:"user_cancelled"}):await e(a$2.DEPLOY_ABORTED,{env:e$1.env,workspace:p?.slug,reason:"user_cancelled"}),await j$1();return}let ee=e$1.allowDestroy||(N.destroyed||[]).length===0?{deleteMissing:!!e$1.allowDestroy}:pe.deleteMissing?{deleteMissing:!1,deleteMissingReferences:(N.destroyed||[]).map(z=>({type:z.type,referenceKey:z.referenceKey??z.slug}))}:{deleteMissing:!1};n?.({type:"applying"});let P=await j(`${u}/api/workspaces/${y}/deploys/apply`,s$1,{method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify({planToken:G,...ee})});if(!P.ok){let z=await Y(P);n?.({type:"error",message:"Failed to apply deploy",detail:z});let{userId:ce,tenantId:Ze}=await d();ce?await f(a$2.DEPLOY_FAILED,ce,Ze,{env:e$1.env,workspace:p?.slug,error_class:"ApplyError"}):await e(a$2.DEPLOY_FAILED,{env:e$1.env,workspace:p?.slug,error_class:"ApplyError"}),await j$1();return}let K=await P.json();n?.({type:"success",env:e$1.env,created:(K.created||[]).length,versioned:(K.versioned||[]).length,destroyed:(K.destroyed||[]).length,createdItems:K.created||[],versionedItems:K.versioned||[],destroyedItems:K.destroyed||[],skippedDestroyedItems:K.skippedDestroyed||[]});let{userId:O,tenantId:te}=await d();O?await f(a$2.DEPLOY_SUCCEEDED,O,te,{env:e$1.env,workspace:p.slug,created:N.created.length,versioned:N.versioned.length,destroyed:N.destroyed.length}):await e(a$2.DEPLOY_SUCCEEDED,{env:e$1.env,workspace:p.slug,created:N.created.length,versioned:N.versioned.length,destroyed:N.destroyed.length});}catch(E){n?.({type:"error",message:"Unexpected error",detail:E.message});let{userId:g,tenantId:C}=await d();g?await f(a$2.DEPLOY_FAILED,g,C,{env:e$1.env,workspace:p?.slug,error_class:E?.constructor?.name}):await e(a$2.DEPLOY_FAILED,{env:e$1.env,workspace:p?.slug,error_class:E?.constructor?.name}),await j$1();}});}function Mt(e$1){e$1.command("deploy").description("Deploy an agent").requiredOption("--env <env>","Environment (sandbox or prod)").option("--workspace-slug <slug>","Target workspace slug (overrides config)").option("--allow-destroy","Allow destructive changes").action(async t=>{if(Hn()){await Xn(t);return}await B(async n=>{t.env==="dev"&&(console.log("Use culvii dev for local iteration"),await j$1(),process.exit(1)),t.env!=="sandbox"&&t.env!=="prod"&&(console.error("Environment must be sandbox or prod"),await j$1(),process.exit(1));let{apiUrl:r$1,context:i}=await r({env:t.env}),s$1=s(i);if(!t.workspaceSlug){console.error("Error: --workspace-slug <slug> is required for deploy. Run `culvii workspace list` to see available workspaces.");let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEPLOY_FAILED,f$1,I,{error_class:"NoWorkspace",workspace:t.workspaceSlug}):await e(a$2.DEPLOY_FAILED,{error_class:"NoWorkspace",workspace:t.workspaceSlug}),await j$1(),process.exit(1);}let u=null,o=await j(`${r$1}/api/workspaces?tenantId=${i.tenant_id}`,n,{headers:s$1});if(!o.ok){console.error(`Failed to fetch workspaces: ${await Y(o)}`);let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEPLOY_FAILED,f$1,I,{env:t.env,error_class:"WorkspaceFetchError",workspace:t.workspaceSlug}):await e(a$2.DEPLOY_FAILED,{env:t.env,error_class:"WorkspaceFetchError",workspace:t.workspaceSlug}),await j$1(),process.exit(1);}let c=((await o.json())?.data?.workspaces||[]).find(f=>f.slug===t.workspaceSlug);if(!c){console.error("Workspace not found: "+t.workspaceSlug);let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEPLOY_FAILED,f$1,I,{env:t.env,workspace:t.workspaceSlug,error_class:"WorkspaceNotFound"}):await e(a$2.DEPLOY_FAILED,{env:t.env,workspace:t.workspaceSlug,error_class:"WorkspaceNotFound"}),await j$1(),process.exit(1);}u=c.id;let w$1=t.workspaceSlug;console.log(`tenant: ${i.tenant_slug} | workspace: ${w$1} | env: ${t.env}`);let p=process.cwd(),y$1=await Ft(p),k=(await Wt(y$1,{})).sort((f,I)=>+(I.type==="surface")-+(f.type==="surface")),A=[],v=new Set,D=new Set(k.filter(f=>f.type==="surface").map(f=>W(f.definition.id??"")).filter(Boolean)),$=async f$1=>{console.error(f$1);let{userId:I,tenantId:E}=await d();I?await f(a$2.DEPLOY_FAILED,I,E,{env:t.env,workspace:c?.slug,error_class:"ValidationError"}):await e(a$2.DEPLOY_FAILED,{env:t.env,workspace:c?.slug,error_class:"ValidationError"}),await j$1(),process.exit(1);};for(let f of k){let I=f.definition.id;I&&v.add(typeof I=="string"?W(I):String(I));}for(let f of k){let I=f.definition.id;I||(console.error(`Deploy failed: ${f.type} is missing an explicit id.`),await j$1(),process.exit(1));let E=typeof I=="string"?W(I):String(I);if(f.type==="surface"){let g=Pe(f.definition);g.length&&await $(`Deploy failed: surface '${E}' ${g.join("; ")}.`);}if(f.type==="agent"){for(let C of Ve(f.definition))await $(`Deploy failed: ${C}`);let g=f.definition.secondaryAgents||[];for(let C of g){let x=C.id,N=!!(C?.systemPrompt||C?.modelConfig);x&&!N&&!v.has(x)&&await $(`Deploy failed: agent '${E}' references secondary agent '${x}' which is not defined in this workspace. Define '${x}' before deploying.`);}for(let C of Te(f.definition))v.has(W(C))||await $(`Deploy failed: agent '${E}' references workflow '${C}' which is not defined in this workspace. Define '${C}' before deploying.`);}if(f.type==="workflow"){for(let g of ye(f.definition))v.has(W(g))||await $(`Deploy failed: workflow '${E}' references agent '${g}' which is not defined in this workspace. Define '${g}' before deploying.`);for(let g of Fe(f.definition))g.version===void 0&&!D.has(W(g.surfaceKey))&&await $(`Deploy failed: workflow '${E}' references local surface '${g.surfaceKey}' which is not defined. Pin a published version or define the surface.`);}A.push({type:f.type,slug:E,definition:f.definition,configHash:Pt(f.definition)});}let M=We(k);M&&await $(`Deploy failed: ${M}`);let S=je(k);S&&await $(`Deploy failed: ${S}`);let R=Me(k);R&&await $(`Deploy failed: ${R}`);let L=Ke(k);L&&await $(`Deploy failed: ${L}`);try{let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEPLOY_STARTED,f$1,I,{env:t.env,workspace:c.slug}):await e(a$2.DEPLOY_STARTED,{env:t.env,workspace:c.slug});let E=await j(`${r$1}/api/workspaces/${u}/deploys/plan`,n,{method:"POST",headers:{...s$1,"Content-Type":"application/json"},body:JSON.stringify({environment:t.env,definitions:A})});if(!E.ok){let O=await Y(E);console.error(`Error: Failed to plan deploy. ${O}`);let{userId:te,tenantId:z}=await d();te?await f(a$2.DEPLOY_FAILED,te,z,{env:t.env,workspace:c?.slug,error_class:"PlanError"}):await e(a$2.DEPLOY_FAILED,{env:t.env,workspace:c?.slug,error_class:"PlanError"}),await j$1(),process.exit(1);}let g=await E.json(),C=g.plan,x=g.planToken;(C.created||[]).length>0||(C.versioned||[]).length>0||(C.destroyed||[]).length>0||(console.log("Nothing to deploy. All resources are up to date."),await j$1(),process.exit(0)),console.log(`Plan for ${t.env}:`);for(let O of C.created||[])console.log(` + ${O.slug} CREATED`);for(let O of C.versioned||[])console.log(` ~ ${O.slug} VERSIONED (${Nt(O)})`);for(let O of C.destroyed||[])console.log(` - ${O.slug} DELETE CANDIDATE (${Nt(O)})`),O.renameHint&&console.log(`${y} Rename hint: ${O.renameHint.suggestedCommand}`);let G=await zn({env:t.env,allowDestroy:t.allowDestroy,destroyed:C.destroyed||[]});if(!await qn(`Deploy to ${t.env}? [y/N] `)){console.log("Deployment cancelled.");let{userId:O,tenantId:te}=await d();O?await f(a$2.DEPLOY_ABORTED,O,te,{env:t.env,workspace:c?.slug,reason:"user_cancelled"}):await e(a$2.DEPLOY_ABORTED,{env:t.env,workspace:c?.slug,reason:"user_cancelled"}),await j$1(),process.exit(0);}let pe=await j(`${r$1}/api/workspaces/${u}/deploys/apply`,n,{method:"POST",headers:{...s$1,"Content-Type":"application/json"},body:JSON.stringify({planToken:x,...G})});if(!pe.ok){let O=await Y(pe);console.error(`Error: Failed to apply deploy. ${O}`);let{userId:te,tenantId:z}=await d();te?await f(a$2.DEPLOY_FAILED,te,z,{env:t.env,workspace:c?.slug,error_class:"ApplyError"}):await e(a$2.DEPLOY_FAILED,{env:t.env,workspace:c?.slug,error_class:"ApplyError"}),await j$1(),process.exit(1);}let ee=await pe.json();console.log(`${w} Deployed to ${t.env}`),console.log(` Created: ${(ee.created||[]).length} resource(s)`);for(let O of ee.created||[])console.log(` + ${O.slug||O.referenceKey||O.id}`);console.log(` Versioned: ${(ee.versioned||[]).length} resource(s)`);for(let O of ee.versioned||[])console.log(` ~ ${O.slug||O.referenceKey||O.id}`);console.log(` Destroyed: ${(ee.destroyed||[]).length} resource(s)`);for(let O of ee.destroyed||[])console.log(` - ${O.slug||O.referenceKey||O.id}`);if((ee.skippedDestroyed||[]).length>0){console.log(` Skipped deletion: ${(ee.skippedDestroyed||[]).length} resource(s)`);for(let O of ee.skippedDestroyed||[])console.log(` k ${O.slug||O.referenceKey||O.id}`);}let{userId:P,tenantId:K}=await d();P?await f(a$2.DEPLOY_SUCCEEDED,P,K,{env:t.env,workspace:c.slug,created:C.created.length,versioned:C.versioned.length,destroyed:C.destroyed.length}):await e(a$2.DEPLOY_SUCCEEDED,{env:t.env,workspace:c.slug,created:C.created.length,versioned:C.versioned.length,destroyed:C.destroyed.length});}catch(f$1){console.error(`Error: Network or unexpected error: ${f$1.message}`);let{userId:I,tenantId:E}=await d();I?await f(a$2.DEPLOY_FAILED,I,E,{env:t.env,workspace:c?.slug,error_class:f$1?.constructor?.name}):await e(a$2.DEPLOY_FAILED,{env:t.env,workspace:c?.slug,error_class:f$1?.constructor?.name}),await j$1(),process.exit(1);}});});}function Zn(){let e=a$1();return e.isTTY&&!e.isCI&&e.supportsColor&&e.supportsUnicode}function jt(e$1){e$1.command("rename").description("Rename a resource").argument("<old-slug>","Current slug").argument("<new-slug>","New slug").requiredOption("--resource-type <type>","Type of resource (agent|workflow)").option("--env <env>","Target environment (sandbox or prod)").option("--workspace-slug <slug>","Target workspace slug (overrides config)").action(async(t,n,r$1)=>{if(Zn()){let o=function(){let[a,l]=ge.useState({type:"loading"});return ge.useEffect(()=>(u.current=l,()=>{u.current=null;}),[]),ge.createElement(s$1,{state:a})};let{RenameView:s$1}=await import('./RenameView-3BABATL6.js'),u={current:null};if(await V(Promise.resolve(ge.createElement(o))),!["agent","workflow"].includes(r$1.resourceType)){u.current?.({type:"error",message:"Invalid resource type",detail:`'${r$1.resourceType}' \u2014 must be one of: agent, workflow`}),await e(a$2.RENAME_FAILED,{error_class:"InvalidResourceType",resourceType:r$1.resourceType,env:r$1.env,workspace:r$1.workspaceSlug}),await j$1();return}await B(async a=>{let{apiUrl:l,context:c}=await r({env:r$1.env}),w=s(c),{userId:p,tenantId:y}=await d();p?await f(a$2.RENAME_STARTED,p,y,{resourceType:r$1.resourceType,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_STARTED,{resourceType:r$1.resourceType,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();let k=c.workspace_id;if(r$1.workspaceSlug){let A=await j(`${l}/api/workspaces?tenantId=${c.tenant_id}`,a,{headers:w});if(!A.ok){u.current?.({type:"error",message:"Failed to fetch workspaces",detail:await Y(A)}),p?await f(a$2.RENAME_FAILED,p,y,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceFetchError",env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceFetchError",env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();return}let D=((await A.json())?.data?.workspaces||[]).find($=>$.slug===r$1.workspaceSlug);if(!D){u.current?.({type:"error",message:`Workspace not found: ${r$1.workspaceSlug}`}),p?await f(a$2.RENAME_FAILED,p,y,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceNotFound",env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceNotFound",env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();return}k=D.id;}if(!k){u.current?.({type:"error",message:"No workspace configured",detail:"Run culvii dev first, or provide --workspace-slug <slug>."}),p?await f(a$2.RENAME_FAILED,p,y,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error_class:"NoWorkspace",env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error_class:"NoWorkspace",env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();return}try{let A=await j(`${l}/api/workspaces/${k}/resources/${t}/rename`,a,{method:"PATCH",headers:{...w,"Content-Type":"application/json"},body:JSON.stringify({newSlug:n,resourceType:r$1.resourceType})});if(!A.ok){let v=await Y(A);u.current?.({type:"error",message:"Failed to rename resource",detail:`Server responded with ${A.status}: ${v}`}),p?await f(a$2.RENAME_FAILED,p,y,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error:v,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error:v,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();return}u.current?.({type:"success",oldSlug:t,newSlug:n}),p?await f(a$2.RENAME_SUCCEEDED,p,y,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_SUCCEEDED,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();}catch(A){u.current?.({type:"error",message:"Unexpected error",detail:A.message}),p?await f(a$2.RENAME_FAILED,p,y,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error:A.message,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error:A.message,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();}});return}await B(async s$1=>{["agent","workflow"].includes(r$1.resourceType)||(console.error(`Error: Invalid resource type '${r$1.resourceType}'. Must be one of: agent, workflow`),await e(a$2.RENAME_FAILED,{error_class:"InvalidResourceType",resourceType:r$1.resourceType,env:r$1.env,workspace:r$1.workspaceSlug}),await j$1(),process.exit(1));let{apiUrl:u,context:o}=await r({env:r$1.env}),a=s(o),{userId:l,tenantId:c}=await d();l?await f(a$2.RENAME_STARTED,l,c,{resourceType:r$1.resourceType,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_STARTED,{resourceType:r$1.resourceType,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1(),console.log(`tenant: ${o.tenant_slug} | workspace: ${r$1.workspaceSlug||o.workspace_slug||"unknown"} | env: ${o.environment}`);let w$1=o.workspace_id;if(r$1.workspaceSlug){let p=await j(`${u}/api/workspaces?tenantId=${o.tenant_id}`,s$1,{headers:a});p.ok||(console.error(`Failed to fetch workspaces: ${await Y(p)}`),l?await f(a$2.RENAME_FAILED,l,c,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceFetchError",env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceFetchError",env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1(),process.exit(1));let A=((await p.json())?.data?.workspaces||[]).find(v=>v.slug===r$1.workspaceSlug);A||(console.error("Workspace not found: "+r$1.workspaceSlug),l?await f(a$2.RENAME_FAILED,l,c,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceNotFound",env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceNotFound",env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1(),process.exit(1)),w$1=A.id;}w$1||(console.error("Error: No workspace configured. Run culvii dev first, or provide --workspace-slug <slug>."),l?await f(a$2.RENAME_FAILED,l,c,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error_class:"NoWorkspace",env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error_class:"NoWorkspace",env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1(),process.exit(1));try{let p=await j(`${u}/api/workspaces/${w$1}/resources/${t}/rename`,s$1,{method:"PATCH",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify({newSlug:n,resourceType:r$1.resourceType})});if(!p.ok){let y=await Y(p);console.error(`Error: Failed to rename resource. Server responded with ${p.status}: ${y}`),l?await f(a$2.RENAME_FAILED,l,c,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error:y,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error:y,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1(),process.exit(1);}console.log(`${w} Renamed ${t} ${z} ${n}`),console.log(" Immutable ID preserved. All execution history retained."),l?await f(a$2.RENAME_SUCCEEDED,l,c,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_SUCCEEDED,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1();}catch(p){console.error(`Error: Network or unexpected error: ${p.message}`),l?await f(a$2.RENAME_FAILED,l,c,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error:p.message,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:t,newSlug:n,resourceType:r$1.resourceType,error:p.message,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1(),process.exit(1);}});});}async function Kt(e,t,n){let r=await j(`${t}/auth/me`,e,{skipEnvironmentHeader:true});if(!r.ok)return {ok:false,status:r.status,error:await Y(r)};let i=await r.json(),s=i?.user||i?.data?.user||i,u=i?.tenant||i?.data?.tenant||{},o=u?.slug||n.tenant_slug||"Unknown",a=u?.name||n.tenant_slug||"Unknown",l$1=Array.isArray(i?.tenants)?i.tenants.find(A=>A.id===u?.id):void 0,c=Array.isArray(l$1?.environments)?l$1.environments:[],w=n.environment||"dev",p=k[w],y=c.find(A=>A.slug===p),k$1=[];if(y){let A=await j(`${t}/auth/me`,e,{skipEnvironmentHeader:true,headers:{"x-environment-id":y.id}});if(A.ok){let v=await A.json(),D=v?.user||v?.data?.user||v;Array.isArray(v?.roles)?k$1=v.roles:Array.isArray(D?.roles)?k$1=D.roles:typeof D?.roles=="string"&&(k$1=[D.roles]);}}return {ok:true,email:s?.email||"Unknown",name:s?.name||"Unknown",tenant:o,tenantName:a,workspace:n.workspace_slug||null,env:w,envAccessible:!!y,accessibleEnvs:c.map(A=>l(A.slug)??A.slug),roles:k$1}}async function xe(e$1,t){let{userId:n,tenantId:r}=await d(),i=e$1?{error:true,...t}:t?{...t}:void 0;n?await f(a$2.WHOAMI_VIEWED,n,r,i):await e(a$2.WHOAMI_VIEWED,i),await j$1();}function Yt(e){e.command("whoami").description("Show current authenticated user context").option("--json","Output as JSON").option("--env <env>","Environment to report (dev, sandbox, or prod); overrides the active env").action(async t=>{let{getCapabilities:n}=await import('./terminalCapabilities-LJTRMVG4.js'),r=n();if(t.json||!r.isTTY||r.isCI||!r.supportsColor||!r.supportsUnicode){await Qn();return}await er();});}async function Qn(){await B(async e=>{let{apiUrl:t,context:n}=await r(),r$1=await Kt(e,t,n);r$1.ok||(process.stderr.write(JSON.stringify({error:r$1.error})+`
|
|
9
|
-
`),await
|
|
10
|
-
`),await
|
|
11
|
-
To switch, run: culvii switch <tenant-slug>`),process.exit(0)),!i[
|
|
12
|
-
Available tenants:`),
|
|
2
|
+
import {a as a$5}from'./chunk-JFIFRAAR.js';import {a as a$4,b as b$1,c as c$1}from'./chunk-KZG5CFSB.js';import {n,e,a as a$2,j as j$1,d,f,c,q,r,s,o,k,l}from'./chunk-LD5ISISS.js';import {a as a$3}from'./chunk-HX54IFSD.js';import'./chunk-57XLDHK6.js';import {x,w,y,z}from'./chunk-YKFGEPLO.js';import {a as a$1}from'./chunk-YPLDPHHD.js';import {a,b}from'./chunk-7UWDMECF.js';import {Command}from'commander';import he,{realpathSync,existsSync}from'fs';import {fileURLToPath}from'url';import ue from'react';import {render}from'ink';import Ze from'ws';import J,{dirname,join}from'path';import ee from'fs/promises';import {createHash}from'crypto';import {spawn}from'child_process';import mn from'chokidar';import {createRequire}from'module';import Pn from'readline';import ct from'os';import {createInterface}from'readline/promises';import {stdout,stdin}from'process';import {jsx}from'react/jsx-runtime';var It=a(F=>{Object.defineProperty(F,"__esModule",{value:true});F.SINGLE_CHILD_SURFACE_COMPONENTS=F.SURFACE_COMPONENT_TYPES=F.SURFACE_COMPONENT_CATALOG=F.SURFACE_SLOTS=F.SURFACE_SLOT_POLICY=void 0;F.getSurfaceBindingPaths=_t;F.validateSurfaceDefinition=At;F.validateSurfaceResource=pn;F.SURFACE_SLOT_POLICY={output:{actions:["navigate"],form:false},wait:{actions:["navigate","node.resume","node.stop"],form:true}};F.SURFACE_SLOTS=Object.keys(F.SURFACE_SLOT_POLICY);F.SURFACE_COMPONENT_CATALOG={Stack:{children:"list"},Row:{children:"list"},Grid:{children:"list"},Card:{children:"single"},Section:{children:"single"},Tabs:{children:"list"},Accordion:{children:"single"},Divider:{children:"none"},Spacer:{children:"none"},Text:{children:"none"},Heading:{children:"none"},Markdown:{children:"none"},Badge:{children:"none"},KeyValue:{children:"none"},Stat:{children:"none"},Avatar:{children:"none"},Icon:{children:"none"},Image:{children:"none"},Code:{children:"none"},Timestamp:{children:"none"},Duration:{children:"none"},Money:{children:"none"},Table:{children:"none"},List:{children:"list"},Tree:{children:"none"},JsonInspector:{children:"none"},FileChip:{children:"none",interaction:"single-action"},StatusPill:{children:"none"},ProgressBar:{children:"none"},Spinner:{children:"none"},ErrorPanel:{children:"none"},Timeline:{children:"list"},Button:{children:"none",interaction:"single-action"},TextField:{children:"none",interaction:"input"},TextArea:{children:"none",interaction:"input"},Select:{children:"none",interaction:"input"},Checkbox:{children:"none",interaction:"input"},RadioGroup:{children:"none",interaction:"input"},DatePicker:{children:"none",interaction:"input"},Form:{children:"list"},DiffView:{children:"none"},ApproveRejectBar:{children:"none",interaction:"multi-action"},EmailMessageCard:{children:"none"},SlackMessageCard:{children:"none"},SlackThread:{children:"list"},CalendarEventCard:{children:"none"},AgentRunPanel:{children:"none"},ToolCallCard:{children:"none"}};F.SURFACE_COMPONENT_TYPES=Object.keys(F.SURFACE_COMPONENT_CATALOG);F.SINGLE_CHILD_SURFACE_COMPONENTS=F.SURFACE_COMPONENT_TYPES.filter(t=>F.SURFACE_COMPONENT_CATALOG[t].children==="single");var ht=300,Et=12,on=new Set(F.SURFACE_COMPONENT_TYPES),cn=new Set(["$output","$input","$binary"]),ln=new Set(["text","number","date","datetime","json"]),dn=new Set(["text","textarea","number","email","url","checkbox","select","file"]);function un(t){return (t.startsWith("/")?t.slice(1):t).split("/",1)[0]}function De(t,e){if(Array.isArray(t))for(let n of t)De(n,e);else if(t&&typeof t=="object"){let n=t;if(typeof n.path=="string")e.push(n.path);else for(let r of Object.values(n))De(r,e);}}function Ce(t,e){if(Array.isArray(t)){for(let r of t)Ce(r,e);return}if(!t||typeof t!="object")return;let n=t;if("path"in n){typeof n.path!="string"&&e.push("Surface binding path must be a string."),n.format!==void 0&&!ln.has(String(n.format))&&e.push(`Unknown surface binding format "${String(n.format)}".`);return}for(let r of Object.values(n))Ce(r,e);}function _t(t){let e=[];for(let n of t.components??[])!n||typeof n!="object"||(De(n.props,e),De(n.actions,e));return De(t.form,e),Array.from(new Set(e))}function At(t,e){let n=[];try{new TextEncoder().encode(JSON.stringify(t)).byteLength>256*1024&&n.push("Surface definition exceeds 256 KiB.");}catch{return ["Surface definition must be JSON serializable."]}if(t?.schema!=="kit.ui/v1"&&n.push('Surface schema must be "kit.ui/v1".'),!Array.isArray(t?.components)||t.components.length===0)return [...n,"Surface requires at least one component."];t.components.length>ht&&n.push(`Surface cannot exceed ${ht} components.`);let r=new Map;for(let o of t.components){if(!o||typeof o!="object"||Array.isArray(o)){n.push("Every surface component must be an object.");continue}let s=o;if(typeof s.id!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(s.id)||typeof s.type!="string"){n.push("Every surface component requires id and type.");continue}r.has(s.id)&&n.push(`Duplicate component id "${s.id}".`),r.set(s.id,s),on.has(s.type)||n.push(`Unknown component type "${s.type}".`);let u=F.SURFACE_COMPONENT_CATALOG[s.type];s.props!==void 0&&(!s.props||typeof s.props!="object"||Array.isArray(s.props))&&n.push(`Component "${s.id}" props must be an object.`),s.children!==void 0&&!Array.isArray(s.children)?n.push(`Component "${s.id}" children must be an array.`):s.children?.length&&u?.children==="none"?n.push(`Component "${s.id}" cannot have children.`):s.children&&s.children.length>1&&u?.children==="single"&&n.push(`Component "${s.id}" can have at most one child.`);let c=s.props?.bind;if(c!==void 0&&(u?.interaction!=="input"?n.push(`Component "${s.id}" cannot bind form state.`):(!F.SURFACE_SLOT_POLICY[e].form||typeof c!="string"||!(c==="/$form"||c.startsWith("/$form/")||c.startsWith("$form.")))&&n.push(`Component "${s.id}" requires a wait-surface $form binding.`)),s.actions!==void 0&&(!s.actions||typeof s.actions!="object"||Array.isArray(s.actions))){n.push(`Component "${s.id}" actions must be an object.`);continue}let w=Object.keys(s.actions??{}).length;w&&!["single-action","multi-action"].includes(u?.interaction??"")?n.push(`Component "${s.id}" cannot have actions.`):w>1&&u?.interaction==="single-action"&&n.push(`Component "${s.id}" can have at most one action.`),Ce(s.props,n);for(let p of Object.values(s.actions??{})){if(!p||typeof p!="object"||Array.isArray(p)){n.push(`Component "${s.id}" has an invalid action.`);continue}let y=p;if(!["navigate","node.resume","node.stop"].includes(y.type)){n.push(`Unknown surface action "${String(y.type)}".`);continue}F.SURFACE_SLOT_POLICY[e].actions.includes(y.type)||n.push(`Action "${y.type}" is not allowed on "${e}" surfaces.`),y.type==="navigate"&&(!y.href||typeof y.href!="object"||typeof y.href.path!="string")&&n.push("Navigate actions require an href binding."),Ce(y,n);}}(typeof t.root!="string"||!r.has(t.root))&&n.push(`Surface root "${String(t.root)}" is missing.`);let i=new Set,a=new Set,d=(o,s)=>{if(s>Et)return void n.push(`Surface component depth exceeds ${Et}.`);if(a.has(o))return void n.push(`Surface component cycle includes "${o}".`);if(i.has(o))return;let u=r.get(o);if(u){a.add(o);for(let c of Array.isArray(u.children)?u.children:[]){if(typeof c!="string"){n.push(`Component "${o}" has a non-string child reference.`);continue}r.has(c)?d(c,s+1):n.push(`Component "${o}" references missing child "${c}".`);}a.delete(o),i.add(o);}};typeof t.root=="string"&&d(t.root,1);for(let o of r.keys())i.has(o)||n.push(`Component "${o}" is unreachable from root.`);for(let o of _t(t)){let s=un(o);s==="$form"&&!F.SURFACE_SLOT_POLICY[e].form?n.push(`Binding "${o}" is only allowed on wait surfaces.`):s!=="$form"&&!cn.has(s)&&n.push(`Invalid surface binding path "${o}".`);}if(t.form!==void 0)if(F.SURFACE_SLOT_POLICY[e].form||n.push("Forms are only allowed on wait surfaces."),!Array.isArray(t.form?.fields))n.push("Surface form fields must be an array.");else {let o=new Set;for(let s of t.form.fields){if(!s||typeof s!="object"||Array.isArray(s)){n.push("Every surface form field must be an object.");continue}let u=s,c=u?.name,w=u?.type;typeof c!="string"||!c||o.has(c)?n.push(`Surface form field name "${String(c)}" is invalid or duplicated.`):o.add(c),dn.has(String(w))||n.push(`Unknown surface form field type "${String(w)}".`),(typeof u.label!="string"||!u.label.trim())&&n.push(`Surface form field "${String(c)}" requires a label.`),w==="file"&&"default"in u&&n.push(`File field "${String(c)}" cannot have a default binding.`),w==="file"&&(u.maxFiles!==void 0&&(!Number.isInteger(u.maxFiles)||Number(u.maxFiles)<1||Number(u.maxFiles)>5)&&n.push(`File field "${String(c)}" maxFiles must be between 1 and 5.`),u.maxBytes!==void 0&&(!Number.isInteger(u.maxBytes)||Number(u.maxBytes)<1||Number(u.maxBytes)>10*1024*1024)&&n.push(`File field "${String(c)}" maxBytes exceeds platform limits.`),u.accept!==void 0&&(!Array.isArray(u.accept)||u.accept.some(p=>typeof p!="string"||!/^[a-z0-9.+-]+\/(?:[a-z0-9.+-]+|\*)$/i.test(p)))&&n.push(`File field "${String(c)}" has invalid MIME types.`)),w==="select"&&(!Array.isArray(u.options)||u.options.length===0?n.push(`Select field "${String(c)}" requires options.`):u.options.some(p=>!p||typeof p!="object"||typeof p.label!="string"||typeof p.value!="string")&&n.push(`Select field "${String(c)}" has invalid options.`));}Ce(t.form,n);}return Array.from(new Set(n))}function pn(t){let e=t;if(!e||typeof e!="object")return ["Surface must be an object."];let n=[];return (typeof e.id!="string"||!/^[a-z0-9][a-z0-9-]{0,62}$/.test(e.id))&&n.push("Surface requires a kebab-case id."),(typeof e.name!="string"||!e.name.trim())&&n.push("Surface requires a name."),F.SURFACE_SLOTS.includes(e.slot)?n.push(...At(e.definition,e.slot)):n.push(`Surface requires slot ${F.SURFACE_SLOTS.map(r=>`"${r}"`).join(" or ")}.`),Array.from(new Set(n))}});var Tt=a(ve=>{var fn=ve&&ve.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:true,get:function(){return e[n]}}),Object.defineProperty(t,r,i);}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n];})),gn=ve&&ve.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&fn(e,t,n);};Object.defineProperty(ve,"__esModule",{value:true});gn(It(),ve);});var Oe=class extends Error{constructor(){super("401 Unauthorized"),this.name="UnauthorizedError";}};function sn(t,e=Date.now()){return t-e<3e4}async function H(t){let e$1=new a$4,r=await(async()=>await e$1.withLock(async()=>{b$1.info("Tokens read from disk for auth check");let i=await e$1.get();if(i||(b$1.error("No tokens found on disk"),render(ue.createElement(c$1,{state:{type:"login_error",message:"Not logged in",detail:"run `culvii login`"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1)),!sn(i.expiresAt))return b$1.info("Access token valid, skipping refresh"),i.accessToken;b$1.info("Access token expired, attempting refresh");let a=`https://${q.cognitoDomain}/oauth2/token`,d=new URLSearchParams;d.set("grant_type","refresh_token"),d.set("refresh_token",i.refreshToken),d.set("client_id",q.clientId);let o;try{o=await fetch(a,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:d.toString()});}catch(w){b$1.error("Network error during refresh",{error:w.message}),render(ue.createElement(c$1,{state:{type:"login_error",message:"Refresh failed",detail:"Cannot reach auth server \u2014 check your connection"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1);}let s=await o.json();(!o.ok||s.error==="invalid_grant")&&(b$1.warn("Refresh failed with invalid_grant"),await e$1.delete(),render(ue.createElement(c$1,{state:{type:"login_error",message:"Session expired",detail:"run `culvii login` to authenticate"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1));let u=Date.now(),c=u+s.expires_in*1e3;return b$1.info("Refresh succeeded",{expiresAt:c}),await e$1.set({accessToken:s.access_token,refreshToken:s.refresh_token||i.refreshToken,idToken:s.id_token||i.idToken,expiresAt:c,tokenType:"Bearer",scope:i.scope,issuedAt:u,issuer:i.issuer}),s.access_token}))();try{await t(r);}catch(i){if(!(i instanceof Oe))throw i;b$1.info("Mid-session 401 detected, attempting refresh");let a=await e$1.withLock(async()=>{b$1.info("Tokens read from disk for retry");let d=await e$1.get();d||(b$1.error("No tokens found on disk during retry"),render(ue.createElement(c$1,{state:{type:"login_error",message:"Not logged in",detail:"run `culvii login`"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1)),b$1.info("Access token expired (forced by 401), attempting refresh");let o=`https://${q.cognitoDomain}/oauth2/token`,s=new URLSearchParams;s.set("grant_type","refresh_token"),s.set("refresh_token",d.refreshToken),s.set("client_id",q.clientId);let u;try{u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()});}catch(y){b$1.error("Network error during refresh retry",{error:y.message}),render(ue.createElement(c$1,{state:{type:"login_error",message:"Refresh failed",detail:"Cannot reach auth server \u2014 check your connection"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1);}let c=await u.json();(!u.ok||c.error==="invalid_grant")&&(b$1.warn("Refresh retry failed with invalid_grant"),await e$1.delete(),render(ue.createElement(c$1,{state:{type:"login_error",message:"Session expired",detail:"run `culvii login` to authenticate"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1));let w=Date.now(),p=w+c.expires_in*1e3;return b$1.info("Refresh retry succeeded",{expiresAt:p}),await e$1.set({accessToken:c.access_token,refreshToken:c.refresh_token||d.refreshToken,idToken:c.id_token||d.idToken,expiresAt:p,tokenType:"Bearer",scope:d.scope,issuedAt:w,issuer:d.issuer}),c.access_token});try{b$1.info("Retry after refresh succeeded"),await t(a);}catch(d){throw d instanceof Oe&&(b$1.error("Retry after refresh failed (still 401)"),await e$1.withLock(async()=>{await e$1.delete();}),render(ue.createElement(c$1,{state:{type:"login_error",message:"Session invalidated",detail:"run `culvii login` to authenticate"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1)),d}}}async function Xe(){let t=new a$4;return t.withLock(async()=>{let e=await t.get();if(!e)return null;let n=`https://${q.cognitoDomain}/oauth2/token`,r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",e.refreshToken),r.set("client_id",q.clientId);let i;try{i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(s){return b$1.error("Network error during silent refresh",{error:s.message}),null}let a=await i.json();if(!i.ok||a.error==="invalid_grant")return b$1.warn("Silent refresh failed",{error:a.error}),null;let d=Date.now(),o=d+a.expires_in*1e3;return await t.set({accessToken:a.access_token,refreshToken:a.refresh_token||e.refreshToken,idToken:a.id_token||e.idToken,expiresAt:o,tokenType:"Bearer",scope:e.scope,issuedAt:d,issuer:e.issuer}),a.access_token})}async function K(t){let e=await t.text();try{let n=JSON.parse(e);if(n.error)return n.error}catch{}return e}async function j(t,e,n={}){let{skipEnvironmentHeader:r,...i}=n,d=await new a$3().read({exitOnError:false}),o$1=d.contexts[d.active],s=o$1?.tenant_id,u=o$1?.environment||"dev",c=o()??u,w=o$1?.environment_ids?.[c]??(c===u?o$1?.environment_id:void 0),p=k[c],y=r?{}:w?{"x-environment-id":w}:{"x-environment-slug":p},k$1={Authorization:`Bearer ${e}`,...s?{"x-tenant-id":s}:{},...y,...i.headers||{}};return fetch(t,{...i,headers:k$1})}function vt(){let t=a$1();return t.isTTY&&!t.isCI&&t.supportsColor&&t.supportsUnicode}function kt(t){let e$1=t.command("workspace").description("Workspace commands").option("--env <env>","Target environment (sandbox or prod)");e$1.command("create").description("Create a new workspace").requiredOption("--name <name>","Workspace name").requiredOption("--slug <slug>","Workspace slug").action(async n=>{if(vt()){let d$1=function(){let[o,s]=ue.useState({type:"loading"});return ue.useEffect(()=>(a=s,()=>{a=null;}),[]),ue.createElement(i,{state:o})};let{WorkspaceCreateView:i}=await import('./WorkspaceView-RNFALIPM.js'),a=null;await V(Promise.resolve(ue.createElement(d$1))),await H(async o=>{let{apiUrl:s$1,context:u}=await r({env:e$1.opts().env}),c=s(u);try{let w=await j(`${s$1}/api/workspaces`,o,{method:"POST",headers:{...c,"Content-Type":"application/json"},body:JSON.stringify({name:n.name,slug:n.slug,tenantId:u.tenant_id})});if(!w.ok){let A=await K(w);a?.({type:"error",message:"Failed to create workspace",detail:`Server responded with ${w.status}: ${A}`});let{userId:h,tenantId:R}=await d();h?await f(a$2.WORKSPACE_CREATE_FAILED,h,R,{error_class:"ApiError",slug:n.slug,env:u.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:"ApiError",slug:n.slug,env:u.environment}),await j$1();return}let p=await w.json();a?.({type:"success",id:p?.data?.workspaceId,slug:p?.data?.workspaceSlug||n.slug,name:n.name});let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_CREATED,y,k,{slug:n.slug,env:u.environment}):await e(a$2.WORKSPACE_CREATED,{slug:n.slug,env:u.environment}),await j$1();}catch(w){a?.({type:"error",message:"Unexpected error",detail:w.message});let{userId:p,tenantId:y}=await d();p?await f(a$2.WORKSPACE_CREATE_FAILED,p,y,{error_class:w?.constructor?.name,env:u.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:w?.constructor?.name,env:u.environment}),await j$1();}});return}await H(async i=>{let{apiUrl:a,context:d$1}=await r({env:e$1.opts().env}),o=s(d$1);console.log(`tenant: ${d$1.tenant_slug} | workspace: N/A | env: ${d$1.environment}`);try{let s=await j(`${a}/api/workspaces`,i,{method:"POST",headers:{...o,"Content-Type":"application/json"},body:JSON.stringify({name:n.name,slug:n.slug,tenantId:d$1.tenant_id})});if(!s.ok){let p=await K(s);console.error(`Error: Failed to create workspace. Server responded with ${s.status}: ${p}`);let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_CREATE_FAILED,y,k,{error_class:"ApiError",slug:n.slug,env:d$1.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:"ApiError",slug:n.slug,env:d$1.environment}),await j$1(),process.exit(1);}let u=await s.json();console.log(`${w} Workspace created successfully.`),console.log(` ID: ${u?.data?.workspaceId}`),u?.data?.workspaceSlug&&console.log(` Slug: ${u?.data?.workspaceSlug}`);let{userId:c,tenantId:w$1}=await d();c?await f(a$2.WORKSPACE_CREATED,c,w$1,{slug:n.slug,env:d$1.environment}):await e(a$2.WORKSPACE_CREATED,{slug:n.slug,env:d$1.environment}),await j$1();}catch(s){console.error(`Error: Network or unexpected error: ${s.message}`);let{userId:u,tenantId:c}=await d();u?await f(a$2.WORKSPACE_CREATE_FAILED,u,c,{error_class:s?.constructor?.name,env:d$1.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:s?.constructor?.name,env:d$1.environment}),await j$1(),process.exit(1);}});}),e$1.command("list").description("List workspaces").action(async()=>{if(vt()){let a=function(){let[d,o]=ue.useState({type:"loading"});return ue.useEffect(()=>(i=o,()=>{i=null;}),[]),ue.createElement(r$1,{state:d})};let{WorkspaceListView:r$1}=await import('./WorkspaceView-RNFALIPM.js'),i=null;await V(Promise.resolve(ue.createElement(a))),await H(async d$1=>{let{apiUrl:o,context:s$1}=await r({env:e$1.opts().env}),u=s(s$1);try{let c=await j(`${o}/api/workspaces?tenantId=${s$1.tenant_id}`,d$1,{headers:u});if(!c.ok){let A=await K(c);i?.({type:"error",message:"Failed to list workspaces",detail:`Server responded with ${c.status}: ${A}`});let{userId:h,tenantId:R}=await d();h?await f(a$2.WORKSPACE_LIST_FAILED,h,R,{error_class:"ApiError",env:s$1.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"ApiError",env:s$1.environment}),await j$1();return}let p=(await c.json())?.data?.workspaces;if(!Array.isArray(p)){i?.({type:"error",message:"Unexpected response format"});let{userId:A,tenantId:h}=await d();A?await f(a$2.WORKSPACE_LIST_FAILED,A,h,{error_class:"UnexpectedResponse",env:s$1.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"UnexpectedResponse",env:s$1.environment}),await j$1();return}i?.({type:"success",workspaces:p.map(A=>({id:A.id,name:A.name,slug:A.slug??""}))});let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_LISTED,y,k,{env:s$1.environment}):await e(a$2.WORKSPACE_LISTED,{env:s$1.environment}),await j$1();}catch(c){i?.({type:"error",message:"Unexpected error",detail:c.message});let{userId:w,tenantId:p}=await d();w?await f(a$2.WORKSPACE_LIST_FAILED,w,p,{error_class:c?.constructor?.name,env:s$1.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:c?.constructor?.name,env:s$1.environment}),await j$1();}});return}await H(async r$1=>{let{apiUrl:i,context:a}=await r({env:e$1.opts().env}),d$1=s(a);console.log(`tenant: ${a.tenant_slug} | workspace: N/A | env: ${a.environment}`);try{let o=await j(`${i}/api/workspaces?tenantId=${a.tenant_id}`,r$1,{headers:d$1});if(!o.ok){let p=await K(o);console.error(`Error: Failed to list workspaces. Server responded with ${o.status}: ${p}`);let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_LIST_FAILED,y,k,{error_class:"ApiError",env:a.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"ApiError",env:a.environment}),await j$1(),process.exit(1);}let u=(await o.json())?.data?.workspaces;if(!Array.isArray(u)){console.error("Error: Unexpected response format");let{userId:p,tenantId:y}=await d();p?await f(a$2.WORKSPACE_LIST_FAILED,p,y,{error_class:"UnexpectedResponse",env:a.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"UnexpectedResponse",env:a.environment}),await j$1(),process.exit(1);}for(let p of u)console.log(`${p.id} ${p.name} ${p.slug}`);let{userId:c,tenantId:w}=await d();c?await f(a$2.WORKSPACE_LISTED,c,w,{env:a.environment}):await e(a$2.WORKSPACE_LISTED,{env:a.environment}),await j$1();}catch(o){console.error(`Error: Network or unexpected error: ${o.message}`);let{userId:s,tenantId:u}=await d();s?await f(a$2.WORKSPACE_LIST_FAILED,s,u,{error_class:o?.constructor?.name,env:a.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:o?.constructor?.name,env:a.environment}),await j$1(),process.exit(1);}});});}function Qe(t,e,n){let r=null,i=0,a=false,d=[],o=new Map,s=null,u=null,c=0,w=[1e3,2e3,4e3,8e3,16e3];function p(){s&&(clearInterval(s),s=null),u&&(clearTimeout(u),u=null),c=0;}function y(){p(),s=setInterval(()=>{if(!r||r.readyState!==Ze.OPEN)return;let D=Date.now().toString()+"-"+Math.random().toString();r.send(JSON.stringify({type:"client-ping",requestId:D})),u=setTimeout(()=>{c++,c>=2&&(b$1.warn("devSync WebSocket dead (missed 2 pongs), terminating"),p(),r?.terminate());},5e3);},2e4);}function k(D){D.removeAllListeners(),D.on("error",()=>{});try{D.terminate();}catch($){b$1.warn("devSync error terminating stale socket",{error:$.message});}}let A=0;async function h(){if(a)return;let D=++A,$;try{$=await e();}catch(I){b$1.error("devSync failed to obtain headers for connection",{error:I.message}),D===A&&R();return}if(a||D!==A)return;r&&k(r);let f=new Ze(t,{headers:$});r=f,f.on("open",()=>{if(r===f){i=0,b$1.info("devSync WebSocket connected",{url:t}),n.onOpen();for(let I of d)f.send(JSON.stringify(I));d=[],y();}}),f.on("message",I=>{if(r!==f)return;let E=Buffer.isBuffer(I)?I.toString("utf-8"):I instanceof ArrayBuffer?Buffer.from(I).toString("utf-8"):Buffer.concat(I).toString("utf-8"),g;try{g=JSON.parse(E);}catch{b$1.warn("Received invalid JSON from devSync",{raw:E});return}if(g.ok===true&&g.slug&&typeof g.warning=="string"){n.onWarning?.(g.slug,g.warning);return}if(g.type==="session-probe"&&typeof g.requestId=="string"){f.send(JSON.stringify({type:"session-pong",requestId:g.requestId}));return}if(g.type==="client-pong"){u&&(clearTimeout(u),u=null),c=0;return}if(g.ok===true&&g.slug&&g.type==="validation-error"){n.onValidationErrorAck?.(g.slug);return}if(g.ok===true&&g.slug){g.resourceId&&o.set(g.slug,g.resourceId),n.onAck(g.slug,g.resourceId,g.orphaned===true);return}if(g.ok===false&&g.slug){n.onError(g.slug,g.error||"Unknown error");return}if(g.ok===false&&!g.slug){n.onFatal(g.error||"Fatal error from server"),a=true,p(),f.close();return}}),f.on("unexpected-response",(I,E)=>{if(r===f){if(E.statusCode===401){b$1.error("devSync credentials rejected (401)"),a=true,p(),f.terminate(),n.onAuthFailure?n.onAuthFailure():n.onFatal("Credentials rejected by server (401)");return}b$1.warn("devSync unexpected handshake response",{statusCode:E.statusCode}),p(),f.terminate(),R();}}),f.on("close",I=>{r!==f||a||(b$1.warn("devSync WebSocket closed",{code:I}),p(),R());}),f.on("error",I=>{r===f&&b$1.error("devSync WebSocket error",{error:I.message});});}function R(){if(p(),a)return;if(i>=w.length){let f=`devSync PERMANENT FAILURE: giving up after ${w.length} retries`;b$1.error(f,{retryCount:i,retryDelaysMs:w}),n.onFatal(f),a=true;return}let D=w[i];i++;let $=w.length-i;b$1.info(`devSync reconnecting in ${D}ms (attempt ${i}/${w.length}, ${$} left before permanent failure)`),setTimeout(()=>{h();},D);}function O(D){r&&r.readyState===Ze.OPEN?r.send(JSON.stringify(D)):d.push(D);}function M(){a=true,p(),r&&k(r),b$1.info("devSync WebSocket closed by client");}function S(){a||(p(),i=0,r&&k(r),h());}return h(),{send:O,close:M,reconnectNow:S}}var Dt=b(Tt(),1);var _n=fileURLToPath(import.meta.url),An=dirname(_n),In=join(An,"lib","evaluator.js"),Tn=createRequire(import.meta.url),Sn=Tn.resolve("tsx/cli");function be(t){return (0, Dt.validateSurfaceResource)(t)}function tt(t){if(Array.isArray(t))return t.map(tt);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=tt(t[n]);return e}return t}function Dn(t){if(!t||typeof t!="object")return t;let e={...t};return Array.isArray(e.nodes)&&(e.nodes=e.nodes.map(({id:n,...r})=>r)),e}function Cn(t){return createHash("sha256").update(JSON.stringify(tt(Dn(t)))).digest("hex")}function pe(t){return (Array.isArray(t?.nodes)?t.nodes:[]).filter(n=>n?.type==="core.agent").map(n=>n?.nodeParams?.agentReferenceKey??n?.nodeParams?.agentId).filter(n=>typeof n=="string"&&!n.startsWith("agt_"))}function Ne(t){return (Array.isArray(t?.nodes)?t.nodes:[]).flatMap(n=>["output","wait"].map(r=>n?.ui?.[r]).filter(r=>r?.kind==="custom"&&typeof r.surfaceKey=="string").map(r=>({surfaceKey:r.surfaceKey,...Number.isInteger(r.version)?{version:r.version}:{}})))}function Rn(t){return Array.isArray(t)?t:t&&typeof t=="object"?Object.entries(t).map(([e,n])=>n&&typeof n=="object"&&!Array.isArray(n)?{name:e,...n}:n):[]}function Ae(t){return Rn(t?.tools).filter(e=>e&&typeof e=="object"&&!Array.isArray(e)).map(e=>({referenceKey:e.workflowReferenceKey??e.workflowId,toolName:e.name,triggerNodeName:e.triggerNodeName})).filter(e=>typeof e.referenceKey=="string"&&!e.referenceKey.startsWith("wfl_"))}function Ie(t){return Ae(t).map(e=>e.referenceKey)}function xn(t){return typeof t?.type=="string"&&t.type!=="manualTrigger"&&t.type.endsWith("Trigger")}function Ln(t,e){return t.get(e)??t.get(W(e))}function Ct(t){let e=new Set,n=[];for(let r of t.values())e.has(r.id)||(e.add(r.id),n.push(r));return n}function Rt(t,e){let n=typeof t?.id=="string"?t.id:"unknown";if(Ae(t).length>0)return {id:n,definition:t};let r=n==="unknown"?void 0:Ln(e,n);return r?{id:n,definition:r.definition}:t&&typeof t=="object"&&!Array.isArray(t)?{id:n,definition:t}:null}function nt(t,e){let n=[t];for(let r of t.definition?.secondaryAgents??[]){let i=Rt(r,e);i&&n.push(i);}return n}function Ue(t){let e=new Map,n=new Map;for(let a of t){let d=a.definition?.id;typeof d=="string"&&(a.type==="agent"?(e.set(d,{id:d,definition:a.definition}),e.set(W(d),{id:d,definition:a.definition})):a.type==="workflow"&&(n.set(d,a.definition),n.set(W(d),a.definition)));}let r=new Set;for(let a of Ct(e))for(let d of nt(a,e))for(let o of Ie(d.definition))r.add(W(o));let i=new Set;for(let a of r){let d=n.get(a);if(d)for(let o of pe(d))i.add(W(o));}for(let a of i){let d=e.get(a);if(d){if(Ae(d.definition).length>0)return `agent '${d.id}' cannot define workflow tools when invoked by an agent workflow tool.`;for(let o of d.definition?.secondaryAgents??[]){let s=Rt(o,e);if(s&&Ae(s.definition).length>0)return `secondary agent '${s.id}' referenced by agent '${d.id}' cannot define workflow tools when '${d.id}' is invoked by an agent workflow tool.`}}}return null}function Pe(t){let e=new Map,n=new Map;for(let i of t){let a=i.definition?.id;typeof a=="string"&&(i.type==="agent"?(e.set(a,{id:a,definition:i.definition}),e.set(W(a),{id:a,definition:i.definition})):i.type==="workflow"&&(n.set(a,i.definition),n.set(W(a),i.definition)));}let r=new Set;for(let i of n.values())for(let a of pe(i))r.add(W(a));for(let i of r){let a=e.get(i);if(!a)continue;let d=nt(a,e);for(let o of d)for(let s of Ae(o.definition)){let u=n.get(s.referenceKey)??n.get(W(s.referenceKey));if(!(!u||pe(u).length===0))return `workflow tool '${s.toolName??"unknown"}' on agent '${o.id}' cannot reference workflow '${s.referenceKey}' because '${a.id}' is invoked by a workflow and the target workflow contains an agent node.`}}return null}function Fe(t){let e=new Map,n=new Map;for(let r of t){let i=r.definition?.id;typeof i=="string"&&(r.type==="agent"?(e.set(i,{id:i,definition:r.definition}),e.set(W(i),{id:i,definition:r.definition})):r.type==="workflow"&&(n.set(i,r.definition),n.set(W(i),r.definition)));}for(let r of Ct(e))for(let i of nt(r,e))for(let a of Ae(i.definition)){let d=n.get(a.referenceKey)??n.get(W(a.referenceKey));if(!d)continue;let o=Array.isArray(d.nodes)?d.nodes:[],s=o.find(xn);if(s)return `workflow tool '${a.toolName??"unknown"}' on agent '${i.id}' references workflow '${a.referenceKey}' with non-manual trigger '${s.name??s.type}'.`;if(a.triggerNodeName){if(o.find(w=>w?.name===a.triggerNodeName)?.type==="manualTrigger")continue;return `workflow tool '${a.toolName??"unknown"}' on agent '${i.id}' must use a manual trigger in workflow '${a.referenceKey}'.`}let u=o.filter(c=>c?.type==="manualTrigger");if(u.length!==1)return u.length===0?`workflow tool '${a.toolName??"unknown"}' on agent '${i.id}' references workflow '${a.referenceKey}' without a manual trigger.`:`workflow tool '${a.toolName??"unknown"}' on agent '${i.id}' must specify triggerNodeName because workflow '${a.referenceKey}' has multiple manual triggers.`}return null}function We(t){let e=[],n=(r,i)=>{let a=i&&typeof i=="object"&&!Array.isArray(i)?i.credentialId:void 0;(typeof a!="string"||!a.trim())&&e.push(`agent '${r}' model must include a credentialId \u2014 use model: { provider, modelId, credentialId }.`);};t?.modelConfig!==void 0&&t?.modelConfig!==null&&n(t?.id,t.modelConfig);for(let r of t?.secondaryAgents??[])r?.modelConfig!==void 0&&r?.modelConfig!==null&&n(r?.id??t?.id,r.modelConfig);return e}function Me(t){let e=new Map;for(let i of t){let a=i.definition?.id;if(!a)continue;let d=i.type==="agent"?Ie(i.definition).map(o=>`workflow:${o}`):i.type==="workflow"?pe(i.definition).map(o=>`agent:${o}`):[];e.set(`${i.type}:${a}`,d);}let n=null;function r(i,a){if(!n)for(let d of e.get(i)??[]){if(!e.has(d))continue;let o=[...a,d];if(a.length>=3){n=`Unsupported nested SDK reference chain: ${o.join(" -> ")}. Only workflow -> agent -> workflow or agent -> workflow -> agent is supported.`;return}r(d,o);}}for(let i of e.keys())r(i,[i]);return n}async function $n(t){try{let r=J.join(t,"culvii.yaml"),a=(await ee.readFile(r,"utf-8")).split(`
|
|
3
|
+
`),d=[],o=!1;for(let s of a){if(s.trim().startsWith("entrypoints:")){o=!0;continue}if(o){let u=s.match(/^\s+-\s+(.+)$/);u?d.push(J.resolve(t,u[1].trim())):s.trim()&&!s.trim().startsWith("#")&&(o=!1);}}if(d.length>0)return b$1.info("Using entrypoints from culvii.yaml",{count:d.length}),d}catch{}let e=[];async function n(r){let i;try{i=await ee.readdir(r,{withFileTypes:!0});}catch{return}for(let a of i){if(a.name==="node_modules"||a.name==="dist"||a.name===".git")continue;let d=J.join(r,a.name);a.isDirectory()?await n(d):a.isFile()&&a.name.endsWith(".culvii.ts")&&e.push(d);}}return await n(t),b$1.info("Found .culvii.ts entrypoints",{count:e.length}),e}function On(t,e){return new Promise((n,r)=>{if(t.length===0){n([]);return}let i=spawn(process.execPath,[Sn,In,...t],{env:{...process.env,...e,CULVII_DEV:"true"},stdio:["ignore","pipe","pipe"]}),a="",d="";i.stdout.on("data",o=>{a+=o.toString();}),i.stderr.on("data",o=>{d+=o.toString();}),i.on("close",o=>{if(d.trim()&&b$1.warn("Evaluator stderr",{stderr:d.trim()}),o!==0){r(new Error(`Evaluator exited with code ${o}. ${d.trim()||"Check your files for syntax errors."}`));return}let s=a.split(`
|
|
4
|
+
`).filter(w=>w.includes("__culvii_dev_definitions__"));if(s.length===0){n([]);return}let u=[],c=new Set;for(let w of s)try{let p=JSON.parse(w);for(let y of p.__culvii_dev_definitions__||[]){let k=y?.definition?.id,A=y?.type&&k?`${y.type}:${k}`:null;if(A){if(c.has(A))continue;c.add(A);}u.push(y);}}catch{b$1.warn("Failed to parse evaluator output",{line:w});}n(u);});})}function W(t){return t.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-").slice(0,63)}function rt(t){let e=process.cwd(),n=new Map,r=null,i=false,a=false,d=false;async function o(){if(i){a=true;return}i=true;try{d&&(d=!1,n.clear()),await u();}catch(p){b$1.error("Evaluation failed",{error:p.message});}finally{i=false,a&&(a=false,o());}}function s(p,y,k){t.onLog?t.onLog(y,k):(k==="error"?process.stderr:process.stdout).write(`${p} ${y}
|
|
5
|
+
`);}async function u(){let p=await $n(e),y$1;try{y$1=await On(p,{});}catch(g){s(x,`Evaluation failed, skipping this sync cycle: ${g.message}`,"error");return}let k=new Map,A=new Set,h=new Set(y$1.map(g=>g.definition.id).filter(Boolean)),R=new Set(y$1.filter(g=>g.type==="surface").flatMap(g=>{let C=g.definition.id;return typeof C=="string"?[C,W(C)]:[]})),O=false,M=false;for(let g of y$1){let C=g.definition.id;if(!C){s(y,`Skipping ${g.type}: referenced resources require an explicit id.`,"warn");continue}let L=typeof C=="string"?W(C):String(C);if(!L){s(y,`Skipping definition: could not derive a valid slug from "${C}". Add an explicit id field.`,"warn");continue}if(g.type==="surface"){let P=be(g.definition);if(P.length){s(x,`Invalid surface '${L}': ${P.join("; ")}.`,"error");return}}let N=`${g.type}:${L}`;if(A.has(N)){s(x,`Duplicate slug '${L}' detected in ${g.type}s. Fix all collisions before syncing.`,"error");return}A.add(N);let G=Cn(g.definition);k.set(N,{slug:L,type:g.type,definition:g.definition,hash:G});let X=g.type==="agent"?Ie(g.definition):[],se=g.type==="workflow"?pe(g.definition):[],le=g.type==="workflow"?Ne(g.definition):[];if(g.type==="agent"){for(let P of We(g.definition))s(x,P,"error"),M=true;for(let P of g.definition.secondaryAgents||[]){let x$1=P?.id,te=!!(P?.systemPrompt||P?.modelConfig);if(typeof x$1=="string"&&!te&&!h.has(x$1)){let z=`Dangling ref: agent '${L}' references secondary agent '${x$1}' which is not defined locally.`;s(x,z,"error"),O=true,t.onValidationError?.({resourceType:"agent",slug:L,missingReferenceId:x$1,message:z});}}}for(let P of X)if(!h.has(P)){let x$1=`Dangling ref: agent '${L}' references workflow '${P}' which is not defined locally.`;s(x,x$1,"error"),O=true,t.onValidationError?.({resourceType:"agent",slug:L,missingReferenceId:P,message:x$1});}for(let P of se)if(!h.has(P)){let x$1=`Dangling ref: workflow '${L}' references agent '${P}' which is not defined locally.`;s(x,x$1,"error"),O=true,t.onValidationError?.({resourceType:"workflow",slug:L,missingReferenceId:P,message:x$1});}for(let P of le)if(P.version===void 0&&!R.has(P.surfaceKey)){let x$1=`Dangling ref: workflow '${L}' references local surface '${P.surfaceKey}' which is not defined locally. Pin a published version or define the surface.`;s(x,x$1,"error"),O=true,t.onValidationError?.({resourceType:"workflow",slug:L,missingReferenceId:P.surfaceKey,message:x$1});}}if(O){s(x,"Fix all dangling references before syncing.","error");return}if(M){s(x,"Fix the model configuration before syncing.","error");return}let S=Ue(y$1);if(S){s(x,S,"error"),s(x,"Fix the secondary agent tools before syncing.","error");return}let D=Fe(y$1);if(D){s(x,D,"error"),s(x,"Fix the workflow tool trigger before syncing.","error");return}let $=Pe(y$1);if($){s(x,$,"error"),s(x,"Fix the workflow tool target before syncing.","error");return}let f=Me(y$1);if(f){s(x,f,"error"),s(x,"Fix the reference chain before syncing.","error");return}let I=0;for(let[g,{hash:C,type:L}]of n.entries())if(!k.has(g)){let N=g.slice(g.indexOf(":")+1),G=L==="agent"?[...k.values()].find(X=>X.hash===C&&X.type===L):void 0;G?s(y,`Looks like '${N}' was renamed to '${G.slug}'.
|
|
6
|
+
Run: culvii rename ${N} ${G.slug} --resource-type ${L}`,"warn"):(t.onOrphan(N,L),n.delete(g),I++);}let E=[...k.entries()].sort(([,g],[,C])=>+(C.type==="surface")-+(g.type==="surface"));for(let[g,{slug:C,type:L,definition:N,hash:G}]of E){let X=n.get(g);(!X||X.hash!==G)&&(n.set(g,{hash:G,type:L}),t.onSync({type:L,slug:C,definition:N,configHash:G}),I++);}I===0&&s(z,"No changes to sync.","info");}let c=mn.watch(e,{ignored:p=>p.includes("node_modules")||p.includes("/dist/")||p.includes("/.git/"),ignoreInitial:true,persistent:true});c.on("all",(p,y)=>{y.endsWith(".ts")&&(r&&clearTimeout(r),r=setTimeout(()=>{o();},500));});let w=false;return {close:()=>c.close(),triggerFullSync:()=>{if(w){o();return}if(w=true,i){d=true,a=true;return}n.clear(),o();}}}function bn(){let t=a$1();return t.isTTY&&!t.isCI&&t.supportsColor&&t.supportsUnicode}var Nn="https://console.culvii.com/";function Te(t,e){return `${Nn}${t}/development/${e}/workflows`}function xt(){let t=new Date,e=n=>String(n).padStart(2,"0");return `${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}`}async function Un(){let{DevView:t}=await import('./DevView-GPKSSOLA.js'),e$1=null;function n(){let[r,i]=ue.useState({type:"provisioning",message:"Starting dev server\u2026"});return ue.useEffect(()=>(e$1=i,()=>{e$1=null;}),[]),ue.createElement(t,{state:r})}await V(Promise.resolve(ue.createElement(n))),await H(async r$1=>{let i=new a$3,a=await i.read({exitOnError:!1}),d$1=Date.now();if(!a.active||!a.contexts[a.active]){e$1?.({type:"error",message:"No active context. Run culvii login first."});let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEV_FAILED,f$1,I,{error_class:"NoActiveContext",workspace:s$1?.workspace_slug,env:s$1?.environment}):await e(a$2.DEV_FAILED,{error_class:"NoActiveContext",workspace:s$1?.workspace_slug,env:s$1?.environment}),await j$1();return}let{apiUrl:o,context:s$1}=await r({env:"dev"}),u=s(s$1),c=s$1.workspace_id,w=s$1.workspace_slug;e$1?.({type:"provisioning",message:"Provisioning dev workspace\u2026"});try{let f$1=await j(`${o}/api/workspaces`,r$1,{method:"POST",headers:{...u,"Content-Type":"application/json"},body:JSON.stringify({name:`dev-${s$1.user_id.slice(0,12)}`,slug:`dev-${s$1.user_id.slice(0,12)}`,tenantId:s$1.tenant_id})});if(!f$1.ok){let E=await K(f$1);e$1?.({type:"error",message:`Failed to auto-provision workspace: ${E}`});let{userId:g,tenantId:C}=await d();g?await f(a$2.DEV_FAILED,g,C,{error_class:"WorkspaceProvisionError",workspace:s$1?.workspace_slug,env:s$1?.environment}):await e(a$2.DEV_FAILED,{error_class:"WorkspaceProvisionError",workspace:s$1?.workspace_slug,env:s$1?.environment}),await j$1();return}let I=await f$1.json();await i.withLock(async()=>{a=await i.read();let E=a.contexts[a.active];E.workspace_ids={...E.workspace_ids||{},dev:I?.data?.workspaceId},E.workspace_slugs={...E.workspace_slugs||{},dev:I?.data?.workspaceSlug},E.workspace_id=I?.data?.workspaceId,E.workspace_slug=I?.data?.workspaceSlug,await i.write(a);}),s$1={...a.contexts[a.active],environment:"dev"},c=s$1.workspace_id,w=s$1.workspace_slug;}catch(f$1){e$1?.({type:"error",message:`Failed to auto-provision workspace: ${f$1.message}`});let{userId:I,tenantId:E}=await d();I?await f(a$2.DEV_FAILED,I,E,{error_class:f$1?.constructor?.name,workspace:s$1?.workspace_slug,env:s$1?.environment}):await e(a$2.DEV_FAILED,{error_class:f$1?.constructor?.name,workspace:s$1?.workspace_slug,env:s$1?.environment}),await j$1();return}let{userId:p,tenantId:y}=await d();p?await f(a$2.DEV_STARTED,p,y,{workspace:s$1.workspace_slug,env:s$1.environment}):await e(a$2.DEV_STARTED,{workspace:s$1.workspace_slug,env:s$1.environment});let k=[];function A(f){return {Authorization:`Bearer ${f}`,...u}}let h=r$1;async function R(){let f=await Xe();return f&&(h=f),A(h)}let O=o.replace(/^http/,"ws")+"/api/dev/sync?workspaceId="+encodeURIComponent(c),M,S=Qe(O,R,{onOpen:()=>{e$1?.({type:"connected",log:[...k],consoleUrl:Te(s$1.tenant_slug,c)}),M?.triggerFullSync();},onAck:(f,I,E)=>{let g={type:E?"orphaned":"synced",message:`${E?"orphaned":"synced"} ${f}`,timestamp:xt()};k.push(g),e$1?.({type:"connected",log:[...k],consoleUrl:Te(s$1.tenant_slug,c)});},onValidationErrorAck:()=>{},onWarning:(f,I)=>{let E={type:"warning",message:I};k.push(E),e$1?.({type:"connected",log:[...k],consoleUrl:Te(s$1.tenant_slug,c)});},onError:(f,I)=>{let E={type:"error",message:`Sync failed for ${f}: ${I}`};k.push(E),e$1?.({type:"connected",log:[...k],consoleUrl:Te(s$1.tenant_slug,c)});},onFatal:async f$1=>{clearInterval($);let I=`Fatal error: ${f$1}. Shutting down...`;e$1?.({type:"error",message:I});let{userId:E,tenantId:g}=await d();E?await f(a$2.DEV_FAILED,E,g,{error_class:"FatalWebSocketError",workspace:s$1.workspace_slug,workspace:s$1?.workspace_slug,env:s$1?.environment}):await e(a$2.DEV_FAILED,{error_class:"FatalWebSocketError",workspace:s$1.workspace_slug,workspace:s$1?.workspace_slug,env:s$1?.environment}),M?.close(),S?.close(),ke(1,I);},onAuthFailure:async()=>{clearInterval($);let f$1="Your session was rejected by the server. Run `culvii login` to re-authenticate. Shutting down...";e$1?.({type:"error",message:f$1});let{userId:I,tenantId:E}=await d();I?await f(a$2.DEV_FAILED,I,E,{error_class:"ApiKeyRejected",workspace:s$1.workspace_slug,workspace:s$1?.workspace_slug,env:s$1?.environment}):await e(a$2.DEV_FAILED,{error_class:"ApiKeyRejected",workspace:s$1.workspace_slug,workspace:s$1?.workspace_slug,env:s$1?.environment}),M?.close(),S?.close(),ke(1,f$1);}});M=rt({workspaceId:c,onSync:f=>{S.send({type:"sync",slug:f.slug,resourceType:f.type,definition:f.definition,workspaceId:c});},onOrphan:(f,I)=>{S.send({type:"orphan",slug:f,resourceType:I,workspaceId:c});},onValidationError:({resourceType:f,slug:I,missingReferenceId:E,message:g})=>{S.send({type:"validation-error",slug:I,resourceType:f,workspaceId:c,missingReferenceId:E,message:g});},onLog:(f,I)=>{let E={type:I==="error"?"error":I==="warn"?"warning":"info",message:f};k.push(E),e$1?.({type:"connected",log:[...k],consoleUrl:Te(s$1.tenant_slug,c)});}});let D=3e3*1e3,$=setInterval(()=>{S.reconnectNow();},D);process.on("SIGINT",async()=>{clearInterval($),S.close(),M.close(),e$1?.({type:"disconnected"});let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEV_STOPPED,f$1,I,{duration_ms:Date.now()-d$1,workspace:s$1.workspace_slug,env:s$1.environment}):await e(a$2.DEV_STOPPED,{duration_ms:Date.now()-d$1,workspace:s$1.workspace_slug,env:s$1.environment}),await j$1(),process.exit(0);});});}function Lt(t){t.command("dev").description("Start the development server and file watcher").action(async()=>{if(bn()){await Un();return}await H(async e$1=>{let n=new a$3,r$1=await n.read({exitOnError:!1});if(!r$1.active||!r$1.contexts[r$1.active]){console.error("No active context. Run culvii login first.");let{userId:S,tenantId:D}=await d();S?await f(a$2.DEV_FAILED,S,D,{error_class:"NoActiveContext",workspace:a?.workspace_slug,env:a?.environment}):await e(a$2.DEV_FAILED,{error_class:"NoActiveContext",workspace:a?.workspace_slug,env:a?.environment}),await j$1(),process.exit(1);}let{apiUrl:i,context:a}=await r({env:"dev"}),d$1=s(a),o=Date.now(),s$1=a.workspace_id,u=a.workspace_slug;try{let S=await j(`${i}/api/workspaces`,e$1,{method:"POST",headers:{...d$1,"Content-Type":"application/json"},body:JSON.stringify({name:`dev-${a.user_id.slice(0,12)}`,slug:`dev-${a.user_id.slice(0,12)}`,tenantId:a.tenant_id})});if(!S.ok){let $=await K(S);console.error(`Failed to auto-provision workspace: ${$}`);let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEV_FAILED,f$1,I,{error_class:"WorkspaceProvisionError",workspace:a.workspace_slug,workspace:a?.workspace_slug,env:a?.environment}):await e(a$2.DEV_FAILED,{error_class:"WorkspaceProvisionError",workspace:a.workspace_slug,workspace:a?.workspace_slug,env:a?.environment}),await j$1(),process.exit(1);}let D=await S.json();await n.withLock(async()=>{r$1=await n.read();let $=r$1.contexts[r$1.active];$.workspace_ids={...$.workspace_ids||{},dev:D?.data?.workspaceId},$.workspace_slugs={...$.workspace_slugs||{},dev:D?.data?.workspaceSlug},$.workspace_id=D?.data?.workspaceId,$.workspace_slug=D?.data?.workspaceSlug,await n.write(r$1);}),a={...r$1.contexts[r$1.active],environment:"dev"},s$1=a.workspace_id,u=a.workspace_slug;}catch(S){console.error(`Failed to auto-provision workspace: ${S.message}`);let{userId:D,tenantId:$}=await d();D?await f(a$2.DEV_FAILED,D,$,{error_class:S?.constructor?.name,workspace:a.workspace_slug,workspace:a?.workspace_slug,env:a?.environment}):await e(a$2.DEV_FAILED,{error_class:S?.constructor?.name,workspace:a.workspace_slug,workspace:a?.workspace_slug,env:a?.environment}),await j$1(),process.exit(1);}console.log(`tenant: ${a.tenant_slug} | workspace: ${u||"unknown"} | env: dev`);let{userId:c,tenantId:w$1}=await d();c?await f(a$2.DEV_STARTED,c,w$1,{workspace:a.workspace_slug,env:a.environment}):await e(a$2.DEV_STARTED,{workspace:a.workspace_slug,env:a.environment});function p(S){return {Authorization:`Bearer ${S}`,...d$1}}let y$1=e$1;async function k(){let S=await Xe();return S&&(y$1=S),p(y$1)}let A=i.replace(/^http/,"ws")+"/api/dev/sync?workspaceId="+encodeURIComponent(s$1),h,R=Qe(A,k,{onOpen:()=>{console.log("Watching ./..."),console.log(`You can access your dev session here: ${Te(a.tenant_slug,s$1)}`),h?.triggerFullSync();},onAck:(S,D,$)=>{let f=xt();console.log($?`${w} [${f}] orphaned ${S}`:`${w} [${f}] synced ${S}`);},onValidationErrorAck:()=>{},onWarning:(S,D)=>{console.log(`${y} ${D}`);},onError:(S,D)=>{console.log(`${y} Sync failed for ${S}: ${D}`);},onFatal:async S=>{clearInterval(M),console.error(`Fatal error: ${S}. Shutting down...`);let{userId:D,tenantId:$}=await d();D?await f(a$2.DEV_FAILED,D,$,{error_class:"FatalWebSocketError",workspace:a.workspace_slug,workspace:a?.workspace_slug,env:a?.environment}):await e(a$2.DEV_FAILED,{error_class:"FatalWebSocketError",workspace:a.workspace_slug,workspace:a?.workspace_slug,env:a?.environment}),await j$1(),h?.close(),R?.close(),process.exit(1);},onAuthFailure:async()=>{clearInterval(M),console.error(`${x} Your session was rejected by the server. Run \`culvii login\` to re-authenticate. Shutting down...`);let{userId:S,tenantId:D}=await d();S?await f(a$2.DEV_FAILED,S,D,{error_class:"ApiKeyRejected",workspace:a.workspace_slug,workspace:a?.workspace_slug,env:a?.environment}):await e(a$2.DEV_FAILED,{error_class:"ApiKeyRejected",workspace:a.workspace_slug,workspace:a?.workspace_slug,env:a?.environment}),await j$1(),h?.close(),R?.close(),process.exit(1);}});h=rt({workspaceId:s$1,onSync:S=>{let D={type:"sync",slug:S.slug,resourceType:S.type,definition:S.definition,workspaceId:s$1};R.send(D);},onOrphan:(S,D)=>{let $={type:"orphan",slug:S,resourceType:D,workspaceId:s$1};R.send($);},onValidationError:({resourceType:S,slug:D,missingReferenceId:$,message:f})=>{let I={type:"validation-error",slug:D,resourceType:S,workspaceId:s$1,missingReferenceId:$,message:f};R.send(I);}});let O=3e3*1e3,M=setInterval(()=>{R.reconnectNow();},O);process.on("SIGINT",async()=>{clearInterval(M),R.close(),h.close(),console.log("Disconnected. Draft state discarded.");let{userId:S,tenantId:D}=await d();S?await f(a$2.DEV_STOPPED,S,D,{duration_ms:Date.now()-o,workspace:a.workspace_slug,env:a.environment}):await e(a$2.DEV_STOPPED,{duration_ms:Date.now()-o,workspace:a.workspace_slug,env:a.environment}),await j$1(),process.exit(0);});});});}function Yn(){let t=a$1();return t.isTTY&&!t.isCI&&t.supportsColor&&t.supportsUnicode}function st(t){if(Array.isArray(t))return t.map(st);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=st(t[n]);return e}return t}function Hn(t){if(!t||typeof t!="object")return t;let e={...t};return Array.isArray(e.nodes)&&(e.nodes=e.nodes.map(({id:n,...r})=>r)),e}function bt(t){return createHash("sha256").update(JSON.stringify(st(Hn(t)))).digest("hex")}async function Nt(t){try{let r=J.join(t,"culvii.yaml"),a=(await ee.readFile(r,"utf-8")).split(`
|
|
7
|
+
`),d=[],o=!1;for(let s of a){if(s.trim().startsWith("entrypoints:")){o=!0;continue}if(o){let u=s.match(/^\s+-\s+(.+)$/);u?d.push(J.resolve(t,u[1].trim())):s.trim()&&!s.trim().startsWith("#")&&(o=!1);}}if(d.length>0)return d}catch{}let e=[];async function n(r){let i;try{i=await ee.readdir(r,{withFileTypes:!0});}catch{return}for(let a of i){if(a.name==="node_modules"||a.name==="dist"||a.name===".git")continue;let d=J.join(r,a.name);a.isDirectory()?await n(d):a.isFile()&&a.name.endsWith(".culvii.ts")&&e.push(d);}}return await n(t),e}function Ut(t,e){return new Promise(n=>{if(t.length===0){n([]);return}let r=fileURLToPath(import.meta.url),i=dirname(r),a=join(i,"lib","evaluator.js"),o=createRequire(import.meta.url).resolve("tsx/cli"),s=spawn(process.execPath,[o,a,...t],{env:{...process.env,...e,CULVII_DEV:"true"},stdio:["ignore","pipe","pipe"]}),u="",c="";s.stdout.on("data",w=>{u+=w.toString();}),s.stderr.on("data",w=>{c+=w.toString();}),s.on("close",()=>{let w=u.split(`
|
|
8
|
+
`).filter(k=>k.includes("__culvii_dev_definitions__")),p=[],y=new Set;for(let k of w)try{let A=JSON.parse(k);for(let h of A.__culvii_dev_definitions__||[]){let R=h?.definition?.id,O=h?.type&&R?`${h.type}:${R}`:null;if(O){if(y.has(O))continue;y.add(O);}p.push(h);}}catch{}n(p);});})}function qn(t){return new Promise(e=>{let n=Pn.createInterface({input:process.stdin,output:process.stdout});n.question(t,r=>{n.close(),e(r.toLowerCase()==="y"||r.toLowerCase()==="yes");});})}function Bn(t){let e=t.versionCount??1,n=t.activeVersion??t.previousVersion;return ` - ${t.slug}: deletes all ${e} ${e===1?"version":"versions"}${n?`; active is v${n}`:""}`}function Ot(t){let e=t.executions??0,n=t.activeExecutions??0,r=t.activeVersion??t.previousVersion;return `${e} total, active${r?` v${r}`:""}: ${n} executions`}async function Gn(t){let{DeployView:e$1}=await import('./DeployView-I4Y55LV4.js'),n=null,r$1=null;function i(){let[a,d]=ue.useState({type:"planning"});return ue.useEffect(()=>(n=d,()=>{n=null;}),[]),ue.createElement(e$1,{state:a,onConfirm:o=>r$1?.(o)})}await V(Promise.resolve(ue.createElement(i))),await H(async a=>{if(t.env==="dev"){n?.({type:"error",message:"Use culvii dev for local iteration"}),await j$1();return}if(t.env!=="sandbox"&&t.env!=="prod"){n?.({type:"error",message:"Environment must be sandbox or prod"}),await j$1();return}let{apiUrl:d$1,context:o}=await r({env:t.env}),s$1=s(o);if(!t.workspaceSlug){n?.({type:"error",message:"--workspace-slug <slug> is required for deploy",detail:"Run `culvii workspace list` to see available workspaces."});let{userId:E,tenantId:g}=await d();E?await f(a$2.DEPLOY_FAILED,E,g,{error_class:"NoWorkspace",workspace:t.workspaceSlug}):await e(a$2.DEPLOY_FAILED,{error_class:"NoWorkspace",workspace:t.workspaceSlug}),await j$1();return}let u=await j(`${d$1}/api/workspaces?tenantId=${o.tenant_id}`,a,{headers:s$1});if(!u.ok){n?.({type:"error",message:"Failed to fetch workspaces",detail:await K(u)});let{userId:E,tenantId:g}=await d();E?await f(a$2.DEPLOY_FAILED,E,g,{env:t.env,error_class:"WorkspaceFetchError",workspace:t.workspaceSlug}):await e(a$2.DEPLOY_FAILED,{env:t.env,error_class:"WorkspaceFetchError",workspace:t.workspaceSlug}),await j$1();return}let p=((await u.json())?.data?.workspaces||[]).find(E=>E.slug===t.workspaceSlug);if(!p){n?.({type:"error",message:`Workspace not found: ${t.workspaceSlug}`});let{userId:E,tenantId:g}=await d();E?await f(a$2.DEPLOY_FAILED,E,g,{env:t.env,workspace:t.workspaceSlug,error_class:"WorkspaceNotFound"}):await e(a$2.DEPLOY_FAILED,{env:t.env,workspace:t.workspaceSlug,error_class:"WorkspaceNotFound"}),await j$1();return}let y=p.id,k=process.cwd(),A=await Nt(k),h=(await Ut(A,{})).sort((E,g)=>+(g.type==="surface")-+(E.type==="surface")),R=[],O=new Set,M=new Set(h.filter(E=>E.type==="surface").map(E=>W(E.definition.id??"")).filter(Boolean)),S=async E=>{n?.({type:"error",message:E});let{userId:g,tenantId:C}=await d();g?await f(a$2.DEPLOY_FAILED,g,C,{env:t.env,workspace:p?.slug,error_class:"ValidationError"}):await e(a$2.DEPLOY_FAILED,{env:t.env,workspace:p?.slug,error_class:"ValidationError"}),await j$1();};for(let E of h){let g=E.definition.id;g&&O.add(typeof g=="string"?W(g):String(g));}for(let E of h){let g=E.definition.id;if(!g){n?.({type:"error",message:`Deploy failed: ${E.type} is missing an explicit id.`}),await j$1();return}let C=typeof g=="string"?W(g):String(g);if(E.type==="surface"){let L=be(E.definition);if(L.length)return S(`Deploy failed: surface '${C}' ${L.join("; ")}.`)}if(E.type==="agent"){for(let N of We(E.definition))return S(`Deploy failed: ${N}`);let L=E.definition.secondaryAgents||[];for(let N of L){let G=N.id,X=!!(N?.systemPrompt||N?.modelConfig);if(G&&!X&&!O.has(G))return S(`Deploy failed: agent '${C}' references secondary agent '${G}' which is not defined.`)}for(let N of Ie(E.definition))if(!O.has(W(N)))return S(`Deploy failed: agent '${C}' references workflow '${N}' which is not defined.`)}if(E.type==="workflow"){for(let L of pe(E.definition))if(!O.has(W(L)))return S(`Deploy failed: workflow '${C}' references agent '${L}' which is not defined.`);for(let L of Ne(E.definition))if(L.version===void 0&&!M.has(W(L.surfaceKey)))return S(`Deploy failed: workflow '${C}' references local surface '${L.surfaceKey}' which is not defined. Pin a published version or define the surface.`)}R.push({type:E.type,slug:C,definition:E.definition,configHash:bt(E.definition)});}let D=Ue(h);if(D)return S(`Deploy failed: ${D}`);let $=Fe(h);if($)return S(`Deploy failed: ${$}`);let f$1=Pe(h);if(f$1)return S(`Deploy failed: ${f$1}`);let I=Me(h);if(I)return S(`Deploy failed: ${I}`);try{let{userId:E,tenantId:g}=await d();E?await f(a$2.DEPLOY_STARTED,E,g,{env:t.env,workspace:p.slug}):await e(a$2.DEPLOY_STARTED,{env:t.env,workspace:p.slug});let C=await j(`${d$1}/api/workspaces/${y}/deploys/plan`,a,{method:"POST",headers:{...s$1,"Content-Type":"application/json"},body:JSON.stringify({environment:t.env,definitions:R})});if(!C.ok){let z=await K(C);n?.({type:"error",message:"Failed to plan deploy",detail:z});let{userId:fe,tenantId:Je}=await d();fe?await f(a$2.DEPLOY_FAILED,fe,Je,{env:t.env,workspace:p?.slug,error_class:"PlanError"}):await e(a$2.DEPLOY_FAILED,{env:t.env,workspace:p?.slug,error_class:"PlanError"}),await j$1();return}let L=await C.json(),N=L.plan,G=L.planToken;if(!((N.created||[]).length>0||(N.versioned||[]).length>0||(N.destroyed||[]).length>0)){n?.({type:"no_changes"}),await j$1();return}if(!await new Promise(z=>{r$1=z,n?.({type:"confirming",plan:{created:N.created||[],versioned:N.versioned||[],destroyed:N.destroyed||[]},env:t.env});})){n?.({type:"aborted",reason:"user_cancelled"});let{userId:z,tenantId:fe}=await d();z?await f(a$2.DEPLOY_ABORTED,z,fe,{env:t.env,workspace:p?.slug,reason:"user_cancelled"}):await e(a$2.DEPLOY_ABORTED,{env:t.env,workspace:p?.slug,reason:"user_cancelled"}),await j$1();return}n?.({type:"applying"});let le=await j(`${d$1}/api/workspaces/${y}/deploys/apply`,a,{method:"POST",headers:{...s$1,"Content-Type":"application/json"},body:JSON.stringify({planToken:G})});if(!le.ok){let z=await K(le);n?.({type:"error",message:"Failed to apply deploy",detail:z});let{userId:fe,tenantId:Je}=await d();fe?await f(a$2.DEPLOY_FAILED,fe,Je,{env:t.env,workspace:p?.slug,error_class:"ApplyError"}):await e(a$2.DEPLOY_FAILED,{env:t.env,workspace:p?.slug,error_class:"ApplyError"}),await j$1();return}let P=await le.json();n?.({type:"success",env:t.env,created:(P.created||[]).length,versioned:(P.versioned||[]).length,destroyed:(P.destroyed||[]).length,createdItems:P.created||[],versionedItems:P.versioned||[],destroyedItems:P.destroyed||[]});let{userId:x,tenantId:te}=await d();x?await f(a$2.DEPLOY_SUCCEEDED,x,te,{env:t.env,workspace:p.slug,created:N.created.length,versioned:N.versioned.length,destroyed:N.destroyed.length}):await e(a$2.DEPLOY_SUCCEEDED,{env:t.env,workspace:p.slug,created:N.created.length,versioned:N.versioned.length,destroyed:N.destroyed.length});}catch(E){n?.({type:"error",message:"Unexpected error",detail:E.message});let{userId:g,tenantId:C}=await d();g?await f(a$2.DEPLOY_FAILED,g,C,{env:t.env,workspace:p?.slug,error_class:E?.constructor?.name}):await e(a$2.DEPLOY_FAILED,{env:t.env,workspace:p?.slug,error_class:E?.constructor?.name}),await j$1();}});}function Pt(t){t.command("deploy").description("Deploy an agent").requiredOption("--env <env>","Environment (sandbox or prod)").option("--workspace-slug <slug>","Target workspace slug (overrides config)").action(async e$1=>{if(Yn()){await Gn(e$1);return}await H(async n=>{e$1.env==="dev"&&(console.log("Use culvii dev for local iteration"),await j$1(),process.exit(1)),e$1.env!=="sandbox"&&e$1.env!=="prod"&&(console.error("Environment must be sandbox or prod"),await j$1(),process.exit(1));let{apiUrl:r$1,context:i}=await r({env:e$1.env}),a=s(i);if(!e$1.workspaceSlug){console.error("Error: --workspace-slug <slug> is required for deploy. Run `culvii workspace list` to see available workspaces.");let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEPLOY_FAILED,f$1,I,{error_class:"NoWorkspace",workspace:e$1.workspaceSlug}):await e(a$2.DEPLOY_FAILED,{error_class:"NoWorkspace",workspace:e$1.workspaceSlug}),await j$1(),process.exit(1);}let d$1=null,o=await j(`${r$1}/api/workspaces?tenantId=${i.tenant_id}`,n,{headers:a});if(!o.ok){console.error(`Failed to fetch workspaces: ${await K(o)}`);let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEPLOY_FAILED,f$1,I,{env:e$1.env,error_class:"WorkspaceFetchError",workspace:e$1.workspaceSlug}):await e(a$2.DEPLOY_FAILED,{env:e$1.env,error_class:"WorkspaceFetchError",workspace:e$1.workspaceSlug}),await j$1(),process.exit(1);}let c=((await o.json())?.data?.workspaces||[]).find(f=>f.slug===e$1.workspaceSlug);if(!c){console.error("Workspace not found: "+e$1.workspaceSlug);let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEPLOY_FAILED,f$1,I,{env:e$1.env,workspace:e$1.workspaceSlug,error_class:"WorkspaceNotFound"}):await e(a$2.DEPLOY_FAILED,{env:e$1.env,workspace:e$1.workspaceSlug,error_class:"WorkspaceNotFound"}),await j$1(),process.exit(1);}d$1=c.id;let w$1=e$1.workspaceSlug;console.log(`tenant: ${i.tenant_slug} | workspace: ${w$1} | env: ${e$1.env}`);let p=process.cwd(),y=await Nt(p),k=(await Ut(y,{})).sort((f,I)=>+(I.type==="surface")-+(f.type==="surface")),A=[],h=new Set,R=new Set(k.filter(f=>f.type==="surface").map(f=>W(f.definition.id??"")).filter(Boolean)),O=async f$1=>{console.error(f$1);let{userId:I,tenantId:E}=await d();I?await f(a$2.DEPLOY_FAILED,I,E,{env:e$1.env,workspace:c?.slug,error_class:"ValidationError"}):await e(a$2.DEPLOY_FAILED,{env:e$1.env,workspace:c?.slug,error_class:"ValidationError"}),await j$1(),process.exit(1);};for(let f of k){let I=f.definition.id;I&&h.add(typeof I=="string"?W(I):String(I));}for(let f of k){let I=f.definition.id;I||(console.error(`Deploy failed: ${f.type} is missing an explicit id.`),await j$1(),process.exit(1));let E=typeof I=="string"?W(I):String(I);if(f.type==="surface"){let g=be(f.definition);g.length&&await O(`Deploy failed: surface '${E}' ${g.join("; ")}.`);}if(f.type==="agent"){for(let C of We(f.definition))await O(`Deploy failed: ${C}`);let g=f.definition.secondaryAgents||[];for(let C of g){let L=C.id,N=!!(C?.systemPrompt||C?.modelConfig);L&&!N&&!h.has(L)&&await O(`Deploy failed: agent '${E}' references secondary agent '${L}' which is not defined in this workspace. Define '${L}' before deploying.`);}for(let C of Ie(f.definition))h.has(W(C))||await O(`Deploy failed: agent '${E}' references workflow '${C}' which is not defined in this workspace. Define '${C}' before deploying.`);}if(f.type==="workflow"){for(let g of pe(f.definition))h.has(W(g))||await O(`Deploy failed: workflow '${E}' references agent '${g}' which is not defined in this workspace. Define '${g}' before deploying.`);for(let g of Ne(f.definition))g.version===void 0&&!R.has(W(g.surfaceKey))&&await O(`Deploy failed: workflow '${E}' references local surface '${g.surfaceKey}' which is not defined. Pin a published version or define the surface.`);}A.push({type:f.type,slug:E,definition:f.definition,configHash:bt(f.definition)});}let M=Ue(k);M&&await O(`Deploy failed: ${M}`);let S=Fe(k);S&&await O(`Deploy failed: ${S}`);let D=Pe(k);D&&await O(`Deploy failed: ${D}`);let $=Me(k);$&&await O(`Deploy failed: ${$}`);try{let{userId:f$1,tenantId:I}=await d();f$1?await f(a$2.DEPLOY_STARTED,f$1,I,{env:e$1.env,workspace:c.slug}):await e(a$2.DEPLOY_STARTED,{env:e$1.env,workspace:c.slug});let E=await j(`${r$1}/api/workspaces/${d$1}/deploys/plan`,n,{method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify({environment:e$1.env,definitions:A})});if(!E.ok){let x=await K(E);console.error(`Error: Failed to plan deploy. ${x}`);let{userId:te,tenantId:z}=await d();te?await f(a$2.DEPLOY_FAILED,te,z,{env:e$1.env,workspace:c?.slug,error_class:"PlanError"}):await e(a$2.DEPLOY_FAILED,{env:e$1.env,workspace:c?.slug,error_class:"PlanError"}),await j$1(),process.exit(1);}let g=await E.json(),C=g.plan,L=g.planToken;(C.created||[]).length>0||(C.versioned||[]).length>0||(C.destroyed||[]).length>0||(console.log("Nothing to deploy. All resources are up to date."),await j$1(),process.exit(0)),console.log(`Plan for ${e$1.env}:`);for(let x of C.created||[])console.log(` + ${x.slug} CREATED`);for(let x of C.versioned||[])console.log(` ~ ${x.slug} VERSIONED (${Ot(x)})`);for(let x of C.destroyed||[])console.log(` - ${x.slug} DELETE (${Ot(x)})`),console.log(Bn(x));if(!await qn(`Deploy to ${e$1.env}? [y/N] `)){console.log("Deployment cancelled.");let{userId:x,tenantId:te}=await d();x?await f(a$2.DEPLOY_ABORTED,x,te,{env:e$1.env,workspace:c?.slug,reason:"user_cancelled"}):await e(a$2.DEPLOY_ABORTED,{env:e$1.env,workspace:c?.slug,reason:"user_cancelled"}),await j$1(),process.exit(0);}let X=await j(`${r$1}/api/workspaces/${d$1}/deploys/apply`,n,{method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify({planToken:L})});if(!X.ok){let x=await K(X);console.error(`Error: Failed to apply deploy. ${x}`);let{userId:te,tenantId:z}=await d();te?await f(a$2.DEPLOY_FAILED,te,z,{env:e$1.env,workspace:c?.slug,error_class:"ApplyError"}):await e(a$2.DEPLOY_FAILED,{env:e$1.env,workspace:c?.slug,error_class:"ApplyError"}),await j$1(),process.exit(1);}let se=await X.json();console.log(`${w} Deployed to ${e$1.env}`),console.log(` Created: ${(se.created||[]).length} resource(s)`);for(let x of se.created||[])console.log(` + ${x.slug||x.referenceKey||x.id}`);console.log(` Versioned: ${(se.versioned||[]).length} resource(s)`);for(let x of se.versioned||[])console.log(` ~ ${x.slug||x.referenceKey||x.id}`);console.log(` Destroyed: ${(se.destroyed||[]).length} resource(s)`);for(let x of se.destroyed||[])console.log(` - ${x.slug||x.referenceKey||x.id}`);let{userId:le,tenantId:P}=await d();le?await f(a$2.DEPLOY_SUCCEEDED,le,P,{env:e$1.env,workspace:c.slug,created:C.created.length,versioned:C.versioned.length,destroyed:C.destroyed.length}):await e(a$2.DEPLOY_SUCCEEDED,{env:e$1.env,workspace:c.slug,created:C.created.length,versioned:C.versioned.length,destroyed:C.destroyed.length});}catch(f$1){console.error(`Error: Network or unexpected error: ${f$1.message}`);let{userId:I,tenantId:E}=await d();I?await f(a$2.DEPLOY_FAILED,I,E,{env:e$1.env,workspace:c?.slug,error_class:f$1?.constructor?.name}):await e(a$2.DEPLOY_FAILED,{env:e$1.env,workspace:c?.slug,error_class:f$1?.constructor?.name}),await j$1(),process.exit(1);}});});}function Jn(){let t=a$1();return t.isTTY&&!t.isCI&&t.supportsColor&&t.supportsUnicode}function Ft(t){t.command("rename").description("Rename a resource").argument("<old-slug>","Current slug").argument("<new-slug>","New slug").requiredOption("--resource-type <type>","Type of resource (agent)").option("--env <env>","Target environment (sandbox or prod)").option("--workspace-slug <slug>","Target workspace slug (overrides config)").action(async(e$1,n,r$1)=>{if(Jn()){let o=function(){let[s,u]=ue.useState({type:"loading"});return ue.useEffect(()=>(d$1.current=u,()=>{d$1.current=null;}),[]),ue.createElement(a,{state:s})};let{RenameView:a}=await import('./RenameView-3BABATL6.js'),d$1={current:null};if(await V(Promise.resolve(ue.createElement(o))),r$1.resourceType!=="agent"){d$1.current?.({type:"error",message:"Invalid resource type",detail:`'${r$1.resourceType}' \u2014 must be: agent`}),await e(a$2.RENAME_FAILED,{error_class:"InvalidResourceType",resourceType:r$1.resourceType,env:r$1.env,workspace:r$1.workspaceSlug}),await j$1();return}await H(async s$1=>{let{apiUrl:u,context:c}=await r({env:r$1.env}),w=s(c),{userId:p,tenantId:y}=await d();p?await f(a$2.RENAME_STARTED,p,y,{resourceType:r$1.resourceType,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_STARTED,{resourceType:r$1.resourceType,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();let k=c.workspace_id;if(r$1.workspaceSlug){let A=await j(`${u}/api/workspaces?tenantId=${c.tenant_id}`,s$1,{headers:w});if(!A.ok){d$1.current?.({type:"error",message:"Failed to fetch workspaces",detail:await K(A)}),p?await f(a$2.RENAME_FAILED,p,y,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceFetchError",env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceFetchError",env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();return}let R=((await A.json())?.data?.workspaces||[]).find(O=>O.slug===r$1.workspaceSlug);if(!R){d$1.current?.({type:"error",message:`Workspace not found: ${r$1.workspaceSlug}`}),p?await f(a$2.RENAME_FAILED,p,y,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceNotFound",env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceNotFound",env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();return}k=R.id;}if(!k){d$1.current?.({type:"error",message:"No workspace configured",detail:"Run culvii dev first, or provide --workspace-slug <slug>."}),p?await f(a$2.RENAME_FAILED,p,y,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error_class:"NoWorkspace",env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error_class:"NoWorkspace",env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();return}try{let A=await j(`${u}/api/workspaces/${k}/resources/${e$1}/rename`,s$1,{method:"PATCH",headers:{...w,"Content-Type":"application/json"},body:JSON.stringify({newSlug:n,resourceType:r$1.resourceType})});if(!A.ok){let h=await K(A);d$1.current?.({type:"error",message:"Failed to rename resource",detail:`Server responded with ${A.status}: ${h}`}),p?await f(a$2.RENAME_FAILED,p,y,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error:h,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error:h,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();return}d$1.current?.({type:"success",oldSlug:e$1,newSlug:n}),p?await f(a$2.RENAME_SUCCEEDED,p,y,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_SUCCEEDED,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();}catch(A){d$1.current?.({type:"error",message:"Unexpected error",detail:A.message}),p?await f(a$2.RENAME_FAILED,p,y,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error:A.message,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error:A.message,env:c.environment,workspace:r$1.workspaceSlug??c.workspace_slug}),await j$1();}});return}await H(async a=>{r$1.resourceType!=="agent"&&(console.error(`Error: Invalid resource type '${r$1.resourceType}'. Must be: agent`),await e(a$2.RENAME_FAILED,{error_class:"InvalidResourceType",resourceType:r$1.resourceType,env:r$1.env,workspace:r$1.workspaceSlug}),await j$1(),process.exit(1));let{apiUrl:d$1,context:o}=await r({env:r$1.env}),s$1=s(o),{userId:u,tenantId:c}=await d();u?await f(a$2.RENAME_STARTED,u,c,{resourceType:r$1.resourceType,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_STARTED,{resourceType:r$1.resourceType,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1(),console.log(`tenant: ${o.tenant_slug} | workspace: ${r$1.workspaceSlug||o.workspace_slug||"unknown"} | env: ${o.environment}`);let w$1=o.workspace_id;if(r$1.workspaceSlug){let p=await j(`${d$1}/api/workspaces?tenantId=${o.tenant_id}`,a,{headers:s$1});p.ok||(console.error(`Failed to fetch workspaces: ${await K(p)}`),u?await f(a$2.RENAME_FAILED,u,c,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceFetchError",env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceFetchError",env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1(),process.exit(1));let A=((await p.json())?.data?.workspaces||[]).find(h=>h.slug===r$1.workspaceSlug);A||(console.error("Workspace not found: "+r$1.workspaceSlug),u?await f(a$2.RENAME_FAILED,u,c,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceNotFound",env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error_class:"WorkspaceNotFound",env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1(),process.exit(1)),w$1=A.id;}w$1||(console.error("Error: No workspace configured. Run culvii dev first, or provide --workspace-slug <slug>."),u?await f(a$2.RENAME_FAILED,u,c,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error_class:"NoWorkspace",env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error_class:"NoWorkspace",env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1(),process.exit(1));try{let p=await j(`${d$1}/api/workspaces/${w$1}/resources/${e$1}/rename`,a,{method:"PATCH",headers:{...s$1,"Content-Type":"application/json"},body:JSON.stringify({newSlug:n,resourceType:r$1.resourceType})});if(!p.ok){let y=await K(p);console.error(`Error: Failed to rename resource. Server responded with ${p.status}: ${y}`),u?await f(a$2.RENAME_FAILED,u,c,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error:y,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error:y,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1(),process.exit(1);}console.log(`${w} Renamed ${e$1} ${z} ${n}`),console.log(" Immutable ID preserved. All execution history retained."),u?await f(a$2.RENAME_SUCCEEDED,u,c,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_SUCCEEDED,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1();}catch(p){console.error(`Error: Network or unexpected error: ${p.message}`),u?await f(a$2.RENAME_FAILED,u,c,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error:p.message,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}):await e(a$2.RENAME_FAILED,{oldSlug:e$1,newSlug:n,resourceType:r$1.resourceType,error:p.message,env:o.environment,workspace:r$1.workspaceSlug??o.workspace_slug}),await j$1(),process.exit(1);}});});}async function Mt(t,e,n){let r=await j(`${e}/auth/me`,t,{skipEnvironmentHeader:true});if(!r.ok)return {ok:false,status:r.status,error:await K(r)};let i=await r.json(),a=i?.user||i?.data?.user||i,d=i?.tenant||i?.data?.tenant||{},o=d?.slug||n.tenant_slug||"Unknown",s=d?.name||n.tenant_slug||"Unknown",u=Array.isArray(i?.tenants)?i.tenants.find(w=>w.id===d?.id):void 0,c=Array.isArray(u?.roleConfig?.grants)?u.roleConfig.grants:[];return {ok:true,email:a?.email||"Unknown",name:a?.name||"Unknown",tenant:o,tenantName:s,workspace:n.workspace_slug||null,access:c}}function zn(t){let e=t.environment?t.workspace?`${t.environment.environmentName} / ${t.workspace.workspaceName}`:`${t.environment.environmentName} \xB7 all workspaces`:"tenant level";return `${t.role.displayName} \u2014 ${e}`}async function Re(t,e$1){let{userId:n,tenantId:r}=await d(),i=t?{error:true,...e$1}:e$1?{...e$1}:void 0;n?await f(a$2.WHOAMI_VIEWED,n,r,i):await e(a$2.WHOAMI_VIEWED,i),await j$1();}function jt(t){t.command("whoami").description("Show current authenticated user context").option("--json","Output as JSON").action(async e=>{let{getCapabilities:n}=await import('./terminalCapabilities-LJTRMVG4.js'),r=n();if(e.json||!r.isTTY||r.isCI||!r.supportsColor||!r.supportsUnicode){await Xn();return}await Zn();});}async function Xn(){await H(async t=>{let{apiUrl:e,context:n}=await r(),r$1=await Mt(t,e,n);r$1.ok||(process.stderr.write(JSON.stringify({error:r$1.error})+`
|
|
9
|
+
`),await Re(!0),process.exit(1)),process.stdout.write(JSON.stringify({email:r$1.email,name:r$1.name,tenant:r$1.tenant,tenant_name:r$1.tenantName,workspace:r$1.workspace,access:r$1.access})+`
|
|
10
|
+
`),await Re(!1,{workspace:r$1.workspace});});}async function Zn(){let{WhoamiView:t}=await import('./WhoamiView-VHDXFFLX.js'),e={type:"loading"},n=null,{useState:r$1,useEffect:i}=await import('react');function a(){let[d,o]=r$1(e);return i(()=>(n=o,()=>{n=null;}),[]),ue.createElement(t,{state:d})}await V(Promise.resolve(ue.createElement(a))),await H(async d=>{try{let{apiUrl:o,context:s}=await r(),u=await Mt(d,o,s);if(!u.ok){n?.({type:"error",message:"Failed to fetch identity",detail:`Server responded with ${u.status}: ${u.error}`}),await Re(!0);return}n?.({type:"success",email:u.email,name:u.name,tenant:u.tenant,tenantName:u.tenantName,workspace:u.workspace,access:u.access.map(zn)}),await Re(!1,{workspace:u.workspace});}catch(o){n?.({type:"error",message:"Unexpected error",detail:o.message}),await Re(!0);}});}function Qn(){let t=a$1();return t.isTTY&&!t.isCI&&t.supportsColor&&t.supportsUnicode}function He(t){return t.workspace_slugs?.[t.environment]??t.workspace_slug??null}function Vt(t){t.command("switch [tenant-slug]").description("Switch the active tenant context").action(async e$1=>{try{let n=new a$3,r;try{r=await n.read({exitOnError:!1});}catch(u){if(u.message==="Active context key not found"){let c=J.join(ct.homedir(),".culvii","config"),w=await ee.readFile(c,"utf-8");r=JSON.parse(w);}else if(u.code==="ENOENT"){console.error("No configuration found. Please run `culvii login` first.");let{userId:c,tenantId:w}=await d();c?await f(a$2.TENANT_SWITCH_FAILED,c,w,{error_class:"ENOENT",slug:e$1}):await e(a$2.TENANT_SWITCH_FAILED,{error_class:"ENOENT",slug:e$1}),await j$1(),process.exit(1);}else throw u}if(!r||!r.contexts){console.error("No configuration found. Please run `culvii login` first.");let{userId:u,tenantId:c}=await d();u?await f(a$2.TENANT_SWITCH_FAILED,u,c,{error_class:"NoConfig",slug:e$1}):await e(a$2.TENANT_SWITCH_FAILED,{error_class:"NoConfig",slug:e$1}),await j$1(),process.exit(1);}let i=r.contexts,a=Object.keys(i);if(a.length===0){console.error("No tenants available. Please run `culvii login` first.");let{userId:u,tenantId:c}=await d();u?await f(a$2.TENANT_SWITCH_FAILED,u,c,{error_class:"NoTenants",slug:e$1}):await e(a$2.TENANT_SWITCH_FAILED,{error_class:"NoTenants",slug:e$1}),await j$1(),process.exit(1);}if(Qn()){let{SwitchView:u}=await import('./SwitchView-PS3ICKZT.js');if(a.length===1&&!e$1&&(await V(Promise.resolve(ue.createElement(u,{state:{type:"only_one",slug:a[0]}}))),process.exit(0)),!e$1){let y=a.map(k=>({slug:k,tenantId:i[k].tenant_id,workspaceSlug:He(i[k]),environment:i[k].environment,isActive:k===r.active}));await V(Promise.resolve(ue.createElement(u,{state:{type:"list",tenants:y}}))),process.exit(0);}if(!i[e$1]){let y=a.map(h=>({slug:h,tenantId:i[h].tenant_id,workspaceSlug:He(i[h]),environment:i[h].environment,isActive:h===r.active}));await V(Promise.resolve(ue.createElement(u,{state:{type:"error",message:`Tenant '${e$1}' not found.`}})));let{userId:k,tenantId:A}=await d();k?await f(a$2.TENANT_SWITCH_FAILED,k,A,{error_class:"TenantNotFound",slug:e$1}):await e(a$2.TENANT_SWITCH_FAILED,{error_class:"TenantNotFound",slug:e$1}),await j$1(),process.exit(1);}await n.withLock(async()=>{let y=J.join(ct.homedir(),".culvii","config"),k=await ee.readFile(y,"utf-8"),A=JSON.parse(k);await n.write({...A,active:e$1});});let c$1=i[e$1];await V(Promise.resolve(ue.createElement(u,{state:{type:"success",slug:e$1,workspaceSlug:He(c$1),environment:c$1.environment}}))),c();let{userId:w,tenantId:p}=await d();w?await f(a$2.TENANT_SWITCHED,w,p,{to:e$1}):await e(a$2.TENANT_SWITCHED,{to:e$1}),await j$1();return}if(a.length===1&&!e$1&&(console.log(`Only one tenant available: ${a[0]}`),process.exit(0)),e$1||(console.log("Available tenants:"),a.forEach((u,c)=>{let w=i[u],p=u===r.active?"*":" ";console.log(`${c+1}. ${p} ${u} (Tenant ID: ${w.tenant_id})`);}),console.log(`
|
|
11
|
+
To switch, run: culvii switch <tenant-slug>`),process.exit(0)),!i[e$1]){console.error(`Error: Tenant '${e$1}' not found.`),console.log(`
|
|
12
|
+
Available tenants:`),a.forEach((w,p)=>{let y=i[w],k=w===r.active?"*":" ";console.log(`${p+1}. ${k} ${w} (Tenant ID: ${y.tenant_id})`);});let{userId:u,tenantId:c}=await d();u?await f(a$2.TENANT_SWITCH_FAILED,u,c,{error_class:"TenantNotFound",slug:e$1}):await e(a$2.TENANT_SWITCH_FAILED,{error_class:"TenantNotFound",slug:e$1}),await j$1(),process.exit(1);}await n.withLock(async()=>{let u=J.join(ct.homedir(),".culvii","config"),c=await ee.readFile(u,"utf-8"),w=JSON.parse(c);await n.write({...w,active:e$1});});let d$1=i[e$1];console.log(`tenant: ${e$1} | workspace: ${He(d$1)||"none"} | env: ${d$1.environment}`),console.log(`Switched to tenant: ${e$1}`),c();let{userId:o,tenantId:s}=await d();o?await f(a$2.TENANT_SWITCHED,o,s,{to:e$1}):await e(a$2.TENANT_SWITCHED,{to:e$1}),await j$1();}catch(n){n.code==="ENOENT"?console.error("No configuration found. Please run `culvii login` first."):console.error(`Failed to switch context: ${n.message}`);let{userId:r,tenantId:i}=await d();r?await f(a$2.TENANT_SWITCH_FAILED,r,i,{error_class:n.code||n.constructor?.name||"UnknownError",slug:e$1}):await e(a$2.TENANT_SWITCH_FAILED,{error_class:n.code||n.constructor?.name||"UnknownError",slug:e$1}),await j$1(),process.exit(1);}});}var Kt=["dev","sandbox","prod"];function ar(){let t=a$1();return t.isTTY&&!t.isCI&&t.supportsColor&&t.supportsUnicode}async function qe(t){if(!ar())return false;let{EnvView:e}=await import('./EnvView-3ZURMIZS.js');return await V(Promise.resolve(ue.createElement(e,{state:t}))),true}async function sr(t,e,n){let r=await j(`${e}/auth/me`,t,{skipEnvironmentHeader:true});if(!r.ok)return [];let i=await r.json(),a=i?.tenant||{};return ((Array.isArray(i?.tenants)?i.tenants.find(o=>o.id===(n??a?.id)):void 0)?.environments??[]).map(o=>l(o.slug)).filter(o=>o!==null)}function Yt(t){t.command("env [environment]").description("Show or switch the active environment (dev, sandbox, prod)").action(async e$1=>{await H(async n=>{let{apiUrl:r$1,context:i}=await r(),a=await sr(n,r$1,i.tenant_id);if(!e$1){if(await qe({type:"show",current:i.environment,tenant:i.tenant_slug,accessible:a}))return;let w=a.includes(i.environment)?"":" (no access)";process.stdout.write(`current: ${i.environment}${w}
|
|
13
13
|
`),process.stdout.write(`tenant: ${i.tenant_slug}
|
|
14
|
-
`),process.stdout.write(`available: ${
|
|
15
|
-
`),!
|
|
16
|
-
Switch with: culvii env ${
|
|
17
|
-
`);return}let
|
|
18
|
-
`),process.exit(1);}let o=
|
|
19
|
-
`),process.exit(1);}let
|
|
14
|
+
`),process.stdout.write(`available: ${a.length?a.join(", "):"none"}
|
|
15
|
+
`),!a.includes(i.environment)&&a.length>0&&process.stdout.write(`
|
|
16
|
+
Switch with: culvii env ${a[0]}
|
|
17
|
+
`);return}let d$1=e$1.toLowerCase();if(!Kt.includes(d$1)){let w=`Invalid environment '${e$1}'.`,p=`Valid values: ${Kt.join(", ")}.`;if(await e(a$2.ENV_SWITCH_FAILED,{error_class:"InvalidEnv",env:e$1}),await j$1(),await qe({type:"error",message:w,detail:p})){process.exitCode=1;return}process.stderr.write(`${w} ${p}
|
|
18
|
+
`),process.exit(1);}let o=d$1;if(a.length&&!a.includes(o)){let w=`You don't have access to '${o}' in this tenant.`,p=`Accessible: ${a.join(", ")}.`;if(await e(a$2.ENV_SWITCH_FAILED,{error_class:"NoAccess",env:o}),await j$1(),await qe({type:"error",message:w,detail:p})){process.exitCode=1;return}process.stderr.write(`${w} ${p}
|
|
19
|
+
`),process.exit(1);}let s=new a$3;await s.withLock(async()=>{let w=J.join(ct.homedir(),".culvii","config"),p=await ee.readFile(w,"utf-8"),y=JSON.parse(p),k=y.contexts[y.active];k&&(k.environment=o,k.environment_id=k.environment_ids?.[o]??k.environment_id),await s.write(y);}),await qe({type:"success",env:o,tenant:i.tenant_slug})||(process.stdout.write(`env: ${o} | tenant: ${i.tenant_slug}
|
|
20
20
|
`),process.stdout.write(`Switched environment to ${o}
|
|
21
|
-
`)),c();let{userId:
|
|
21
|
+
`)),c();let{userId:u,tenantId:c$1}=await d();u?await f(a$2.ENV_SWITCHED,u,c$1,{to:o}):await e(a$2.ENV_SWITCHED,{to:o}),await j$1();});});}var lt=`---
|
|
22
22
|
name: culvii
|
|
23
23
|
description: Use this skill when the user wants to write, test, or deploy Culvii agents or workflows using the @culvii/kit SDK and CLI.
|
|
24
24
|
---
|
|
@@ -511,7 +511,6 @@ culvii login # authenticate via browser OAuth
|
|
|
511
511
|
culvii dev # start file watcher + sync drafts to cloud
|
|
512
512
|
culvii deploy --env sandbox --workspace-slug <slug> # deploy to sandbox
|
|
513
513
|
culvii deploy --env prod --workspace-slug <slug> # deploy to prod
|
|
514
|
-
culvii deploy ... --allow-destroy # allow deletion of removed resources
|
|
515
514
|
culvii init [project-name] # scaffold a new project
|
|
516
515
|
culvii whoami # show current user and context
|
|
517
516
|
culvii switch <tenant-slug> # switch active tenant
|
|
@@ -666,7 +665,7 @@ createLookupWorkflow();
|
|
|
666
665
|
createConciergeAgent();
|
|
667
666
|
createParentWorkflow();
|
|
668
667
|
\`\`\`
|
|
669
|
-
`;function
|
|
668
|
+
`;function ir(){let t=a$1();return t.isTTY&&!t.isCI&&t.supportsColor&&t.supportsUnicode}var xe={claude:{projectDir:".claude/skills/culvii",globalDir:".claude/skills/culvii",detect:".claude"},cursor:{projectDir:".cursor/skills/culvii",globalDir:".cursor/skills/culvii",detect:".cursor"},windsurf:{projectDir:".windsurf/skills/culvii",globalDir:".codeium/windsurf/skills/culvii",detect:".windsurf"},github:{projectDir:".github/skills/culvii",globalDir:".copilot/skills/culvii",detect:".github"},opencode:{projectDir:".opencode/skills/culvii",globalDir:".config/opencode/skills/culvii",detect:".opencode"},gemini:{projectDir:".gemini/skills/culvii",globalDir:".gemini/skills/culvii",detect:".gemini"},kiro:{projectDir:".kiro/skills/culvii",globalDir:".kiro/skills/culvii",detect:".kiro"},agents:{projectDir:".agents/skills/culvii",globalDir:".agents/skills/culvii",detect:".agents"}};function Ht(t){let e=process.cwd(),n=new Set;if(t){let i=t.toLowerCase();if(i==="codex"&&(i="agents"),!xe[i]){let a=[...Object.keys(xe),"codex"].sort();return {error:`Invalid agent: ${t}. Must be one of: ${a.join(", ")}.`}}return n.add(i),{targets:n}}let r=false;for(let[i,a]of Object.entries(xe))i!=="agents"&&he.existsSync(J.join(e,a.detect))&&(n.add(i),r=true);return n.add("agents"),r?{targets:n}:(n.add("claude"),{targets:n,fallbackWarning:"No specific agent directories detected. Defaulting to Claude Code and Universal Fallback paths."})}function qt(t){t.command("skill").description("Manage AI agent skills").command("install").description("Install the culvii SDK & CLI skill for AI agents").option("--agent <agent>","Specify agent (claude|cursor|windsurf|github|opencode|gemini|kiro|codex|agents) to skip auto-detection").option("--global","Install globally to your home directory instead of the current project").action(async n=>{let r=process.cwd(),i=ct.homedir();if(ir()){let w=function(){let[h,R]=ue.useState({type:"loading"});return ue.useEffect(()=>(c.current=R,()=>{c.current=null;}),[]),ue.createElement(u,{state:h})};let{SkillView:u}=await import('./SkillView-N27S3VSV.js'),c={current:null};await V(Promise.resolve(ue.createElement(w)));let p=Ht(n.agent);if("error"in p){c.current?.({type:"error",message:"Invalid agent",detail:p.error});return}let{targets:y,fallbackWarning:k}=p,A=[];for(let h of y){let R=xe[h],O=n.global?i:r,M=n.global?R.globalDir:R.projectDir,S=J.join(O,M),D=J.join(S,"SKILL.md");try{he.existsSync(S)||he.mkdirSync(S,{recursive:!0}),he.writeFileSync(D,lt,"utf8");let $=n.global?J.join("~",M,"SKILL.md"):J.join(M,"SKILL.md"),f=h==="agents"?"Universal/Codex":h;A.push({agentName:f,displayPath:$});}catch($){c.current?.({type:"error",message:`Failed to install skill for ${h}`,detail:$.message});return}}c.current?.({type:"success",installed:A,fallbackWarning:k});return}let a=Ht(n.agent);"error"in a&&(console.error(`${x} ${a.error}`),process.exit(1));let{targets:d,fallbackWarning:o}=a;o&&console.log(`${w} ${o}`);for(let u of d){let c=xe[u],w$1=n.global?i:r,p=n.global?c.globalDir:c.projectDir,y=J.join(w$1,p),k=J.join(y,"SKILL.md");try{he.existsSync(y)||he.mkdirSync(y,{recursive:!0}),he.writeFileSync(k,lt,"utf8");let A=n.global?J.join("~",p,"SKILL.md"):J.join(p,"SKILL.md");console.log(`${w} Installed skill for ${u==="agents"?"Universal/Codex":u} at ${A}`);}catch(A){console.error(`${x} Failed to install skill for ${u}: ${A.message}`),process.exit(1);}}});}function dt({label:t,items:e,defaultIndex:n,onSelect:r}){let i=e.map((d,o)=>({key:String(o+1),label:d.label,description:d.description})),a=n!==void 0?String(n+1):void 0;return jsx(a$5,{label:t,options:i,defaultKey:a,onSubmit:d=>{let o=parseInt(d,10)-1,s=e[o];s&&r(s.value);}})}function pr(){let t=a$1();return t.isTTY&&!t.isCI&&t.supportsColor&&t.supportsUnicode}var ne=["agent-only","agent-workflow","agent-workflow-tool","multi-agent"],re=["openai","anthropic","gemini","google-vertex"],Gt={"agent-only":"A single standalone AI agent","agent-workflow":"An AI agent triggered by a manual workflow","agent-workflow-tool":"An agent that invokes a workflow as a callable tool","multi-agent":"A coordinator agent that delegates to a specialist agent"},Jt={openai:"openai/YOUR_MODEL_ID",anthropic:"anthropic/YOUR_MODEL_ID",gemini:"gemini/YOUR_MODEL_ID","google-vertex":"google-vertex/YOUR_MODEL_ID"},zt=`{
|
|
670
669
|
"compilerOptions": {
|
|
671
670
|
"target": "ES2022",
|
|
672
671
|
"module": "NodeNext",
|
|
@@ -676,11 +675,11 @@ createParentWorkflow();
|
|
|
676
675
|
"esModuleInterop": true
|
|
677
676
|
},
|
|
678
677
|
"include": ["src/**/*.ts"]
|
|
679
|
-
}`;function
|
|
678
|
+
}`;function Xt(t){return JSON.stringify({name:t,version:"0.1.0",type:"commonjs",private:true,scripts:{dev:"culvii dev",deploy:"culvii deploy"},dependencies:{"@culvii/kit":"latest",tsx:"^4.22.3"},engines:{node:">=22.0.0"}},null,2)}function Ge(t){return `// Generated by culvii init \u2014 replace YOUR_CREDENTIAL_ID and YOUR_MODEL_ID with your actual values from the Culvii console
|
|
680
679
|
import { MultiAgentEngine, createAgentModelConfigFromRef } from '@culvii/kit';
|
|
681
680
|
|
|
682
681
|
const MODEL_CREDENTIAL_ID = 'YOUR_CREDENTIAL_ID';
|
|
683
|
-
const MODEL = createAgentModelConfigFromRef('${
|
|
682
|
+
const MODEL = createAgentModelConfigFromRef('${t}', MODEL_CREDENTIAL_ID);
|
|
684
683
|
|
|
685
684
|
function createGreeterAgent() {
|
|
686
685
|
return new MultiAgentEngine({
|
|
@@ -695,7 +694,7 @@ function createGreeterAgent() {
|
|
|
695
694
|
}
|
|
696
695
|
|
|
697
696
|
createGreeterAgent();
|
|
698
|
-
`}var
|
|
697
|
+
`}var Zt=`// Generated by culvii init \u2014 replace YOUR_CREDENTIAL_ID and YOUR_MODEL_ID with your actual values from the Culvii console
|
|
699
698
|
import { Workflow, Step } from '@culvii/kit';
|
|
700
699
|
|
|
701
700
|
function createGreetingWorkflow() {
|
|
@@ -726,11 +725,11 @@ function createGreetingWorkflow() {
|
|
|
726
725
|
}
|
|
727
726
|
|
|
728
727
|
createGreetingWorkflow();
|
|
729
|
-
`;function
|
|
728
|
+
`;function Qt(t){return `// Generated by culvii init \u2014 replace YOUR_CREDENTIAL_ID and YOUR_MODEL_ID with your actual values from the Culvii console
|
|
730
729
|
import { MultiAgentEngine, createAgentModelConfigFromRef } from '@culvii/kit';
|
|
731
730
|
|
|
732
731
|
const MODEL_CREDENTIAL_ID = 'YOUR_CREDENTIAL_ID';
|
|
733
|
-
const MODEL = createAgentModelConfigFromRef('${
|
|
732
|
+
const MODEL = createAgentModelConfigFromRef('${t}', MODEL_CREDENTIAL_ID);
|
|
734
733
|
|
|
735
734
|
function createCoordinatorAgent() {
|
|
736
735
|
return new MultiAgentEngine({
|
|
@@ -754,11 +753,11 @@ function createCoordinatorAgent() {
|
|
|
754
753
|
}
|
|
755
754
|
|
|
756
755
|
createCoordinatorAgent();
|
|
757
|
-
`}function
|
|
756
|
+
`}function en(t){return `// Generated by culvii init \u2014 replace YOUR_CREDENTIAL_ID and YOUR_MODEL_ID with your actual values from the Culvii console
|
|
758
757
|
import { MultiAgentEngine, createAgentModelConfigFromRef, defineWorkflowTool } from '@culvii/kit';
|
|
759
758
|
|
|
760
759
|
const MODEL_CREDENTIAL_ID = 'YOUR_CREDENTIAL_ID';
|
|
761
|
-
const MODEL = createAgentModelConfigFromRef('${
|
|
760
|
+
const MODEL = createAgentModelConfigFromRef('${t}', MODEL_CREDENTIAL_ID);
|
|
762
761
|
|
|
763
762
|
function createResearchAgent() {
|
|
764
763
|
return new MultiAgentEngine({
|
|
@@ -787,7 +786,7 @@ function createResearchAgent() {
|
|
|
787
786
|
}
|
|
788
787
|
|
|
789
788
|
createResearchAgent();
|
|
790
|
-
`}var
|
|
789
|
+
`}var tn=`// Generated by culvii init \u2014 replace YOUR_CREDENTIAL_ID and YOUR_MODEL_ID with your actual values from the Culvii console
|
|
791
790
|
import { Workflow, Step } from '@culvii/kit';
|
|
792
791
|
|
|
793
792
|
function createResearchWorkflow() {
|
|
@@ -805,7 +804,7 @@ function createResearchWorkflow() {
|
|
|
805
804
|
}
|
|
806
805
|
|
|
807
806
|
createResearchWorkflow();
|
|
808
|
-
`;function
|
|
807
|
+
`;function nn(){return `// Generated by culvii init \u2014 replace YOUR_CREDENTIAL_ID and YOUR_MODEL_ID with your actual values from the Culvii console
|
|
809
808
|
import { Workflow, Step } from '@culvii/kit';
|
|
810
809
|
|
|
811
810
|
function createCoordinationWorkflow() {
|
|
@@ -836,9 +835,9 @@ function createCoordinationWorkflow() {
|
|
|
836
835
|
}
|
|
837
836
|
|
|
838
837
|
createCoordinationWorkflow();
|
|
839
|
-
`}async function
|
|
840
|
-
Select a template:`),
|
|
841
|
-
Select a model provider:`),
|
|
842
|
-
`)?
|
|
843
|
-
`),_e&&(_e(),_e=null),await j$1(),process.exit(
|
|
844
|
-
`),
|
|
838
|
+
`}async function ut(t,e){return (await t.question(e)).trim()}async function fr(t,e$1){let{userId:n,tenantId:r}=await d(),i=async(p,y={})=>{n?await f(p,n,r,y):await e(p,y);};await i(a$2.INIT_STARTED);let a=t,d$1=e$1.template,o=e$1.provider;if(d$1&&!ne.includes(d$1)&&(console.error(`${x} Invalid template '${d$1}'. Valid options: ${ne.join(", ")}`),await i(a$2.INIT_FAILED,{error_class:"InvalidTemplate"}),await j$1(),process.exit(1)),o&&!re.includes(o)&&(console.error(`${x} Invalid provider '${o}'. Valid options: ${re.join(", ")}`),await i(a$2.INIT_FAILED,{error_class:"InvalidProvider"}),await j$1(),process.exit(1)),!e$1.yes&&process.stdout.isTTY&&process.stdin.isTTY){let{render:p}=await import('ink');if(!a&&!e$1.here&&(a=await new Promise(y=>{let{unmount:k}=p(ue.createElement(a$5,{label:"Project name [Enter = my-culvii-project]",defaultValue:"my-culvii-project",onSubmit:A=>{k(),y(A||"my-culvii-project");}}));})),!d$1){let y=ne.indexOf("agent-workflow");d$1=await new Promise(k=>{let{unmount:A}=p(ue.createElement(dt,{label:"Select a template [Enter = agent-workflow]",items:ne.map(h=>({value:h,label:h.padEnd(16),description:Gt[h]})),defaultIndex:y,onSelect:h=>{A(),k(h);}}));});}if(!o){let y=re.indexOf("openai");o=await new Promise(k=>{let{unmount:A}=p(ue.createElement(dt,{label:"Select a model provider [Enter = openai]",items:re.map(h=>({value:h,label:h})),defaultIndex:y,onSelect:h=>{A(),k(h);}}));});}}else !a&&!e$1.here&&(a="my-culvii-project"),d$1||(d$1="agent-workflow"),o||(o="openai");let{InitView:u}=await import('./InitView-TI2HU6VV.js'),c={update:null};function w(){let[p,y]=ue.useState({type:"scaffolding",message:"Scaffolding project\u2026"});return ue.useEffect(()=>(c.update=y,()=>{c.update=null;}),[]),ue.createElement(u,{state:p})}await V(Promise.resolve(ue.createElement(w)));try{let p=e$1.here?process.cwd():J.join(process.cwd(),a);if(existsSync(p)){if((await ee.readdir(p)).filter(S=>!S.startsWith(".")).length>0){c.update?.({type:"error",message:`Directory '${J.relative(process.cwd(),p)||"."}' already exists and is not empty.`}),await i(a$2.INIT_FAILED,{error_class:"DirectoryNotEmpty"}),await j$1();return}}else await ee.mkdir(p,{recursive:!0});let y=J.join(p,"src");await ee.mkdir(y,{recursive:!0});let k=Jt[o],A=[];await ee.writeFile(J.join(p,"package.json"),Xt(e$1.here?J.basename(p):a),"utf-8"),await ee.writeFile(J.join(p,"tsconfig.json"),zt,"utf-8"),A.push("package.json"),A.push("tsconfig.json");let h=async(O,M)=>{await ee.writeFile(J.join(y,O),M,"utf-8"),A.push(J.join("src",O));};d$1==="agent-only"?await h("greeter-agent.culvii.ts",Ge(k)):d$1==="agent-workflow"?(await h("greeter-agent.culvii.ts",Ge(k)),await h("greeting-workflow.culvii.ts",Zt)):d$1==="agent-workflow-tool"?(await h("research-agent.culvii.ts",en(k)),await h("research-workflow.culvii.ts",tn)):d$1==="multi-agent"&&(await h("coordinator-agent.culvii.ts",Qt(k)),await h("coordination-workflow.culvii.ts",nn()));let R=e$1.here?".":`./${a}`;c.update?.({type:"success",template:d$1,projectDir:R,written:A,here:!!e$1.here,projectName:a}),await i(a$2.INIT_SUCCEEDED,{template:d$1,provider:o}),await j$1();}catch(p){c.update?.({type:"error",message:`Initialization failed: ${p.message}`}),await i(a$2.INIT_FAILED,{error_class:p?.constructor?.name??"UnknownError"}),await j$1();return}}function rn(t){t.command("init [project-name]").description("Scaffold a new Culvii project with working agent and workflow files").option("--template <template>",`Template: ${ne.join(" | ")}`).option("--provider <provider>",`Model provider: ${re.join(" | ")}`).option("--here","Scaffold into the current directory instead of a named subdirectory").option("-y, --yes","Accept all defaults non-interactively").action(async(e$1,n)=>{if(pr()){await fr(e$1,n);return}let{userId:r,tenantId:i}=await d(),a=async(u,c={})=>{r?await f(u,r,i,c):await e(u,c);};await a(a$2.INIT_STARTED);let d$1=e$1,o=n.template,s=n.provider;o&&!ne.includes(o)&&(console.error(`${x} Invalid template '${o}'. Valid options: ${ne.join(", ")}`),await a(a$2.INIT_FAILED,{error_class:"InvalidTemplate"}),await j$1(),process.exit(1)),s&&!re.includes(s)&&(console.error(`${x} Invalid provider '${s}'. Valid options: ${re.join(", ")}`),await a(a$2.INIT_FAILED,{error_class:"InvalidProvider"}),await j$1(),process.exit(1));try{if(!n.yes&&process.stdout.isTTY&&process.stdin.isTTY){let A=createInterface({input:stdin,output:stdout});try{if(!d$1&&!n.here&&(d$1=await ut(A,"Project name (my-culvii-project): ")||"my-culvii-project"),!o)for(console.log(`
|
|
839
|
+
Select a template:`),ne.forEach((h,R)=>{console.log(` ${R+1}) ${h.padEnd(16)} ${Gt[h]}`);});!o;){let h=await ut(A,"Template [1-4] (2): "),R=h?parseInt(h,10)-1:1;R>=0&&R<ne.length?o=ne[R]:console.log(` Please enter a number between 1 and ${ne.length}.`);}if(!s)for(console.log(`
|
|
840
|
+
Select a model provider:`),re.forEach((h,R)=>{console.log(` ${R+1}) ${h}`);});!s;){let h=await ut(A,"Provider [1-4] (1): "),R=h?parseInt(h,10)-1:0;R>=0&&R<re.length?s=re[R]:console.log(` Please enter a number between 1 and ${re.length}.`);}}finally{A.close();}}else !d$1&&!n.here&&(d$1="my-culvii-project"),o||(o="agent-workflow"),s||(s="openai");let c=n.here?process.cwd():J.join(process.cwd(),d$1);existsSync(c)?(await ee.readdir(c)).filter(R=>!R.startsWith(".")).length>0&&(console.error(`${x} Directory '${J.relative(process.cwd(),c)||"."}' already exists and is not empty.`),await a(a$2.INIT_FAILED,{error_class:"DirectoryNotEmpty"}),await j$1(),process.exit(1)):await ee.mkdir(c,{recursive:!0});let w$1=J.join(c,"src");await ee.mkdir(w$1,{recursive:!0});let p=Jt[s],y=[];await ee.writeFile(J.join(c,"package.json"),Xt(n.here?J.basename(c):d$1),"utf-8"),await ee.writeFile(J.join(c,"tsconfig.json"),zt,"utf-8"),y.push("package.json"),y.push("tsconfig.json");let k=async(A,h)=>{await ee.writeFile(J.join(w$1,A),h,"utf-8"),y.push(J.join("src",A));};o==="agent-only"?await k("greeter-agent.culvii.ts",Ge(p)):o==="agent-workflow"?(await k("greeter-agent.culvii.ts",Ge(p)),await k("greeting-workflow.culvii.ts",Zt)):o==="agent-workflow-tool"?(await k("research-agent.culvii.ts",en(p)),await k("research-workflow.culvii.ts",tn)):o==="multi-agent"&&(await k("coordinator-agent.culvii.ts",Qt(p)),await k("coordination-workflow.culvii.ts",nn())),console.log(`${w} Initialized '${o}' project${n.here?"":` in ./${d$1}`}`),y.forEach(A=>console.log(` + ${A}`)),n.here||console.log(` cd ${d$1}`),console.log(" 1. Run `npm install`"),console.log(" 2. Replace YOUR_CREDENTIAL_ID and YOUR_MODEL_ID with your actual values from the Culvii console"),console.log(" 3. Run `culvii dev`"),await a(a$2.INIT_SUCCEEDED,{template:o,provider:s}),await j$1();}catch(u){console.error(`${x} Initialization failed: ${u.message}`),await a(a$2.INIT_FAILED,{error_class:u?.constructor?.name??"UnknownError"}),await j$1(),process.exit(1);}});}var pt=a$1();pt.noColor&&(process.env.FORCE_COLOR="0");var _e=null;function mr(t){_e=t;}async function ke(t=0,e){e&&process.stderr.write(e.endsWith(`
|
|
841
|
+
`)?e:`${e}
|
|
842
|
+
`),_e&&(_e(),_e=null),await j$1(),process.exit(t);}var B=new Command;B.exitOverride(t=>{(t.code==="commander.helpDisplayed"||t.code==="commander.version")&&ke(0),ke(t.exitCode);});B.hook("preAction",(t,e)=>{n(e.optsWithGlobals().env);});B.name("culvii").description("Culvii CLI").version("0.0.6").option("--debug","Enable debug logging to ~/.culvii/logs/cli.log").configureOutput({writeOut:t=>process.stdout.write(t),writeErr:t=>process.stderr.write(t)});async function V(t){if(_e&&(_e(),_e=null),(!pt.isTTY||pt.isCI)&&!(ae.includes("--help")||ae.includes("-h"))){console.log("Running in non-interactive mode.");return}let{render:e}=await import('ink'),n=await t,{unmount:r}=e(n);mr(r);}var ae=process.argv.slice(2);(async()=>{try{let{ConfigStore:t}=await import('./config-store-WSXGIIJ4.js');await new t().read({exitOnError:!1});}catch{await e(a$2.CLI_INSTALLED),await j$1();}})();if(ae.length===0)import('./OnboardingView-QWEF3FJU.js').then(async({OnboardingView:t})=>{let e=await import('react');await V(Promise.resolve(e.createElement(t)));});else if(ae.includes("--help")||ae.includes("-h"))import('./HelpView-ZMOAJNYC.js').then(async({HelpView:t})=>{let e$1=ae[0]&&!ae[0].startsWith("-")?ae[0]:"culvii";await e(a$2.CLI_HELP_VIEWED,{command:e$1}),await j$1();let n=await import('react');await V(Promise.resolve(n.createElement(t)));});else if(ae.includes("--version")||ae.includes("-V")||ae.includes("-v"))await e(a$2.CLI_VERSION_VIEWED),process.stdout.write(B.version()+`
|
|
843
|
+
`),ke(0);else {let t=B.command("auth").description("Authentication commands");t.command("login").description("Login to Culvii").action(async()=>{let{login:n}=await import('./login-4VBBCK4V.js');await n();}),t.command("logout").description("Logout of Culvii").action(async()=>{let{logout:n}=await import('./logout-VOWHM2QB.js');await n();}),B.command("login").description("Login to Culvii").action(async()=>{let{login:n}=await import('./login-4VBBCK4V.js');await n();}),B.command("logout").description("Logout of Culvii").action(async()=>{let{logout:n}=await import('./logout-VOWHM2QB.js');await n();}),kt(B),Lt(B),Pt(B),Ft(B),jt(B),Vt(B),Yt(B),qt(B),rn(B);let e$1=false;try{e$1=!!process.argv[1]&&realpathSync(process.argv[1])===fileURLToPath(import.meta.url);}catch{e$1=false;}e$1&&B.parseAsync(process.argv).catch(async n=>{let{userId:r,tenantId:i}=await d();r?await f(a$2.CLI_UNHANDLED_ERROR,r,i,{error_class:n?.constructor?.name||"UnknownError",command:process.argv.slice(2).join(" ")}):await e(a$2.CLI_UNHANDLED_ERROR,{error_class:n?.constructor?.name||"UnknownError",command:process.argv.slice(2).join(" ")}),await j$1(),console.error(n),await ke(1);});}export{_e as activeUnmount,ke as exit,B as program,V as renderApp,mr as setActiveUnmount};
|
package/dist/lib/evaluator.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`),e=true;}process.exit(e?1:0);}
|
|
2
|
+
import a from'path';async function o(){let r=process.argv.slice(2);r.length===0&&process.exit(0);let e=false;for(let t of r)try{await import(a.resolve(t));}catch(s){process.stderr.write(`[culvii evaluator] Failed to import ${t}: ${s.message}
|
|
3
|
+
`),e=true;}try{let{DevRegistry:t}=await import('@culvii/kit');await t.flushAsync();}catch{}process.exit(e?1:0);}o().catch(r=>{process.stderr.write(`[culvii evaluator] Fatal error: ${r.message}
|
|
4
4
|
`),process.exit(1);});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a as a$4}from'./chunk-JFIFRAAR.js';import {b,c,a as a$2}from'./chunk-KZG5CFSB.js';import {e,a,j,q,l,m,b as b$1,h,g,i,c as c$1,f}from'./chunk-
|
|
2
|
+
import {a as a$4}from'./chunk-JFIFRAAR.js';import {b,c,a as a$2}from'./chunk-KZG5CFSB.js';import {e,a,j,q,l,m,b as b$1,h,g,i,c as c$1,f}from'./chunk-LD5ISISS.js';import {a as a$3}from'./chunk-HX54IFSD.js';import {a as a$1}from'./chunk-JYNOILCD.js';import'./chunk-57XLDHK6.js';import'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import ue from'open';import s from'react';import {render}from'ink';import j$1,{timingSafeEqual}from'crypto';import se from'http';import {jsx}from'react/jsx-runtime';function z(a){return a.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ne(){let a=j$1.randomBytes(64);return z(a)}function ae(a){let E=j$1.createHash("sha256").update(a).digest();return z(E)}function oe(){let a=j$1.randomBytes(32);return z(a)}var de=`<!DOCTYPE html>
|
|
3
3
|
<html>
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="utf-8">
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {b,a,c}from'./chunk-KZG5CFSB.js';import {q,d,f,a as a$1,e,j}from'./chunk-
|
|
2
|
+
import {b,a,c}from'./chunk-KZG5CFSB.js';import {q,d,f,a as a$1,e,j}from'./chunk-LD5ISISS.js';import'./chunk-HX54IFSD.js';import'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import w from'react';import {render}from'ink';async function S(){b.info("Logout flow started");let e$1=new a,o=false;await e$1.withLock(async()=>{let a=await e$1.get();if(!a){o=false;return}if(a.refreshToken){b.info("Revocation attempted");let g=`https://${q.cognitoDomain}/oauth2/revoke`,r=new URLSearchParams;r.set("token",a.refreshToken),r.set("client_id",q.clientId);try{await fetch(g,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()}),b.info("Revocation completed");}catch{b.info("Revocation network error ignored");}}await e$1.delete(),b.info("Tokens deleted"),o=true;let{userId:c,tenantId:u}=await d();c?await f(a$1.LOGOUT,c,u):await e(a$1.LOGOUT),await j();}),o?render(w.createElement(c,{state:{type:"logout_success"}})):render(w.createElement(c,{state:{type:"already_logged_out"}}));}
|
|
3
3
|
export{S as logout};
|
package/package.json
CHANGED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {a as a$4}from'./chunk-5NBKYMD7.js';import {a}from'./chunk-R67TA4FU.js';import {a as a$3}from'./chunk-FQVHJUX4.js';import {a as a$1}from'./chunk-JYNOILCD.js';import'./chunk-57XLDHK6.js';import {o,l,c,a as a$2,e,y,d,w}from'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import {useState,useEffect}from'react';import {useApp,useInput,Box,Text}from'ink';import {jsxs,jsx}from'react/jsx-runtime';function P(e){if(e.type==="surface")return "Marks inactive; published versions are retained.";let p=e.versionCount??1,a=e.activeVersion??e.previousVersion;return `Deletes all ${p} ${p===1?"version":"versions"}${a?`; active is v${a}`:""}.`}function I(e){if(e.type==="surface"){let d=e.activeVersion??e.previousVersion;return d?`active v${d}`:"active"}let p=e.executions??0,a=e.activeExecutions??0,c=e.activeVersion??e.previousVersion;return `${p} total, active${c?` v${c}`:""}: ${a} executions`}function G({state:e$1,onConfirm:p}){let{exit:a$5}=useApp(),[c$1,d$1]=useState(false);return useEffect(()=>{e$1.type==="confirming"&&d$1(e$1.allowDestroy);},[e$1]),useEffect(()=>{if(e$1.type==="success"||e$1.type==="no_changes"||e$1.type==="aborted"||e$1.type==="error"){let o=setTimeout(()=>a$5(),100);return ()=>clearTimeout(o)}},[e$1.type,a$5]),useInput((o,k)=>{e$1.type==="confirming"&&(o.toLowerCase()==="y"?p?.(true,c$1):o.toLowerCase()==="n"||k.escape?p?.(false,c$1):o.toLowerCase()==="d"&&e$1.plan.destroyed.length>0?d$1(true):o.toLowerCase()==="k"&&e$1.plan.destroyed.length>0&&d$1(false));}),jsxs(Box,{flexDirection:"column",children:[jsx(a,{command:"culvii",subcommand:"deploy"}),e$1.type==="planning"&&jsx(Box,{paddingLeft:2,children:jsx(a$1,{label:"Planning deploy\u2026"})}),e$1.type==="confirming"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,gap:1,children:[jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{color:o,children:["Plan for ",jsx(Text,{color:l,bold:true,children:e$1.env}),":"]}),jsxs(Box,{flexDirection:"column",marginTop:1,children:[e$1.plan.created.map(o$1=>jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:c,children:"+"}),jsx(Text,{color:l,children:o$1.slug}),jsx(Text,{color:o,children:"CREATED"})]},o$1.slug)),e$1.plan.versioned.map(o$1=>jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:a$2,children:"~"}),jsx(Text,{color:l,children:o$1.slug}),jsxs(Text,{color:o,children:["VERSIONED (",I(o$1),")"]})]},o$1.slug)),e$1.plan.destroyed.map(o$1=>jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:e,children:"-"}),jsx(Text,{color:l,children:o$1.slug}),jsxs(Text,{color:o,children:[o$1.type==="surface"?"DEACTIVATE":"DELETE"," CANDIDATE (",I(o$1),")"]})]}),o$1.renameHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{color:d,children:[y," Rename hint: ",o$1.renameHint]})})]},o$1.slug))]})]}),e$1.plan.destroyed.length>0&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:d,children:y}),jsx(Text,{color:l,children:"Missing resources:"}),jsx(Text,{color:c$1?e:c,bold:true,children:c$1?"delete":"keep active"})]}),!e$1.allowDestroy&&jsx(Text,{color:o,children:"Press d to delete all, k to keep active."}),c$1&&jsx(Box,{flexDirection:"column",marginTop:1,children:e$1.plan.destroyed.map(o=>jsxs(Text,{color:e,children:["- ",o.slug,": ",P(o)]},`delete-detail-${o.slug}`))})]}),jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:o,children:"Deploy to "}),jsx(Text,{color:l,bold:true,children:e$1.env}),jsx(Text,{color:o,children:"?"}),jsx(Text,{color:a$2,bold:true,children:"[y/N]"})]})]}),e$1.type==="applying"&&jsx(Box,{paddingLeft:2,children:jsx(a$1,{label:"Applying\u2026"})}),e$1.type==="no_changes"&&jsx(Box,{paddingLeft:2,children:jsx(a$3.Dim,{children:"Nothing to deploy. All resources are up to date."})}),e$1.type==="aborted"&&e$1.reason==="user_cancelled"&&jsx(Box,{paddingLeft:2,children:jsx(a$3.Dim,{children:"Deployment cancelled."})}),e$1.type==="aborted"&&e$1.reason==="allow_destroy_required"&&jsx(Box,{paddingLeft:2,children:jsx(a$3.Dim,{children:"Aborted. Re-run with --allow-destroy to confirm destructive changes."})}),e$1.type==="error"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,children:[jsx(a$3.Err,{children:e$1.message}),e$1.detail&&jsx(a$3.Dim,{children:e$1.detail})]}),e$1.type==="success"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,gap:1,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:c,children:w}),jsxs(Text,{color:l,bold:true,children:["Deployed to ",e$1.env]})]}),jsx(a$4,{variant:"ok",content:[{k:"created",v:jsxs(Text,{color:l,children:[e$1.created," resource(s)"]})},{k:"versioned",v:jsxs(Text,{color:l,children:[e$1.versioned," resource(s)"]})},{k:"destroyed",v:jsxs(Text,{color:l,children:[e$1.destroyed," resource(s)"]})}]}),jsxs(Box,{flexDirection:"column",children:[(e$1.createdItems||[]).map(o=>jsxs(Text,{color:c,children:["+ ",o.slug]},`created-${o.slug}`)),(e$1.versionedItems||[]).map(o=>jsxs(Text,{color:a$2,children:["~ ",o.slug]},`versioned-${o.slug}`)),(e$1.destroyedItems||[]).map(o=>jsxs(Text,{color:e,children:["- ",o.slug]},`destroyed-${o.slug}`)),(e$1.skippedDestroyedItems||[]).map(o$1=>jsxs(Text,{color:o,children:["k ",o$1.slug]},`skipped-${o$1.slug}`))]})]})]})}export{G as DeployView};
|
package/dist/DevView-SOPAMSZ4.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {a}from'./chunk-R67TA4FU.js';import {a as a$2}from'./chunk-FQVHJUX4.js';import {a as a$1}from'./chunk-JYNOILCD.js';import'./chunk-57XLDHK6.js';import {w,c,l,o,a as a$3,y,d}from'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import {useEffect}from'react';import {useApp,Box,Text}from'ink';import {jsxs,jsx}from'react/jsx-runtime';function C({state:o$1}){let{exit:g}=useApp();return useEffect(()=>{if(o$1.type==="error"||o$1.type==="disconnected"){let r=setTimeout(()=>g(),100);return ()=>clearTimeout(r)}},[o$1.type,g]),jsxs(Box,{flexDirection:"column",children:[jsx(a,{command:"culvii",subcommand:"dev"}),o$1.type==="provisioning"&&jsx(Box,{paddingLeft:2,children:jsx(a$1,{label:o$1.message})}),o$1.type==="error"&&jsx(Box,{flexDirection:"column",paddingLeft:2,children:jsx(a$2.Err,{children:o$1.message})}),o$1.type==="disconnected"&&jsx(Box,{paddingLeft:2,children:jsx(a$2.Dim,{children:"Disconnected. Draft state discarded."})}),o$1.type==="connected"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,gap:1,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:c,children:w}),jsx(Text,{color:l,bold:true,children:o$1.workspace}),jsx(Text,{color:o,children:"\xB7"}),jsx(Text,{color:a$3,children:o$1.env})]}),jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:o,children:"Console:"}),jsx(Text,{color:a$3,children:o$1.consoleUrl})]}),jsx(a$2.Dim,{children:"Watching ./..."}),jsx(Box,{flexDirection:"column",gap:0,children:o$1.log.map((r,y$1)=>jsxs(Box,{flexDirection:"row",gap:1,children:[r.type==="synced"&&jsx(Text,{color:c,children:w}),r.type==="orphaned"&&jsx(Text,{color:c,children:w}),(r.type==="warning"||r.type==="error")&&jsx(Text,{color:d,children:y}),r.type==="info"&&jsx(Text,{color:o,children:"\xB7"}),r.timestamp&&jsxs(Text,{color:o,children:["[",r.timestamp,"]"]}),jsx(Text,{color:r.type==="warning"||r.type==="error"?d:o,children:r.message})]},y$1))})]})]})}export{C as DevView};
|
package/dist/EnvView-MCZC2NBO.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {a as a$2}from'./chunk-MPKGJC7N.js';import {a}from'./chunk-R67TA4FU.js';import {a as a$1}from'./chunk-FQVHJUX4.js';import {l,e,o,w as w$1,c,x as x$1}from'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import {useEffect}from'react';import {useApp,Box,Text}from'ink';import {jsxs,jsx}from'react/jsx-runtime';function D(e){return e==="prod"?"allow":e==="sandbox"?"warn":"info"}function x({env:e}){return jsx(a$2,{variant:D(e),children:e})}function w({envs:e}){return e.length===0?jsx(Text,{color:o,children:"none"}):jsx(Box,{flexDirection:"row",gap:1,children:e.map(t=>jsx(x,{env:t},t))})}function C({state:e$1}){let{exit:t}=useApp();return useEffect(()=>{let v=setTimeout(()=>t(),100);return ()=>clearTimeout(v)},[t]),jsxs(Box,{flexDirection:"column",children:[jsx(a,{command:"culvii",subcommand:"env"}),e$1.type==="show"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,gap:1,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:l,children:"current"}),jsx(x,{env:e$1.current}),!e$1.accessible.includes(e$1.current)&&jsx(Text,{color:e,children:"(no access)"})]}),jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:o,children:"tenant:"}),jsx(Text,{color:l,children:e$1.tenant})]}),jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:o,children:"available:"}),jsx(w,{envs:e$1.accessible})]}),!e$1.accessible.includes(e$1.current)&&e$1.accessible.length>0&&jsxs(a$1.Dim,{children:["To switch, run: culvii env ",e$1.accessible[0]]})]}),e$1.type==="success"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,gap:1,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:c,children:w$1}),jsx(Text,{color:l,bold:true,children:"Switched environment to"}),jsx(x,{env:e$1.env})]}),jsxs(a$1.Dim,{children:["tenant: ",e$1.tenant]})]}),e$1.type==="error"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:e,children:x$1}),jsx(Text,{color:l,children:e$1.message})]}),e$1.detail&&jsx(Box,{paddingLeft:2,children:jsx(a$1.Dim,{children:e$1.detail})})]})]})}export{C as EnvView};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {a as a$4}from'./chunk-MPKGJC7N.js';import {a as a$3}from'./chunk-5NBKYMD7.js';import {a}from'./chunk-R67TA4FU.js';import {a as a$2}from'./chunk-FQVHJUX4.js';import {a as a$1}from'./chunk-JYNOILCD.js';import'./chunk-57XLDHK6.js';import {x,e,l,w,c,o}from'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import {useEffect}from'react';import {useApp,Box,Text}from'ink';import {jsxs,jsx}from'react/jsx-runtime';function B(o){return o==="prod"?"allow":o==="sandbox"?"warn":"info"}function G({state:o$1}){let{exit:a$5}=useApp();return useEffect(()=>{if(o$1.type!=="loading"){let u=setTimeout(()=>a$5(),100);return ()=>clearTimeout(u)}},[o$1.type,a$5]),jsxs(Box,{flexDirection:"column",children:[jsx(a,{command:"culvii",subcommand:"whoami"}),o$1.type==="loading"&&jsx(Box,{paddingLeft:2,children:jsx(a$1,{label:"Fetching identity\u2026"})}),o$1.type==="error"&&jsxs(Box,{flexDirection:"column",paddingLeft:2,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:e,children:x}),jsx(Text,{color:l,children:o$1.message})]}),o$1.detail&&jsx(Box,{paddingLeft:2,children:jsx(a$2.Dim,{children:o$1.detail})})]}),o$1.type==="success"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(Text,{color:c,children:w}),jsx(Text,{color:l,children:o$1.email})]}),jsx(a$3,{variant:"default",compact:true,content:[{k:"tenant",v:jsxs(Text,{color:l,children:[o$1.tenantName," ",jsxs(Text,{color:o,children:["(",o$1.tenant,")"]})]})},{k:"workspace",v:jsx(Text,{color:l,children:o$1.workspace||jsx(Text,{color:o,children:"none"})})},{k:"env",v:jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(a$4,{variant:B(o$1.env),children:o$1.env}),!o$1.envAccessible&&jsx(Text,{color:e,children:"(no access)"})]})},{k:"access",v:o$1.accessibleEnvs.length>0?jsx(Text,{color:l,children:o$1.accessibleEnvs.join(", ")}):jsx(Text,{color:o,children:"none"})},{k:"roles",v:o$1.roles.length>0?jsx(Text,{color:l,children:o$1.roles.join(", ")}):jsx(Text,{color:o,children:"none"})}]})]})]})}export{G as WhoamiView};
|
package/dist/chunk-MPKGJC7N.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {p,o,j,f as f$1,k,a,h,d,i,e,g,c}from'./chunk-YKFGEPLO.js';import {Box,Text}from'ink';import {jsx}from'react/jsx-runtime';var f={allow:{color:c,backgroundColor:g},healthy:{color:c,backgroundColor:g},deny:{color:e,backgroundColor:i},blocked:{color:e,backgroundColor:i},warn:{color:d,backgroundColor:h},throttled:{color:d,backgroundColor:h},accent:{color:a,backgroundColor:k},info:{color:f$1,backgroundColor:j},draft:{color:o,backgroundColor:p}};function T({variant:G,children:N}){let e=f[G];return jsx(Box,{flexDirection:"row",children:jsx(Box,{paddingX:1,backgroundColor:e.backgroundColor,children:jsx(Text,{color:e.color,bold:true,children:N})})})}export{T as a};
|
package/dist/chunk-WB3426JN.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {a}from'./chunk-HX54IFSD.js';import {Analytics}from'@segment/analytics-node';var h={CLI_INSTALLED:"cli_installed",CLI_VERSION_VIEWED:"cli_version_viewed",CLI_HELP_VIEWED:"cli_help_viewed",CLI_UNHANDLED_ERROR:"cli_unhandled_error",LOGIN_STARTED:"login_started",LOGIN_SUCCEEDED:"login_succeeded",LOGIN_FAILED:"login_failed",LOGOUT:"logout",DEV_STARTED:"dev_started",DEV_STOPPED:"dev_stopped",DEV_FAILED:"dev_failed",DEPLOY_STARTED:"deploy_started",DEPLOY_SUCCEEDED:"deploy_succeeded",DEPLOY_FAILED:"deploy_failed",DEPLOY_ABORTED:"deploy_aborted",API_KEY_CREATED:"api_key_created",API_KEY_LISTED:"api_key_listed",API_KEY_REVOKED:"api_key_revoked",API_KEY_ROTATED:"api_key_rotated",API_KEY_CREATE_FAILED:"api_key_create_failed",API_KEY_LIST_FAILED:"api_key_list_failed",API_KEY_ROTATE_FAILED:"api_key_rotate_failed",API_KEY_REVOKE_FAILED:"api_key_revoke_failed",TENANT_SWITCHED:"tenant_switched",ENV_SWITCHED:"env_switched",ENV_SWITCH_FAILED:"env_switch_failed",WORKSPACE_CREATED:"workspace_created",WORKSPACE_LISTED:"workspace_listed",TENANT_SWITCH_FAILED:"tenant_switch_failed",WORKSPACE_CREATE_FAILED:"workspace_create_failed",WORKSPACE_LIST_FAILED:"workspace_list_failed",WHOAMI_VIEWED:"whoami_viewed",RENAME_STARTED:"rename_started",RENAME_SUCCEEDED:"rename_succeeded",RENAME_FAILED:"rename_failed",INIT_STARTED:"init_started",INIT_SUCCEEDED:"init_succeeded",INIT_FAILED:"init_failed"},D="byn3jQco5axUIlfeohbQYYPGrZgGpw7A",x=process.env.CULVII_TELEMETRY!=="false",r=x?new Analytics({writeKey:D,flushAt:1,flushInterval:0}):null;function g(){return {surface:"cli",cli_version:"0.0.5",node_version:process.version,os:process.platform,arch:process.arch}}var c=null;async function w(){if(c)return c;try{let{ConfigStore:n}=await import('./config-store-WSXGIIJ4.js');c=(await new n().read({exitOnError:!1})).anonymousId??"unknown";}catch{c="unknown";}return c}var d=null,E=null,f=false;function U(){f=false;}async function y(){if(f)return {userId:d,tenantId:E};try{let{ConfigStore:n}=await import('./config-store-WSXGIIJ4.js'),e=await new n().read({exitOnError:!1}),i=e.contexts[e.active];E=i?.tenant_id??null,d=i?.user_id??e.anonymousId??null;}catch{d=null,E=null;}finally{f=true;}return {userId:d,tenantId:E}}async function C(n,t={},e,i){if(r)try{let o=await y(),a=e??o.userId,s=i!==void 0?i:o.tenantId,_=await w();a?r.track({userId:a,event:n,properties:{...g(),...s?{tenant_id:s}:{},...t}}):r.track({anonymousId:_,event:n,properties:{...g(),...t}});}catch{}}async function V(n,t,e,i={}){await C(n,i,t,e);}async function b(n,t={}){if(r)try{r.identify({userId:n,traits:t});}catch{}}async function F(n,t){if(r)try{r.alias({userId:n,previousId:t});}catch{}}async function K(n,t,e={}){if(r)try{r.group({userId:n,groupId:t,traits:e});}catch{}}var l=null;async function p(){if(r)return l||(l=r.flush({timeout:3e3}).catch(()=>{}).finally(()=>{l=null;}),l)}var u={dev:"development",sandbox:"sandbox",prod:"production"};function k(n){let t=Object.entries(u).find(([,e])=>e===n);return t?t[0]:null}var L=["dev","sandbox","prod"];function W(n){let t=new Set(n.map(k).filter(e=>e!==null));return L.find(e=>t.has(e))??null}var v;function G(n){v=n&&n in u?n:void 0;}function H(){return v}var R="https://api.platform.culvii.com",S={apiBaseUrl:R,clientId:"7fklt2iomn19epdbhpmfblk820",cognitoDomain:"culvii-console.auth.us-east-2.amazoncognito.com"},I=process.env.CULVII_ENV,N=I&&I in u?I:"dev",O={...S,logicalEnvironment:N,scopes:["openid","email","profile"],callbackPorts:[52700,52701,52702,52703,52704,52705,52706,52707,52708,52709],callbackPath:"/callback"};async function M(n){let e=await new a().read(),i=e.contexts[e.active];i||(console.error("Error: Active context key not found in contexts in ~/.culvii/config."),console.error("Please run `culvii login` to authenticate and configure your active context."),await p(),process.exit(1));let o={...i},a$1=n?.env??v;a$1&&(o.environment=a$1);let s=o.environment||"dev";o.environment_id=o.environment_ids?.[s]??o.environment_id,o.workspace_ids&&s in o.workspace_ids&&(o.workspace_id=o.workspace_ids[s]??null),o.workspace_slugs&&s in o.workspace_slugs&&(o.workspace_slug=o.workspace_slugs[s]??null),n?.workspace&&(o.workspace_id=n.workspace);let _=O.apiBaseUrl;return _||(console.error("Error: No API URL found for the configured platform."),await p(),process.exit(1)),{apiUrl:_,context:o}}function j(n){let t=n.environment||"dev",e=n.environment_ids?.[t]??n.environment_id;return {...n.tenant_id?{"x-tenant-id":n.tenant_id}:{},...e?{"x-environment-id":e}:{"x-environment-slug":u[t]}}}
|
|
3
|
-
export{h as a,w as b,U as c,y as d,C as e,V as f,b as g,F as h,K as i,p as j,u as k,k as l,W as m,G as n,H as o,N as p,O as q,M as r,j as s};
|