secureagentbase 1.2.13

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.
@@ -0,0 +1,151 @@
1
+ import { gcpFetch, createServiceAccount, grantRole } from './gcp.js';
2
+ export async function githubFetch(pat, path, opts) {
3
+ const response = await fetch(`https://api.github.com${path}`, {
4
+ method: opts?.method || 'GET',
5
+ headers: {
6
+ 'Authorization': `Bearer ${pat}`,
7
+ 'Accept': 'application/vnd.github.v3+json',
8
+ 'Content-Type': 'application/json',
9
+ },
10
+ body: opts?.body ? JSON.stringify(opts.body) : undefined,
11
+ });
12
+ if (!response.ok) {
13
+ const err = await response.text().catch(() => response.statusText);
14
+ throw new Error(`GitHub API error (${response.status}): ${err}`);
15
+ }
16
+ if (response.status === 204)
17
+ return {};
18
+ const text = await response.text();
19
+ return text ? JSON.parse(text) : {};
20
+ }
21
+ export async function validatePat(pat) {
22
+ const user = await githubFetch(pat, '/user');
23
+ const response = await fetch('https://api.github.com/user', {
24
+ headers: { 'Authorization': `Bearer ${pat}` },
25
+ });
26
+ const scopes = (response.headers.get('x-oauth-scopes') || '').split(',').map((s) => s.trim());
27
+ return { login: user.login, scopes };
28
+ }
29
+ export async function ensureRepo(pat, repoFull) {
30
+ const [owner, repo] = repoFull.split('/');
31
+ try {
32
+ await githubFetch(pat, `/repos/${repoFull}`);
33
+ }
34
+ catch (e) {
35
+ if (e.message?.includes('404')) {
36
+ await githubFetch(pat, '/user/repos', {
37
+ method: 'POST',
38
+ body: {
39
+ name: repo,
40
+ description: 'Created by SecureAgentBase',
41
+ private: false,
42
+ auto_init: true,
43
+ license_template: 'apache-2.0',
44
+ },
45
+ });
46
+ }
47
+ else {
48
+ throw e;
49
+ }
50
+ }
51
+ }
52
+ export async function setGitHubVariable(pat, repoFull, name, value) {
53
+ if (!value)
54
+ return;
55
+ try {
56
+ await githubFetch(pat, `/repos/${repoFull}/actions/variables`, {
57
+ method: 'POST',
58
+ body: { name, value },
59
+ });
60
+ }
61
+ catch {
62
+ await githubFetch(pat, `/repos/${repoFull}/actions/variables/${name}`, {
63
+ method: 'PATCH',
64
+ body: { name, value },
65
+ });
66
+ }
67
+ }
68
+ export async function setupOidc(auth, projectId, repoFullName) {
69
+ const poolId = 'firebase-deploy-pool';
70
+ const providerId = 'github-provider';
71
+ const poolName = `projects/${projectId}/locations/global/workloadIdentityPools/${poolId}`;
72
+ const providerName = `projects/${projectId}/locations/global/workloadIdentityPools/${poolId}/providers/${providerId}`;
73
+ // Create WIF pool (handle 409 already exists, 403 permission denied if pool exists from prior run)
74
+ try {
75
+ await gcpFetch(auth, `https://iam.googleapis.com/v1/projects/${projectId}/locations/global/workloadIdentityPools?workloadIdentityPoolId=${poolId}`, {
76
+ method: 'POST',
77
+ body: { displayName: 'Firebase Deploy Pool' },
78
+ });
79
+ }
80
+ catch (e) {
81
+ if (!e.message?.includes('409') && !e.message?.includes('ALREADY_EXISTS') && !e.message?.includes('PERMISSION_DENIED'))
82
+ throw e;
83
+ }
84
+ // Create WIF provider
85
+ try {
86
+ await gcpFetch(auth, `https://iam.googleapis.com/v1/projects/${projectId}/locations/global/workloadIdentityPools/${poolId}/providers?workloadIdentityPoolProviderId=${providerId}`, {
87
+ method: 'POST',
88
+ body: {
89
+ displayName: 'GitHub Actions',
90
+ attributeMapping: {
91
+ 'google.subject': 'assertion.sub',
92
+ 'attribute.actor': 'assertion.actor',
93
+ 'attribute.repository': 'assertion.repository',
94
+ 'attribute.ref': 'assertion.ref',
95
+ },
96
+ attributeCondition: `assertion.repository == '${repoFullName}'`,
97
+ oidc: { issuerUri: 'https://token.actions.githubusercontent.com' },
98
+ },
99
+ });
100
+ }
101
+ catch (e) {
102
+ if (!e.message?.includes('409') && !e.message?.includes('ALREADY_EXISTS') && !e.message?.includes('PERMISSION_DENIED'))
103
+ throw e;
104
+ // Update attribute condition if provider exists
105
+ try {
106
+ await gcpFetch(auth, `https://iam.googleapis.com/v1/projects/${projectId}/locations/global/workloadIdentityPools/${poolId}/providers/${providerId}?updateMask=attributeCondition`, {
107
+ method: 'PATCH',
108
+ body: { attributeCondition: `assertion.repository == '${repoFullName}'` },
109
+ });
110
+ }
111
+ catch {
112
+ // May not have permission to update either — that's fine
113
+ }
114
+ }
115
+ // Create deploy service accounts
116
+ const { email: saStagingEmail } = await createServiceAccount(auth, projectId, 'firebase-deploy-staging', 'Firebase Deploy Staging');
117
+ const { email: saProductionEmail } = await createServiceAccount(auth, projectId, 'firebase-deploy-prod', 'Firebase Deploy Production');
118
+ // Grant roles on the project (best-effort — deploy SA may not have permission)
119
+ for (const saEmail of [saStagingEmail, saProductionEmail]) {
120
+ const member = `serviceAccount:${saEmail}`;
121
+ await grantRole(auth, `projects/${projectId}`, member, 'roles/firebase.admin').catch(() => { });
122
+ await grantRole(auth, `projects/${projectId}`, member, 'roles/datastore.owner').catch(() => { });
123
+ await grantRole(auth, `projects/${projectId}`, member, 'roles/serviceusage.serviceUsageConsumer').catch(() => { });
124
+ await grantRole(auth, `projects/${projectId}`, member, 'roles/iam.workloadIdentityPoolAdmin').catch(() => { });
125
+ await grantRole(auth, `projects/${projectId}`, member, 'roles/iam.securityAdmin').catch(() => { });
126
+ await grantRole(auth, `projects/${projectId}`, member, 'roles/serviceusage.serviceUsageAdmin').catch(() => { });
127
+ // Grant pool impersonation (best-effort)
128
+ const poolMember = `principalSet://iam.googleapis.com/${poolName}/attribute.repository/${repoFullName}`;
129
+ try {
130
+ const saUrl = `projects/${projectId}/serviceAccounts/${saEmail}`;
131
+ const policyUrl = `https://iam.googleapis.com/v1/${saUrl}:getIamPolicy`;
132
+ const policy = await gcpFetch(auth, policyUrl, { method: 'POST' });
133
+ const bindings = policy.bindings || [];
134
+ const existing = bindings.find((b) => b.role === 'roles/iam.workloadIdentityUser');
135
+ if (!existing) {
136
+ bindings.push({ role: 'roles/iam.workloadIdentityUser', members: [poolMember] });
137
+ }
138
+ else if (!existing.members.includes(poolMember)) {
139
+ existing.members.push(poolMember);
140
+ }
141
+ await gcpFetch(auth, `https://iam.googleapis.com/v1/${saUrl}:setIamPolicy`, {
142
+ method: 'POST',
143
+ body: { policy: { bindings, etag: policy.etag } },
144
+ });
145
+ }
146
+ catch {
147
+ // May already be set or may lack permission — that's fine
148
+ }
149
+ }
150
+ return { wifPoolName: poolName, wifProviderName: providerName, saStagingEmail, saProductionEmail };
151
+ }
@@ -0,0 +1 @@
1
+ export declare const getStartupScript: () => string;
@@ -0,0 +1,9 @@
1
+ // CLI startup script — auto-generated from shared/startup-script.sh
2
+ // Do not edit directly. Run `npm run generate` to regenerate.
3
+ import { readFileSync } from 'fs';
4
+ import { join, dirname } from 'path';
5
+ import { fileURLToPath } from 'url';
6
+ export const getStartupScript = () => {
7
+ const dir = dirname(fileURLToPath(import.meta.url));
8
+ return readFileSync(join(dir, 'startup-script.sh'), 'utf-8');
9
+ };
@@ -0,0 +1,452 @@
1
+ #!/bin/bash
2
+ # SecureAgentBase VM Startup Script
3
+ # Shared between web wizard (src/framework/infra-setup/scripts.ts) and CLI (cli/src/lib/startup-script.ts)
4
+ # Keep in sync — do not edit one without the other.
5
+ set +e
6
+ export HOME=/root
7
+ export DEBIAN_FRONTEND=noninteractive
8
+ # Fetch GitHub repo from metadata or use fallback
9
+ GITHUB_REPO=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/github_repo" -H "Metadata-Flavor: Google")
10
+ if [ -n "$GITHUB_REPO" ]; then
11
+ REPO_OWNER=$(echo "$GITHUB_REPO" | cut -d'/' -f1)
12
+ REPO_NAME=$(echo "$GITHUB_REPO" | cut -d'/' -f2)
13
+ if [[ ! "$REPO_NAME" =~ ^[A-Za-z0-9._-]+$ ]] || [[ ! "$REPO_OWNER" =~ ^[A-Za-z0-9._-]+$ ]]; then
14
+ echo "WARNING: Invalid github_repo metadata, using SecureAgentBase as default"
15
+ REPO_OWNER="kallhoffa"
16
+ REPO_NAME="SecureAgentBase"
17
+ fi
18
+ else
19
+ echo "WARNING: No github_repo metadata set, using SecureAgentBase as default"
20
+ REPO_OWNER="kallhoffa"
21
+ REPO_NAME="SecureAgentBase"
22
+ fi
23
+ FIREBASE_STAGING=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/firebase_staging" -H "Metadata-Flavor: Google")
24
+ FIREBASE_PRODUCTION=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/firebase_production" -H "Metadata-Flavor: Google")
25
+ GITHUB_PAT=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/github_pat" -H "Metadata-Flavor: Google")
26
+ DISCORD_BOT_TOKEN=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/discord_bot_token" -H "Metadata-Flavor: Google")
27
+ DISCORD_GUILD_ID=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/discord_guild_id" -H "Metadata-Flavor: Google")
28
+ GCP_WIF_PROVIDER=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/gcp_wif_provider" -H "Metadata-Flavor: Google")
29
+ GCP_SA_STAGING=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/gcp_sa_staging" -H "Metadata-Flavor: Google")
30
+ GCP_SA_PRODUCTION=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/gcp_sa_production" -H "Metadata-Flavor: Google")
31
+ FIREBASE_STAGING_CONFIG=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/firebase_staging_config" -H "Metadata-Flavor: Google")
32
+ FIREBASE_PRODUCTION_CONFIG=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/firebase_production_config" -H "Metadata-Flavor: Google")
33
+ VITE_APP_NAME=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/vite_app_name" -H "Metadata-Flavor: Google")
34
+ GCP_SA_KEY=$(curl -sf "http://metadata.google.internal/computeMetadata/v1/instance/attributes/gcp_sa_key" -H "Metadata-Flavor: Google")
35
+
36
+ # Clean up any potential HTML responses from failed requests or unconfigured metadata
37
+ for var in FIREBASE_STAGING FIREBASE_PRODUCTION GITHUB_PAT DISCORD_BOT_TOKEN DISCORD_GUILD_ID GCP_WIF_PROVIDER GCP_SA_STAGING GCP_SA_PRODUCTION FIREBASE_STAGING_CONFIG FIREBASE_PRODUCTION_CONFIG VITE_APP_NAME GCP_SA_KEY; do
38
+ val=${!var}
39
+ if [[ "$val" =~ "<html" || "$val" =~ "<!" || "$val" =~ "<HTML" ]]; then
40
+ eval "$var=\"\""
41
+ fi
42
+ done
43
+
44
+ # Idempotency guard — GCP re-runs the startup script on EVERY boot, not just first boot.
45
+ # Skip all provisioning steps if this VM was already set up, so reboots are harmless.
46
+ if [ -f /root/.kimaki/.provisioned ]; then
47
+ echo "Already provisioned, skipping startup script"
48
+ echo "ALREADY_PROVISIONED" > /dev/ttyS0 2>/dev/null || true
49
+ exit 0
50
+ fi
51
+
52
+ echo "REPO_OWNER=$REPO_OWNER | FIREBASE_STAGING=$FIREBASE_STAGING"
53
+
54
+ # Disk space guard — warn via serial console well before the disk fills up.
55
+ # Large installs (apt, node tarball, npm -g) silently fail with ENOSPC at 100%.
56
+ check_disk() {
57
+ DISK_USED_PCT=$(df -P / | awk 'NR==2 {gsub("%","",$5); print $5}')
58
+ DISK_AVAIL_MB=$(df -P / | awk 'NR==2 {print int($4/1024)}')
59
+ if [ -n "$DISK_USED_PCT" ] && [ "$DISK_USED_PCT" -ge 85 ]; then
60
+ echo "KIMAKI_DISK_ALERT:${DISK_USED_PCT}pct used on root filesystem (${DISK_AVAIL_MB} MB free)" > /dev/ttyS0 2>/dev/null || true
61
+ echo "WARNING: disk ${DISK_USED_PCT}% full, only ${DISK_AVAIL_MB} MB free" >&2
62
+ fi
63
+ }
64
+ check_disk
65
+
66
+ sudo apt-get update -y > /dev/null 2>&1 || true
67
+ sudo apt-get install -y curl git jq apt-transport-https ca-certificates gnupg2 ufw unzip > /dev/null 2>&1 || true
68
+
69
+ # Install Node.js 20.x — pinned binary release with checksum verification
70
+ NODE_VERSION="20.18.0"
71
+ NODE_TARBALL="node-v${NODE_VERSION}-linux-x64.tar.gz"
72
+ curl -fsSL "https://nodejs.org/dist/v${NODE_VERSION}/${NODE_TARBALL}" -o "/tmp/${NODE_TARBALL}" > /dev/null 2>&1 || true
73
+ curl -fsSL "https://nodejs.org/dist/v${NODE_VERSION}/SHASUMS256.txt" -o /tmp/SHASUMS256.txt > /dev/null 2>&1 || true
74
+ if (cd /tmp && sha256sum -c SHASUMS256.txt --ignore-missing --status 2>/dev/null); then
75
+ tar -xzf "/tmp/${NODE_TARBALL}" -C /usr/local --strip-components=1 2>/dev/null
76
+ export PATH="/usr/local/bin:$PATH"
77
+ echo "Node.js ${NODE_VERSION} installed from binary"
78
+ else
79
+ echo "WARNING: Node.js checksum verification failed, falling back to apt"
80
+ apt-get install -y nodejs > /dev/null 2>&1 || true
81
+ fi
82
+
83
+ # Install GitHub CLI
84
+ type gh >/dev/null 2>&1 || (curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg 2>/dev/null && echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null && sudo apt-get update -y > /dev/null 2>&1 && sudo apt-get install -y gh > /dev/null 2>&1) || true
85
+
86
+ # Install Kimaki (skip if already installed — re-running npm -g installs crashes with ENOTEMPTY)
87
+ if command -v kimaki >/dev/null 2>&1; then
88
+ echo "kimaki already installed, skipping global install"
89
+ else
90
+ npm install -g kimaki@latest > /dev/null 2>&1 || true
91
+ fi
92
+
93
+ # Clone the SecureAgentBase template repository into Kimaki's projects dir
94
+ # so kimaki can detect/register it as a project
95
+ mkdir -p /root/.kimaki/projects
96
+ cd /root/.kimaki/projects
97
+
98
+ # Force HTTP/1.1 to avoid GitHub HTTP/2 curl 92 errors on large repos
99
+ git config --global http.version HTTP/1.1
100
+ git config --global http.postBuffer 524288000
101
+
102
+ # Reuse an existing clone on re-runs ("destination path already exists" otherwise)
103
+ if [ -d "$REPO_NAME/.git" ]; then
104
+ echo "Project already cloned, reusing existing checkout"
105
+ cd "$REPO_NAME"
106
+ REPO_CLONED=true
107
+ else
108
+ REPO_CLONED=false
109
+ for i in 1 2 3; do
110
+ if git clone --depth 1 "https://github.com/$REPO_OWNER/$REPO_NAME.git" "$REPO_NAME" > /dev/null 2>&1; then
111
+ REPO_CLONED=true
112
+ break
113
+ fi
114
+ sleep 5
115
+ done
116
+
117
+ # If clone failed, fall back to creating directory manually
118
+ if [ "$REPO_CLONED" != "true" ]; then
119
+ mkdir -p "$REPO_NAME"
120
+ cd "$REPO_NAME"
121
+ git init
122
+ echo "placeholder" > README.md
123
+ cat > .gitignore << 'GITEOF'
124
+ node_modules/
125
+ .env*
126
+ dist/
127
+ build/
128
+ *.log
129
+ GITEOF
130
+ else
131
+ cd "$REPO_NAME"
132
+ rm -rf .git
133
+ git init
134
+ fi
135
+ fi
136
+
137
+ git checkout -b main
138
+
139
+ # Clean up wizard-specific files — users don't need the infra setup wizard
140
+ rm -rf src/infra-setup.tsx src/create-app.tsx
141
+ rm -rf src/framework/infra-setup/
142
+ rm -rf src/admin/
143
+ rm -rf cli/
144
+ rm -rf tests/e2e/wizard.spec.js
145
+ rm -rf src/_tests_/WizardSteps.test.jsx src/_tests_/create-app.test.tsx src/_tests_/StepHeader.test.jsx src/_tests_/api.test.ts src/_tests_/crypto.test.ts src/_tests_/scripts.test.ts
146
+ rm -f WIZARD_DEV_NOTES.md
147
+
148
+ # Fix App.tsx: remove wizard/admin imports and routes
149
+ if [ -f src/App.tsx ]; then
150
+ # Remove import lines for InfraSetup, CreateApp, AdminPanel
151
+ sed -i "/import InfraSetup from '.\\/infra-setup';/d" src/App.tsx
152
+ sed -i "/import CreateApp from '.\\/create-app';/d" src/App.tsx
153
+ sed -i "/import AdminPanel from '.\\/admin\\/AdminPanel';/d" src/App.tsx
154
+ # Remove Route elements for /infra-setup, /create-app, /admin/*
155
+ sed -i '/<Route path="\\/infra-setup".*\\/>/d' src/App.tsx
156
+ sed -i '/<Route path="\\/create-app".*\\/>/d' src/App.tsx
157
+ sed -i '/<Route path="\\/admin/d' src/App.tsx
158
+ # Clean up orphaned {isAppMode && ()} blocks left behind after Route deletion
159
+ perl -i -0pe 's/\\{isAppMode && \\(\\s*\\n\\s*\\)\\}//gs' src/App.tsx
160
+ echo "App.tsx cleaned of wizard/admin references"
161
+ fi
162
+
163
+ # Fix navigation-bar.tsx: remove admin link and useIsAdmin import
164
+ if [ -f src/navigation-bar.tsx ]; then
165
+ sed -i "/import { useIsAdmin } from '.\\/admin\\/useIsAdmin';/d" src/navigation-bar.tsx
166
+ sed -i "/const { isAdmin } = useIsAdmin(db);/d" src/navigation-bar.tsx
167
+ # Delete from {isAdmin && to the next closing )} on its own line
168
+ sed -i '/{isAdmin &&/,/^[[:space:]]*)}/d' src/navigation-bar.tsx
169
+ echo "navigation-bar.tsx cleaned of admin references"
170
+ fi
171
+
172
+ # Write a CONTEXT.md scaffold for the domain-modeling/setup-project skills
173
+ if [ ! -f CONTEXT.md ]; then
174
+ cat > CONTEXT.md << 'CONTEXTEOF'
175
+ # Context
176
+
177
+ Glossary of this project's domain terms, maintained by the `domain-modeling` skill. Architectural decisions live in `docs/adr/`; run `/setup-project` to scaffold the issue tracker and ADR workflow.
178
+ CONTEXTEOF
179
+ fi
180
+
181
+ # Configure git
182
+ git config user.email "agent@secureagentbase.com"
183
+ git config user.name "SecureAgent Manager"
184
+
185
+ # Add and commit all files
186
+ git add .
187
+ git commit -m "Initial commit of SecureAgentBase template"
188
+
189
+ # Create GitHub repo and push
190
+ # Write diagnostics to /dev/ttyS0 (serial port 1) for external debugging
191
+ # and compact markers at the end that survive buffer overflow
192
+ check_disk
193
+ PUSH_RESULT="NOT_ATTEMPTED"
194
+ if [ -n "$GITHUB_PAT" ]; then
195
+ # Clear stale gh credentials first — a revoked PAT or old token causes 401s that
196
+ # persist across boots because gh caches the failed login state.
197
+ gh auth logout --hostname github.com 2>/dev/null || true
198
+ echo "$GITHUB_PAT" | gh auth login --with-token 2>/dev/null
199
+ gh auth setup-git 2>/dev/null || true
200
+
201
+ # Create new repo or force-push if it already exists
202
+ if gh repo view "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null; then
203
+ git remote remove origin 2>/dev/null || true
204
+ git remote add origin "https://github.com/${REPO_OWNER}/${REPO_NAME}.git" || true
205
+ if git push -u origin main --force 2>&1; then
206
+ PUSH_RESULT="PUSH_OK"
207
+ else
208
+ PUSH_RESULT="PUSH_FAILED"
209
+ fi
210
+ else
211
+ if gh repo create "${REPO_OWNER}/${REPO_NAME}" --public --source=. --push 2>&1; then
212
+ PUSH_RESULT="CREATE_OK"
213
+ else
214
+ # Fallback: try force-push (repo may exist but PAT can't view it)
215
+ git remote remove origin 2>/dev/null || true
216
+ git remote add origin "https://github.com/${REPO_OWNER}/${REPO_NAME}.git" || true
217
+ if git push -u origin main --force 2>&1; then
218
+ PUSH_RESULT="FALLBACK_PUSH_OK"
219
+ else
220
+ PUSH_RESULT="ALL_PUSH_FAILED"
221
+ fi
222
+ fi
223
+ fi
224
+
225
+ # Write push result marker to serial port (compact, survives buffer overflow)
226
+ echo "PUSH_RESULT=$PUSH_RESULT" > /dev/ttyS0 2>/dev/null || true
227
+
228
+ # Set GitHub variables
229
+ gh auth status 2>/dev/null || true
230
+
231
+ # Set Firebase project IDs as VARIABLES (workflow reads vars.FIREBASE_PROJECT_ID_STAGING)
232
+ gh variable set FIREBASE_PROJECT_ID_STAGING --body "$FIREBASE_STAGING" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || echo "WARN: Failed to set FIREBASE_PROJECT_ID_STAGING"
233
+ gh variable set FIREBASE_PROJECT_ID_PRODUCTION --body "$FIREBASE_PRODUCTION" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || echo "WARN: Failed to set FIREBASE_PROJECT_ID_PRODUCTION"
234
+
235
+ # Set OIDC variables (required by google-github-actions/auth)
236
+ [ -n "$GCP_WIF_PROVIDER" ] && gh variable set GCP_WIF_PROVIDER --body "$GCP_WIF_PROVIDER" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
237
+ [ -n "$GCP_SA_STAGING" ] && gh variable set GCP_SA_STAGING --body "$GCP_SA_STAGING" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
238
+ [ -n "$GCP_SA_PRODUCTION" ] && gh variable set GCP_SA_PRODUCTION --body "$GCP_SA_PRODUCTION" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
239
+
240
+ # Set VITE app variables
241
+ [ -n "$VITE_APP_NAME" ] && gh variable set VITE_APP_NAME --body "$VITE_APP_NAME" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
242
+
243
+ # Set Firebase config variables from JSON configs (parse with jq)
244
+ # Convert camelCase field names to SCREAMING_SNAKE_CASE for GitHub variable names
245
+ if [ -n "$FIREBASE_STAGING_CONFIG" ] && echo "$FIREBASE_STAGING_CONFIG" | jq -e . >/dev/null 2>&1; then
246
+ for field in apiKey authDomain projectId storageBucket messagingSenderId appId measurementId; do
247
+ val=$(echo "$FIREBASE_STAGING_CONFIG" | jq -r ".${field} // empty" 2>/dev/null)
248
+ if [ -n "$val" ]; then
249
+ upper_field=$(echo "${field}" | sed 's/\([a-z]\)\([A-Z]\)/\1_\2/g' | tr '[:lower:]' '[:upper:]')
250
+ gh variable set "FIREBASE_${upper_field}_STAGING" --body "$val" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
251
+ fi
252
+ done
253
+ fi
254
+
255
+ if [ -n "$FIREBASE_PRODUCTION_CONFIG" ] && echo "$FIREBASE_PRODUCTION_CONFIG" | jq -e . >/dev/null 2>&1; then
256
+ for field in apiKey authDomain projectId storageBucket messagingSenderId appId measurementId; do
257
+ val=$(echo "$FIREBASE_PRODUCTION_CONFIG" | jq -r ".${field} // empty" 2>/dev/null)
258
+ if [ -n "$val" ]; then
259
+ upper_field=$(echo "${field}" | sed 's/\([a-z]\)\([A-Z]\)/\1_\2/g' | tr '[:lower:]' '[:upper:]')
260
+ gh variable set "FIREBASE_${upper_field}_PRODUCTION" --body "$val" -R "${REPO_OWNER}/${REPO_NAME}" 2>/dev/null || true
261
+ fi
262
+ done
263
+ fi
264
+
265
+ echo "VAR_RESULT=DONE" > /dev/ttyS0 2>/dev/null || true
266
+ echo "GitHub variables set successfully" > /dev/null 2>&1
267
+ fi
268
+
269
+ # Install Kimaki globally and create its configuration
270
+ KIMAKI_CONFIG_DIR=/root/.kimaki
271
+ mkdir -p $KIMAKI_CONFIG_DIR
272
+ echo "$REPO_NAME" > "$KIMAKI_CONFIG_DIR/.project_name"
273
+ cat > $KIMAKI_CONFIG_DIR/config.yml << 'KIMAKICONF'
274
+ # Kimaki config - auto-generated
275
+ openai_api_key: ""
276
+ github_token: ""
277
+ KIMAKICONF
278
+
279
+ # Write opencode.json with provider timeout settings (chatty upstream models)
280
+ cat > "/root/.kimaki/projects/$REPO_NAME/opencode.json" << 'OPENCODEEOF'
281
+ {
282
+ "$schema": "https://opencode.ai/config.json",
283
+ "model": "opencode-go/kimi-k2.6",
284
+ "provider": {
285
+ "opencode-go": {
286
+ "options": {
287
+ "timeout": 300000,
288
+ "headerTimeout": 120000,
289
+ "chunkTimeout": 120000
290
+ }
291
+ }
292
+ }
293
+ }
294
+ OPENCODEEOF
295
+
296
+ # Install agent skills globally — opencode and Claude Code auto-discover these dirs.
297
+ SKILLS_DIR=/root/.config/opencode/skills
298
+ mkdir -p "$SKILLS_DIR" /tmp/sab-skills-tmp
299
+ # 1) Matt Pocock engineering skills (MIT licensed): tdd, code-review, diagnosing-bugs, research, prototype, etc.
300
+ if [ ! -d "$SKILLS_DIR/tdd" ] && git clone --depth 1 https://github.com/mattpocock/skills.git /tmp/sab-skills-tmp/matt-skills > /dev/null 2>&1; then
301
+ cp -r /tmp/sab-skills-tmp/matt-skills/skills/engineering/. "$SKILLS_DIR/" 2>/dev/null || true
302
+ fi
303
+ # 2) SecureAgentBase skills: reuse the local project copy, else clone the template repo.
304
+ if [ -d "/root/.kimaki/projects/$REPO_NAME/.opencode/skills" ]; then
305
+ cp -r "/root/.kimaki/projects/$REPO_NAME/.opencode/skills/." "$SKILLS_DIR/" 2>/dev/null || true
306
+ elif git clone --depth 1 https://github.com/kallhoffa/SecureAgentBase.git /tmp/sab-skills-tmp/sab > /dev/null 2>&1; then
307
+ cp -r /tmp/sab-skills-tmp/sab/.opencode/skills/. "$SKILLS_DIR/" 2>/dev/null || true
308
+ fi
309
+ # 3) Claude Code compatibility mirror.
310
+ mkdir -p /root/.claude/skills
311
+ cp -r "$SKILLS_DIR/." /root/.claude/skills/ 2>/dev/null || true
312
+ rm -rf /tmp/sab-skills-tmp
313
+
314
+ # Write sensitive env vars to a restricted file, referenced by systemd
315
+ cat > /root/.kimaki/env << ENVEOF
316
+ GITHUB_PAT=$GITHUB_PAT
317
+ KIMAKI_BOT_TOKEN=$DISCORD_BOT_TOKEN
318
+ DISCORD_BOT_TOKEN=$DISCORD_BOT_TOKEN
319
+ DISCORD_GUILD_ID=$DISCORD_GUILD_ID
320
+ FIREBASE_STAGING=$FIREBASE_STAGING
321
+ FIREBASE_PRODUCTION=$FIREBASE_PRODUCTION
322
+ NODE_ENV=production
323
+ ENVEOF
324
+ chmod 600 /root/.kimaki/env
325
+
326
+ # Write GCP service account key from metadata (if provided) to a restricted file
327
+ if [ -n "$GCP_SA_KEY" ]; then
328
+ echo "$GCP_SA_KEY" > /root/.kimaki/gcp-sa-key.json
329
+ chmod 600 /root/.kimaki/gcp-sa-key.json
330
+ fi
331
+
332
+ # Create systemd service for Kimaki (no-clobber — never overwrite a running unit)
333
+ KIMAKI_PATH=$(command -v kimaki || true)
334
+ if [ -z "$KIMAKI_PATH" ] || [ ! -x "$KIMAKI_PATH" ]; then
335
+ echo "KIMAKI_MISSING" > /dev/ttyS0 2>/dev/null || true
336
+ echo "WARNING: kimaki binary not found, defaulting to /usr/bin/kimaki" >&2
337
+ KIMAKI_PATH=/usr/bin/kimaki
338
+ fi
339
+ if [ ! -f /etc/systemd/system/kimaki.service ]; then
340
+ cat > /etc/systemd/system/kimaki.service << SERVICEEOF
341
+ [Unit]
342
+ Description=Kimaki Agent Service
343
+ After=network.target
344
+
345
+ [Service]
346
+ Type=simple
347
+ User=root
348
+ WorkingDirectory=/root/.kimaki/projects/$REPO_NAME
349
+ ExecStart=/usr/bin/node $KIMAKI_PATH
350
+ Restart=on-failure
351
+ RestartSec=10
352
+ EnvironmentFile=/root/.kimaki/env
353
+ Environment=NODE_ENV=production
354
+
355
+ [Install]
356
+ WantedBy=multi-user.target
357
+ SERVICEEOF
358
+
359
+ # Verify the ExecStart line actually references a script (an empty KIMAKI_PATH
360
+ # would write `ExecStart=/usr/bin/node` and exit status=0 in ~30ms).
361
+ grep -q "ExecStart=/usr/bin/node $KIMAKI_PATH" /etc/systemd/system/kimaki.service \
362
+ || echo "WARNING: kimaki.service ExecStart may be broken" >&2
363
+
364
+ systemctl daemon-reload
365
+ systemctl enable kimaki.service
366
+ systemctl start kimaki.service
367
+ else
368
+ echo "kimaki.service already exists, skipping re-write"
369
+ systemctl daemon-reload
370
+ systemctl restart kimaki.service
371
+ fi
372
+
373
+ # Create a separate script for project registration (more reliable than inline)
374
+ cat > /usr/local/bin/kimaki-register.sh << 'REGISTER_SCRIPT'
375
+ #!/bin/bash
376
+ set +e
377
+ export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/.bun/bin"
378
+ export HOME=/root
379
+
380
+ # Wait for kimaki to be ready
381
+ for i in $(seq 1 60); do
382
+ if systemctl is-active --quiet kimaki.service; then
383
+ echo "$(date): Kimaki is active, proceeding with registration..." >> /var/log/kimaki-register.log
384
+ break
385
+ fi
386
+ echo "$(date): Waiting for kimaki.service... attempt $i" >> /var/log/kimaki-register.log
387
+ sleep 5
388
+ done
389
+
390
+ # Determine KIMAKI_CMD
391
+ if command -v kimaki &> /dev/null; then
392
+ KIMAKI_CMD="kimaki"
393
+ else
394
+ KIMAKI_CMD="npx -y kimaki@latest"
395
+ fi
396
+
397
+ echo "$(date): Using KIMAKI_CMD: $KIMAKI_CMD" >> /var/log/kimaki-register.log
398
+
399
+ # Try to register the project (retries needed because OpenCode server needs time to start)
400
+ PROJECT_NAME=$(cat /root/.kimaki/.project_name 2>/dev/null || echo "SecureAgentBase")
401
+ # Skip if already registered (reboot-safe — project add fails non-zero when the channel exists)
402
+ if $KIMAKI_CMD project list --json 2>/dev/null | grep -q "$PROJECT_NAME"; then
403
+ echo "$(date): Project already registered, skipping" >> /var/log/kimaki-register.log
404
+ echo "KIMAKI_BOT_ONLINE" > /dev/ttyS0 2>/dev/null || true
405
+ exit 0
406
+ fi
407
+ for i in $(seq 1 30); do
408
+ echo "$(date): Attempting to register project (attempt $i)..." >> /var/log/kimaki-register.log
409
+ if $KIMAKI_CMD project add /root/.kimaki/projects/$PROJECT_NAME >> /var/log/kimaki-register.log 2>&1; then
410
+ echo "$(date): Project registered successfully!" >> /var/log/kimaki-register.log
411
+ # Signal to the wizard's serial port poller that the Discord bot is online
412
+ echo "KIMAKI_BOT_ONLINE" > /dev/ttyS0 2>/dev/null || true
413
+ exit 0
414
+ fi
415
+ echo "$(date): Attempt $i failed, retrying in 10s..." >> /var/log/kimaki-register.log
416
+ sleep 10
417
+ done
418
+
419
+ echo "$(date): Registration failed after 30 attempts" >> /var/log/kimaki-register.log
420
+ exit 1
421
+ REGISTER_SCRIPT
422
+
423
+ chmod +x /usr/local/bin/kimaki-register.sh
424
+
425
+ # Create project registration service
426
+ cat > /etc/systemd/system/kimaki-register.service << 'REGISTER_EOF'
427
+ [Unit]
428
+ Description=Register SecureAgentBase with Kimaki
429
+ After=kimaki.service
430
+
431
+ [Service]
432
+ Type=oneshot
433
+ User=root
434
+ ExecStart=/usr/local/bin/kimaki-register.sh
435
+ RemainAfterExit=yes
436
+
437
+ [Install]
438
+ WantedBy=multi-user.target
439
+ REGISTER_EOF
440
+
441
+ systemctl daemon-reload
442
+ systemctl enable kimaki-register.service
443
+
444
+ # Mark this VM as provisioned — GCP re-runs startup scripts on every boot,
445
+ # and the top-of-script guard skips everything once this marker exists.
446
+ touch /root/.kimaki/.provisioned
447
+
448
+ # Final compact marker — this is the LAST output before kimaki-register starts
449
+ # Non-sensitive status only — no secrets or project identifiers leaked
450
+ echo "SCRIPT_COMPLETE" > /dev/ttyS0 2>/dev/null || true
451
+
452
+ systemctl start kimaki-register.service &
@@ -0,0 +1,22 @@
1
+ export interface Config {
2
+ gcpProjectId?: string;
3
+ saEmail?: string;
4
+ saKeyPath?: string;
5
+ firebaseStaging?: Record<string, string>;
6
+ firebaseProduction?: Record<string, string>;
7
+ githubPat?: string;
8
+ githubRepo?: string;
9
+ discordBotToken?: string;
10
+ discordGuildId?: string;
11
+ vmIp?: string;
12
+ vmZone?: string;
13
+ oidc?: {
14
+ wifPoolName?: string;
15
+ wifProviderName?: string;
16
+ saStagingEmail?: string;
17
+ saProductionEmail?: string;
18
+ };
19
+ }
20
+ export declare function loadConfig(): Config;
21
+ export declare function saveConfig(config: Config): void;
22
+ export declare function clearConfig(): void;
@@ -0,0 +1,25 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import * as os from 'node:os';
4
+ const CONFIG_DIR = path.join(os.homedir(), '.secureagentbase');
5
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
6
+ export function loadConfig() {
7
+ try {
8
+ if (fs.existsSync(CONFIG_FILE)) {
9
+ return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf-8'));
10
+ }
11
+ }
12
+ catch (e) {
13
+ // Corrupted config, start fresh
14
+ }
15
+ return {};
16
+ }
17
+ export function saveConfig(config) {
18
+ fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
19
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { mode: 0o600 });
20
+ }
21
+ export function clearConfig() {
22
+ if (fs.existsSync(CONFIG_FILE)) {
23
+ fs.unlinkSync(CONFIG_FILE);
24
+ }
25
+ }
@@ -0,0 +1,4 @@
1
+ export declare class CLIError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ export declare function handleError(err: unknown): void;