Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(sandbox): inject per-user and workspace skill env vars at execution

hailongzhao188200e3b1a7
diff --git a/frontend/src/api/env-vars.ts b/frontend/src/api/env-vars.ts
new file mode 100644
index 000000000..5dc64c287
--- /dev/null
+++ b/frontend/src/api/env-vars.ts
@@ -0,0 +1,85 @@
+import { del, get, put } from '@/utils/request'
+
+/**
+ * Which value an execution would actually use for one variable.
+ *
+ * `unset` means nothing is stored anywhere, `workspace` means an admin filled
+ * it in for everyone, `user` means the caller filled in their own — which wins
+ * over the workspace one for this caller only.
+ */
+export type EnvVarSource = 'unset' | 'workspace' | 'user'
+
+/**
+ * One variable as its owner may see it. There is deliberately no value field:
+ * the endpoint reports what is missing, never what is stored.
+ */
+export interface EnvVarView {
+ name: string
+ description?: string
+ required?: boolean
+ source: EnvVarSource
+ /** Present only for the caller's own value; a workspace value has no per-variable timestamp. */
+ updated_at?: string
+}
+
+/** One skill's declared credentials. */
+export interface SkillEnvGroup {
+ skill_id: string
+ skill_name: string
+ vars: EnvVarView[]
+}
+
+/**
+ * One sandbox config: the caller's own config-wide variables, injected into
+ * every execution on it, plus the credentials its skills declared.
+ */
+export interface ConfigEnvGroup {
+ sandbox_config_id: string
+ sandbox_config_name: string
+ vars: EnvVarView[]
+ skills: SkillEnvGroup[]
+}
+
+export function listMyEnvVars(): Promise<{ data: ConfigEnvGroup[] }> {
+ return get('/api/v1/me/env-vars') as unknown as Promise<{ data: ConfigEnvGroup[] }>
+}
+
+export function setMySkillEnv(
+ skillId: string,
+ name: string,
+ value: string,
+): Promise<{ success: boolean }> {
+ return put('/api/v1/me/env-vars/skill', { skill_id: skillId, name, value }) as unknown as Promise<{
+ success: boolean
+ }>
+}
+
+/**
+ * Removes the caller's own value, after which the workspace value (if any)
+ * applies again. The scope and name travel in a JSON body rather than the query
+ * string, matching the PUT above.
+ */
+export function deleteMySkillEnv(skillId: string, name: string): Promise<{ success: boolean }> {
+ return del('/api/v1/me/env-vars/skill', { skill_id: skillId, name }) as unknown as Promise<{
+ success: boolean
+ }>
+}
+
+export function setMySandboxEnv(
+ configId: string,
+ name: string,
+ value: string,
+): Promise<{ success: boolean }> {
+ return put('/api/v1/me/env-vars/sandbox', {
+ sandbox_config_id: configId,
+ name,
+ value,
+ }) as unknown as Promise<{ success: boolean }>
+}
+
+export function deleteMySandboxEnv(configId: string, name: string): Promise<{ success: boolean }> {
+ return del('/api/v1/me/env-vars/sandbox', {
+ sandbox_config_id: configId,
+ name,
+ }) as unknown as Promise<{ success: boolean }>
+}
diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts
index 51760de11..127881046 100644
--- a/frontend/src/api/system/index.ts
+++ b/frontend/src/api/system/index.ts
@@ -1006,6 +1006,18 @@ export function parseSandboxConflict(err: unknown): SandboxConflict | null {
export type ConfigSkillStatus = 'installing' | 'ready' | 'failed' | 'removing' | 'removed'
+/**
+ * One environment variable the skill's installer declared. `is_set` reports
+ * whether a workspace-wide value exists; the value itself is never returned,
+ * so an editor can show that something is stored but not what.
+ */
+export interface ConfigSkillEnv {
+ name: string
+ description?: string
+ required?: boolean
+ is_set: boolean
+}
+
export interface ConfigSkill {
id: string
name: string
@@ -1023,6 +1035,9 @@ export interface ConfigSkill {
install_message_id?: string
created_at: string
updated_at: string
+ // Absent for a skill whose installer declared nothing, which is how the
+ // panel decides whether to offer the environment variable editor at all.
+ envs?: ConfigSkillEnv[]
}
export interface ConfigSkillInstallEvent {
@@ -1069,10 +1084,15 @@ export function reinstallConfigSkill(
) as unknown as Promise<{ data: { skill_id: string } }>
}
+/**
+ * Partial update: an absent field is left alone. `envs` names only the
+ * variables to write — an entry with an empty string clears the stored value
+ * while keeping the declaration, and undeclared names are ignored server-side.
+ */
export function patchConfigSkill(
configId: string,
skillId: string,
- payload: { enabled: boolean },
+ payload: { enabled?: boolean; envs?: Record<string, string> },
): Promise<{ data: ConfigSkill }> {
return patch(`/api/v1/sandbox-configs/${configId}/skills/${skillId}`, payload) as unknown as Promise<{
data: ConfigSkill
diff --git a/frontend/src/components/SandboxConfigEditorDrawer.vue b/frontend/src/components/SandboxConfigEditorDrawer.vue
index 97b7ce141..35d1833ea 100644
--- a/frontend/src/components/SandboxConfigEditorDrawer.vue
+++ b/frontend/src/components/SandboxConfigEditorDrawer.vue
@@ -472,9 +472,6 @@
<p v-if="pendingCheckNames.length" class="check-result__hint">
{{ $t('settings.sandbox.checkPendingHint', { names: pendingCheckNames.join('、') }) }}
</p>
- <t-alert v-if="checkResult.capabilities && checkResult.capabilities.supports_volumes === false" theme="warning"
- class="compact-alert"
- :message="$t('settings.sandbox.noVolumeSupport')" />
</div>
</SettingDrawer>
diff --git a/frontend/src/components/SandboxSkillsPanel.vue b/frontend/src/components/SandboxSkillsPanel.vue
index 1ccb7de6c..5ee4cf11c 100644
--- a/frontend/src/components/SandboxSkillsPanel.vue
+++ b/frontend/src/components/SandboxSkillsPanel.vue
@@ -179,6 +179,27 @@
@change="(v: any) => toggleEnabled(skill, Boolean(v))"
/>
</t-tooltip>
+ <t-tooltip
+ :content="
+ expandedEnvSkillId === skill.id
+ ? $t('settings.sandbox.skillEnv.toggleHide')
+ : $t('settings.sandbox.skillEnv.toggle')
+ "
+ placement="top"
+ >
+ <button
+ type="button"
+ class="skill-item__icon-btn"
+ :class="{ 'is-on': expandedEnvSkillId === skill.id }"
+ :aria-label="$t('settings.sandbox.skillEnv.toggle')"
+ @click="toggleEnvs(skill)"
+ >
+ <t-icon
+ :name="expandedEnvSkillId === skill.id ? 'chevron-up' : 'key'"
+ size="16px"
+ />
+ </button>
+ </t-tooltip>
<span class="skill-item__actions-divider" />
<t-tooltip :content="$t('settings.sandbox.skillFiles')" placement="top">
<button
@@ -333,6 +354,79 @@
<li v-for="(line, i) in failedErrorLines(skill)" :key="i">{{ line }}</li>
</ul>
</div>
+
+ <div v-if="expandedEnvSkillId === skill.id" class="skill-item__envs">
+ <p v-if="!skill.envs || skill.envs.length === 0" class="skill-envs__none">
+ {{ $t('settings.sandbox.skillEnv.none') }}
+ </p>
+ <template v-else>
+ <h5 class="skill-envs__title">{{ $t('settings.sandbox.skillEnv.workspaceTitle') }}</h5>
+ <p class="skill-envs__hint">{{ $t('settings.sandbox.skillEnv.workspaceHint') }}</p>
+ <div class="skill-envs__rows">
+ <div v-for="env in skill.envs" :key="env.name" class="skill-envs__row">
+ <div class="skill-envs__meta">
+ <code class="skill-envs__name">{{ env.name }}</code>
+ <span v-if="env.required" class="skill-envs__tag skill-envs__tag--required">
+ {{ $t('settings.sandbox.skillEnv.required') }}
+ </span>
+ <span
+ class="skill-envs__tag"
+ :class="env.is_set ? 'skill-envs__tag--set' : 'skill-envs__tag--unset'"
+ >
+ {{
+ env.is_set
+ ? $t('settings.sandbox.skillEnv.isSet')
+ : $t('settings.sandbox.skillEnv.notSet')
+ }}
+ </span>
+ <span v-if="env.description" class="skill-envs__desc">{{ env.description }}</span>
+ </div>
+ <div class="skill-envs__editor">
+ <t-input
+ v-model="envDrafts[skill.id][env.name]"
+ type="password"
+ autocomplete="off"
+ :aria-label="env.name"
+ :placeholder="
+ env.is_set
+ ? $t('settings.sandbox.skillEnv.placeholderSet')
+ : $t('settings.sandbox.skillEnv.placeholderUnset')
+ "
+ />
+ <t-popconfirm
+ v-if="canClearAdminSkillEnv(env)"
+ theme="warning"
+ :content="$t('settings.sandbox.skillEnv.clearConfirm', { name: env.name })"
+ :confirm-btn="{ content: $t('settings.sandbox.skillEnv.clear'), theme: 'danger' }"
+ :cancel-btn="{ content: $t('common.cancel') }"
+ @confirm="clearEnv(skill, env.name)"
+ >
+ <t-button
+ theme="danger"
+ variant="text"
+ size="small"
+ :disabled="envSaveInFlight(skill)"
+ :loading="envSaveInFlight(skill)"
+ >
+ {{ $t('settings.sandbox.skillEnv.clear') }}
+ </t-button>
+ </t-popconfirm>
+ </div>
+ </div>
+ </div>
+ <div class="skill-envs__footer">
+ <t-button
+ theme="primary"
+ size="small"
+ :disabled="!hasEnvEdits(skill) || envSaveInFlight(skill)"
+ :loading="envSaveInFlight(skill)"
+ @click="saveEnvs(skill)"
+ >
+ {{ $t('settings.sandbox.skillEnv.save') }}
+ </t-button>
+ </div>
+ </template>
+ </div>
</li>
</ul>
</section>
@@ -348,7 +442,7 @@
</template>
<script setup lang="ts">
-import { computed, nextTick, onUnmounted, ref, watch } from 'vue'
+import { computed, nextTick, onUnmounted, reactive, ref, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { fetchEventSource } from '@microsoft/fetch-event-source'
@@ -378,6 +472,18 @@ import {
import { getApiBaseUrl } from '@/utils/api-base'
import { generateRandomString } from '@/utils/index'
import i18n from '@/i18n'
+import {
+ MAX_ENV_VALUE_BYTES,
+ addSkillEnvSaveInFlight,
+ adminSkillEnvClearPayload,
+ canClearAdminSkillEnv,
+ clearSkillEnvSaveInFlight,
+ clearSubmittedSkillEnvDrafts,
+ editedSkillEnvPayload,
+ isSkillEnvSaveInFlight,
+ isValidEnvValueLength,
+ type SkillEnvSavesInFlight,
+} from '@/views/settings/envVarState'
// Skills are installed into the config's snapshot image, so the panel needs a
// config that already exists. The editor only renders it on a saved config.
@@ -414,6 +520,15 @@ const transcriptEpoch = ref(0)
const focusedSkillId = ref('')
const skillItemEls = new Map<string, HTMLElement>()
let focusTimer: number | null = null
+// Workspace-wide env values. Only one skill's editor is open at a time, for the
+// same reason as the timeline: the row is already dense.
+const expandedEnvSkillId = ref('')
+// Drafts keyed by skill then variable name. An absent key means "the admin did
+// not touch this field", which is what keeps the PATCH partial: an empty string
+// clears the stored value server-side, so submitting every input would wipe
+// values nobody looked at.
+const envDrafts = reactive<Record<string, Record<string, string>>>({})
+const envSavesInFlight = ref<SkillEnvSavesInFlight>({})
const fileInputRef = ref<HTMLInputElement | null>(null)
const progressById = ref<Record<string, ConfigSkillInstallEvent>>({})
@@ -548,6 +663,90 @@ function openSkillFiles(skill: ConfigSkill) {
filesDrawerVisible.value = true
}
+function toggleEnvs(skill: ConfigSkill) {
+ if (expandedEnvSkillId.value === skill.id) {
+ expandedEnvSkillId.value = ''
+ return
+ }
+ // Reopening starts from a clean slate rather than resurrecting a half-typed
+ // secret from the last time the editor was open.
+ envDrafts[skill.id] = {}
+ expandedEnvSkillId.value = skill.id
+}
+
+function envPayload(skill: ConfigSkill): Record<string, string> {
+ return editedSkillEnvPayload(
+ (skill.envs || []).map((env) => env.name),
+ envDrafts[skill.id],
+ )
+}
+
+function hasEnvEdits(skill: ConfigSkill): boolean {
+ return Object.keys(envPayload(skill)).length > 0
+}
+
+function envSaveInFlight(skill: ConfigSkill): boolean {
+ const configId = props.record?.id
+ return configId
+ ? isSkillEnvSaveInFlight(envSavesInFlight.value, configId, skill.id)
+ : false
+}
+
+async function saveEnvs(skill: ConfigSkill) {
+ const envs = envPayload(skill)
+ if (Object.keys(envs).length === 0) return
+ if (Object.values(envs).some((value) => !isValidEnvValueLength(value))) {
+ MessagePlugin.error(
+ t('settings.sandbox.skillEnv.valueTooLong', { max: MAX_ENV_VALUE_BYTES }),
+ )
+ return
+ }
+ await submitEnvs(skill, envs, 'settings.sandbox.skillEnv.saveSuccess')
+}
+
+async function clearEnv(skill: ConfigSkill, name: string) {
+ await submitEnvs(skill, adminSkillEnvClearPayload(name), 'settings.sandbox.skillEnv.clearSuccess')
+}
+
+async function submitEnvs(
+ skill: ConfigSkill,
+ envs: Record<string, string>,
+ successKey: string,
+) {
+ if (!props.record) return
+ const configId = props.record.id
+ if (isSkillEnvSaveInFlight(envSavesInFlight.value, configId, skill.id)) return
+ // A response that lands after the drawer moved to another config describes a
+ // panel nobody is looking at any more.
+ const isCurrent = () => props.record?.id === configId
+ envSavesInFlight.value = addSkillEnvSaveInFlight(
+ envSavesInFlight.value,
+ configId,
+ skill.id,
+ )
+ try {
+ const res = await patchConfigSkill(configId, skill.id, { envs })
+ if (!isCurrent()) return
+ const updated = res?.data
+ if (updated) {
+ skills.value = skills.value.map((item) => (item.id === skill.id ? updated : item))
+ }
+ // Nothing reads a stored value back. Remove only values that are still the
+ // submitted ones; newer typing during the request must survive cleanup.
+ envDrafts[skill.id] = clearSubmittedSkillEnvDrafts(envDrafts[skill.id] || {}, envs)
+ MessagePlugin.success(t(successKey))
+ } catch (e: any) {
+ if (!isCurrent()) return
+ MessagePlugin.error(e?.message || t('settings.sandbox.skillEnv.saveFailed'))
+ } finally {
+ envSavesInFlight.value = clearSkillEnvSaveInFlight(
+ envSavesInFlight.value,
+ configId,
+ skill.id,
+ )
+ }
+}
+
function progressOf(skill: ConfigSkill): number {
const percent = progressById.value[skill.id]?.percent
if (typeof percent === 'number' && Number.isFinite(percent)) {
@@ -945,7 +1144,11 @@ async function removeSkill(skill: ConfigSkill) {
// steps tears the follows down and coming back re-reads the list.
watch(
() => props.record?.id,
- (configID) => {
+ (configID, previousConfigID) => {
+ if (configID !== previousConfigID) {
+ expandedEnvSkillId.value = ''
+ for (const skillId of Object.keys(envDrafts)) delete envDrafts[skillId]
+ }
if (configID) {
void loadAll()
return
@@ -1176,6 +1379,101 @@ onUnmounted(() => {
box-shadow: 0 0 0 2px var(--td-brand-color-focus, rgba(0, 168, 112, 0.18));
}
+.skill-item__envs {
+ grid-column: 1 / -1;
+ border-top: 1px solid var(--td-component-stroke);
+ padding-top: 10px;
+}
+
+.skill-envs__none {
+ margin: 0;
+ font-size: 12px;
+ color: var(--td-text-color-placeholder);
+}
+
+.skill-envs__title {
+ margin: 0;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+}
+
+.skill-envs__hint {
+ margin: 2px 0 0;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--td-text-color-secondary);
+}
+
+.skill-envs__rows {
+ margin-top: 10px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.skill-envs__row {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.skill-envs__meta {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.skill-envs__name {
+ font-family: var(--td-font-family-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);
+ font-size: 12px;
+ color: var(--td-text-color-primary);
+ overflow-wrap: anywhere;
+}
+
+.skill-envs__tag {
+ font-size: 12px;
+ line-height: 18px;
+ padding: 0 8px;
+ border-radius: 10px;
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-text-color-secondary);
+}
+
+.skill-envs__tag--required {
+ background: var(--td-warning-color-light);
+ color: var(--td-warning-color);
+}
+
+.skill-envs__tag--set {
+ background: var(--td-success-color-light);
+ color: var(--td-success-color);
+}
+
+.skill-envs__desc {
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--td-text-color-secondary);
+}
+
+.skill-envs__editor {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.skill-envs__editor :deep(.t-input__wrap) {
+ flex: 1;
+ min-width: 0;
+}
+
+.skill-envs__footer {
+ margin-top: 10px;
+ display: flex;
+ justify-content: flex-end;
+}
+
.skill-status-ring {
width: 16px;
height: 16px;
diff --git a/frontend/src/config/deploymentCapabilities.test.ts b/frontend/src/config/deploymentCapabilities.test.ts
index c0424d5a2..e678c0cdd 100644
--- a/frontend/src/config/deploymentCapabilities.test.ts
+++ b/frontend/src/config/deploymentCapabilities.test.ts
@@ -39,3 +39,11 @@ test('only route-backed settings sections require deployment capabilities', () =
assert.equal(SETTINGS_SECTION_CAPABILITY.parser, undefined)
assert.equal(SETTINGS_SECTION_CAPABILITY['runtime-queues'], undefined)
})
+
+test('skill credentials follow the sandbox capability rather than a key of their own', () => {
+ // The values are injected into a skill script's process, so a deployment with
+ // no sandbox support has nowhere to put them and the page could only ever show
+ // its empty state.
+ assert.equal(SETTINGS_SECTION_CAPABILITY.envvars, 'settings.sandbox')
+ assert.equal(SETTINGS_SECTION_CAPABILITY.envvars, SETTINGS_SECTION_CAPABILITY.sandbox)
+})
diff --git a/frontend/src/config/deploymentCapabilities.ts b/frontend/src/config/deploymentCapabilities.ts
index c47ab3c47..f7a03f057 100644
--- a/frontend/src/config/deploymentCapabilities.ts
+++ b/frontend/src/config/deploymentCapabilities.ts
@@ -44,5 +44,9 @@ export const SETTINGS_SECTION_CAPABILITY: Partial<Record<string, DeploymentCapab
vectorstore: 'settings.vectorstore',
storage: 'settings.storage',
sandbox: 'settings.sandbox',
+ // Skill credentials exist only because sandboxes do: the values are injected
+ // into a skill script's process. A deployment without sandbox support has
+ // nowhere to inject them, so the page would only ever show its empty state.
+ envvars: 'settings.sandbox',
mcp: 'settings.mcp',
}
diff --git a/frontend/src/config/settingsAccess.test.ts b/frontend/src/config/settingsAccess.test.ts
index 29005519e..29061fa62 100644
--- a/frontend/src/config/settingsAccess.test.ts
+++ b/frontend/src/config/settingsAccess.test.ts
@@ -14,6 +14,17 @@ test('management shortcuts are stricter than read-only settings pages', () => {
assert.equal(SETTINGS_MANAGEMENT_SHORTCUT_MIN_ROLE.models, 'admin')
})
+test('personal skill environment variables are visible to every member', () => {
+ assert.equal(SETTINGS_SECTION_MIN_ROLE.envvars, 'viewer')
+ // The workspace-wide values live in the sandbox config editor, which is
+ // already Admin+; a management shortcut on the avatar menu would only
+ // duplicate that entrance.
+ assert.equal(
+ Object.prototype.hasOwnProperty.call(SETTINGS_MANAGEMENT_SHORTCUT_MIN_ROLE, 'envvars'),
+ false,
+ )
+})
+
test('system administration settings stay explicitly system-admin-only', () => {
assert.deepEqual(
[...SYSTEM_ADMIN_SETTINGS_SECTIONS],
diff --git a/frontend/src/config/settingsAccess.ts b/frontend/src/config/settingsAccess.ts
index e4bb0b6c1..05a73aaf1 100644
--- a/frontend/src/config/settingsAccess.ts
+++ b/frontend/src/config/settingsAccess.ts
@@ -25,6 +25,9 @@ export const SETTINGS_SECTION_MIN_ROLE: Record<string, SettingsRoleKey> = {
members: 'viewer',
mymemory: 'viewer',
memory: 'admin',
+ // Every member fills in their own environment variables; the workspace-wide
+ // values stay in the Admin+ sandbox editor.
+ envvars: 'viewer',
}
/**
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 7b106b3c6..98b6b1d8e 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -1361,6 +1361,25 @@ export default {
skillError: 'Error',
skillEnabled: 'Skill enabled',
skillDisabled: 'Skill disabled',
+ skillEnv: {
+ toggle: 'Environment variables',
+ toggleHide: 'Hide environment variables',
+ none: 'This skill declared no environment variables.',
+ workspaceTitle: 'Workspace-wide values',
+ workspaceHint: 'Every member who has not set their own value uses the value here. Members set their own under Settings, Environment variables.',
+ required: 'Required',
+ isSet: 'Set',
+ notSet: 'Not set',
+ placeholderSet: 'Stored, type to replace',
+ placeholderUnset: 'Enter a value',
+ save: 'Save',
+ saveSuccess: 'Workspace values saved',
+ saveFailed: 'Could not save the workspace values.',
+ clear: 'Clear',
+ clearConfirm: 'Clear the workspace value for {name}? The declaration stays. Members without their own value will then be missing it.',
+ clearSuccess: 'Workspace value cleared.',
+ valueTooLong: 'A value cannot exceed {max} bytes.'
+ },
},
mcpService: 'MCP Service',
versionInfo: 'Version Info',
@@ -1814,6 +1833,45 @@ export default {
saveFailed: 'Operation failed: {message}'
}
},
+ envVarSettings: {
+ title: 'Environment variables',
+ description: 'Values you enter here belong to you alone. A sandbox variable is passed to every skill script and shell command you run on that sandbox; a skill credential is passed only when that skill runs. Nothing is displayed again once saved.',
+ loading: 'Loading…',
+ loadFailed: 'Could not load the environment variables.',
+ retry: 'Try again',
+ noConfigTitle: 'No sandbox configured',
+ noConfigDescription: 'This workspace has no sandbox backend yet, so there is nothing to set variables for.',
+ sandboxTitle: 'Sandbox variables',
+ sandboxHint: 'Passed to everything you run on this sandbox, whether or not a skill is involved.',
+ sandboxEmpty: 'You have no variables on this sandbox.',
+ skillTitle: 'Skill credentials',
+ skillHint: 'What each skill declared it needs. Passed only when that skill runs.',
+ requiredTag: 'Required',
+ statusUnset: 'Not set',
+ statusWorkspace: 'Using the workspace value',
+ statusUser: 'Set by you',
+ blocking: 'Required but not set, so this skill cannot run.',
+ addRow: 'Add a variable',
+ namePlaceholder: 'VARIABLE_NAME',
+ nameRule: 'Upper-case letters, digits and underscores, starting with a letter or an underscore.',
+ nameInvalid: 'That name cannot be used. Names the sandbox reserves, such as PATH or anything starting with WEKNORA_, are not accepted.',
+ nameDuplicate: 'You already have a variable with that name here.',
+ valuePlaceholder: 'Enter a value',
+ storedPlaceholder: 'Stored, type to replace',
+ valueRequired: 'Enter a value before saving.',
+ valueTooLong: 'A value cannot exceed {max} bytes.',
+ tooManyValues: 'You can store at most {max} variables here.',
+ save: 'Save',
+ saveSuccess: 'Saved. The value is stored and will not be shown again.',
+ saveFailed: 'Could not save the value.',
+ delete: 'Delete',
+ deleteConfirm: 'Delete {name}? It will no longer be passed to anything you run on this sandbox.',
+ deleteSuccess: 'Variable deleted.',
+ clear: 'Remove my value',
+ clearConfirm: 'Remove your own value for {name}? The workspace value, if there is one, applies again afterwards.',
+ clearSuccess: 'Your value was removed.',
+ updatedAt: 'You set this on {time}'
+ },
memoryWorkspaceSettings: {
title: 'Long-term memory',
description: 'Let the assistant remember what members tell it — who they are, how they like to work, stable facts and what they are working on — across conversations.',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 49b442c89..e489281e5 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -4777,6 +4777,45 @@ export default {
saveFailed: '작업 실패: {message}'
}
},
+ envVarSettings: {
+ title: '환경 변수',
+ description: '여기에 입력한 값은 나에게만 속합니다. 샌드박스 변수는 해당 샌드박스에서 실행하는 모든 스킬 스크립트와 명령에 전달되고, 스킬 자격 증명은 그 스킬이 실행될 때만 전달됩니다. 저장한 뒤에는 다시 표시되지 않습니다.',
+ loading: '불러오는 중…',
+ loadFailed: '환경 변수를 불러오지 못했습니다.',
+ retry: '다시 시도',
+ noConfigTitle: '샌드박스가 없습니다',
+ noConfigDescription: '이 워크스페이스에는 아직 샌드박스 백엔드가 없어 설정할 변수가 없습니다.',
+ sandboxTitle: '샌드박스 변수',
+ sandboxHint: '스킬과 무관하게 이 샌드박스에서 실행하는 모든 것에 전달됩니다.',
+ sandboxEmpty: '이 샌드박스에 등록한 변수가 없습니다.',
+ skillTitle: '스킬 자격 증명',
+ skillHint: '각 스킬이 필요하다고 선언한 변수입니다. 그 스킬이 실행될 때만 전달됩니다.',
+ requiredTag: '필수',
+ statusUnset: '설정되지 않음',
+ statusWorkspace: '워크스페이스 공용 값 사용 중',
+ statusUser: '내가 설정함',
+ blocking: '필수인데 설정되지 않아 이 스킬을 실행할 수 없습니다.',
+ addRow: '변수 추가',
+ namePlaceholder: 'VARIABLE_NAME',
+ nameRule: '대문자, 숫자, 밑줄만 사용하며 문자 또는 밑줄로 시작해야 합니다.',
+ nameInvalid: '이 이름은 사용할 수 없습니다. PATH처럼 샌드박스가 예약한 이름이나 WEKNORA_로 시작하는 이름은 허용되지 않습니다.',
+ nameDuplicate: '같은 이름의 변수가 이미 있습니다.',
+ valuePlaceholder: '값 입력',
+ storedPlaceholder: '저장됨, 입력하면 교체됩니다',
+ valueRequired: '저장하기 전에 값을 입력하세요.',
+ valueTooLong: '값 하나는 {max}바이트를 초과할 수 없습니다.',
+ tooManyValues: '여기에는 최대 {max}개의 변수를 저장할 수 있습니다.',
+ save: '저장',
+ saveSuccess: '저장했습니다. 값은 보관되며 다시 표시되지 않습니다.',
+ saveFailed: '값을 저장하지 못했습니다.',
+ delete: '삭제',
+ deleteConfirm: '{name}을 삭제할까요? 이후 이 샌드박스에서 실행하는 것에는 전달되지 않습니다.',
+ deleteSuccess: '변수를 삭제했습니다.',
+ clear: '내 값 삭제',
+ clearConfirm: '{name}에 설정한 내 값을 삭제할까요? 이후에는 워크스페이스 공용 값이 있으면 다시 적용됩니다.',
+ clearSuccess: '내 값을 삭제했습니다.',
+ updatedAt: '{time}에 설정함'
+ },
memoryWorkspaceSettings: {
title: '장기 기억',
description: '구성원이 말한 개인 정보, 선호, 사실, 진행 중인 일을 어시스턴트가 대화를 넘어 기억하도록 합니다.',
@@ -5213,6 +5252,25 @@ export default {
skillError: 'Error',
skillEnabled: 'Skill enabled',
skillDisabled: 'Skill disabled',
+ skillEnv: {
+ toggle: '환경 변수',
+ toggleHide: '환경 변수 접기',
+ none: '이 스킬은 환경 변수를 선언하지 않았습니다.',
+ workspaceTitle: '워크스페이스 공용 값',
+ workspaceHint: '자기 값을 설정하지 않은 모든 구성원이 여기의 값을 사용합니다. 구성원은 설정의 환경 변수에서 자기 값을 설정할 수 있습니다.',
+ required: '필수',
+ isSet: '설정됨',
+ notSet: '설정되지 않음',
+ placeholderSet: '저장됨, 입력하면 교체됩니다',
+ placeholderUnset: '값 입력',
+ save: '저장',
+ saveSuccess: '워크스페이스 공용 값을 저장했습니다',
+ saveFailed: '워크스페이스 공용 값을 저장하지 못했습니다.',
+ clear: '삭제',
+ clearConfirm: '{name}의 워크스페이스 공용 값을 삭제할까요? 선언은 유지됩니다. 자기 값이 없는 구성원은 이후 이 값이 비어 있습니다.',
+ clearSuccess: '워크스페이스 공용 값을 삭제했습니다.',
+ valueTooLong: '값 하나는 {max}바이트를 초과할 수 없습니다.'
+ },
},
mcpService: 'MCP 서비스',
versionInfo: '버전 정보',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 55ca6bfac..cad813070 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -4777,6 +4777,45 @@ export default {
saveFailed: 'Не удалось выполнить: {message}'
}
},
+ envVarSettings: {
+ title: 'Переменные окружения',
+ description: 'Введённые здесь значения принадлежат только вам. Переменная песочницы передаётся во все скрипты навыков и команды, которые вы запускаете в этой песочнице; учётные данные навыка — только при запуске этого навыка. После сохранения значение больше не отображается.',
+ loading: 'Загрузка…',
+ loadFailed: 'Не удалось загрузить переменные окружения.',
+ retry: 'Повторить',
+ noConfigTitle: 'Песочница не настроена',
+ noConfigDescription: 'В этом рабочем пространстве пока нет песочницы, поэтому задавать переменные не для чего.',
+ sandboxTitle: 'Переменные песочницы',
+ sandboxHint: 'Передаются во всё, что вы запускаете в этой песочнице, независимо от навыков.',
+ sandboxEmpty: 'У вас нет переменных в этой песочнице.',
+ skillTitle: 'Учётные данные навыков',
+ skillHint: 'То, что каждый навык объявил необходимым. Передаётся только при запуске этого навыка.',
+ requiredTag: 'Обязательно',
+ statusUnset: 'Не задано',
+ statusWorkspace: 'Используется значение рабочего пространства',
+ statusUser: 'Задано вами',
+ blocking: 'Обязательная переменная не задана, поэтому навык не может работать.',
+ addRow: 'Добавить переменную',
+ namePlaceholder: 'VARIABLE_NAME',
+ nameRule: 'Только заглавные латинские буквы, цифры и подчёркивания; первым символом должна быть буква или подчёркивание.',
+ nameInvalid: 'Это имя использовать нельзя. Имена, зарезервированные песочницей, например PATH или начинающиеся с WEKNORA_, не принимаются.',
+ nameDuplicate: 'Переменная с таким именем здесь уже есть.',
+ valuePlaceholder: 'Введите значение',
+ storedPlaceholder: 'Сохранено, введите новое значение для замены',
+ valueRequired: 'Перед сохранением введите значение.',
+ valueTooLong: 'Значение не может превышать {max} байт.',
+ tooManyValues: 'Здесь можно сохранить не более {max} переменных.',
+ save: 'Сохранить',
+ saveSuccess: 'Сохранено. Значение сохранено и больше не будет показано.',
+ saveFailed: 'Не удалось сохранить значение.',
+ delete: 'Удалить',
+ deleteConfirm: 'Удалить {name}? Она больше не будет передаваться в то, что вы запускаете в этой песочнице.',
+ deleteSuccess: 'Переменная удалена.',
+ clear: 'Удалить моё значение',
+ clearConfirm: 'Удалить ваше значение для {name}? После этого снова применится значение рабочего пространства, если оно задано.',
+ clearSuccess: 'Ваше значение удалено.',
+ updatedAt: 'Вы задали это {time}'
+ },
memoryWorkspaceSettings: {
title: 'Долговременная память',
description: 'Позволяет ассистенту помнить между разговорами то, что говорят участники: кто они, как предпочитают работать, устойчивые факты и текущие задачи.',
@@ -5213,6 +5252,25 @@ export default {
skillError: 'Error',
skillEnabled: 'Skill enabled',
skillDisabled: 'Skill disabled',
+ skillEnv: {
+ toggle: 'Переменные окружения',
+ toggleHide: 'Скрыть переменные окружения',
+ none: 'Этот навык не объявил переменных окружения.',
+ workspaceTitle: 'Значения для всего рабочего пространства',
+ workspaceHint: 'Каждый участник, не задавший своё значение, использует значение отсюда. Своё значение участник задаёт в настройках, раздел «Переменные окружения».',
+ required: 'Обязательно',
+ isSet: 'Задано',
+ notSet: 'Не задано',
+ placeholderSet: 'Сохранено, введите новое значение для замены',
+ placeholderUnset: 'Введите значение',
+ save: 'Сохранить',
+ saveSuccess: 'Значения рабочего пространства сохранены',
+ saveFailed: 'Не удалось сохранить значения рабочего пространства.',
+ clear: 'Очистить',
+ clearConfirm: 'Очистить значение рабочего пространства для {name}? Объявление останется. У участников без своего значения его не будет.',
+ clearSuccess: 'Значение рабочего пространства очищено.',
+ valueTooLong: 'Значение не может превышать {max} байт.'
+ },
},
mcpService: 'Сервис MCP',
versionInfo: 'Информация о версии',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index c6b61cf66..8bbbb2609 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -4779,6 +4779,45 @@ export default {
saveFailed: '操作失败:{message}'
}
},
+ envVarSettings: {
+ title: '环境变量',
+ description: '这里填的值只属于你自己。沙盒变量会带给你在该沙盒上运行的所有技能脚本和命令;技能凭据只在该技能运行时带上。保存之后都不会再显示出来。',
+ loading: '加载中…',
+ loadFailed: '环境变量加载失败。',
+ retry: '重试',
+ noConfigTitle: '还没有沙盒',
+ noConfigDescription: '这个空间还没有配置沙盒后端,暂时没有可设置的变量。',
+ sandboxTitle: '沙盒变量',
+ sandboxHint: '你在这个沙盒上运行的任何东西都会带上,不限于技能。',
+ sandboxEmpty: '你在这个沙盒上还没有变量。',
+ skillTitle: '技能凭据',
+ skillHint: '各技能声明自己需要的变量,只在该技能运行时带上。',
+ requiredTag: '必填',
+ statusUnset: '未设置',
+ statusWorkspace: '正在使用空间共用值',
+ statusUser: '你已设置',
+ blocking: '必填但未设置,该技能无法运行。',
+ addRow: '添加变量',
+ namePlaceholder: 'VARIABLE_NAME',
+ nameRule: '只能用大写字母、数字和下划线,且以字母或下划线开头。',
+ nameInvalid: '这个名字不能用。沙箱保留的名字(例如 PATH,或以 WEKNORA_ 开头的名字)不接受。',
+ nameDuplicate: '这里已经有同名变量了。',
+ valuePlaceholder: '填入值',
+ storedPlaceholder: '已存值,填入新值即替换',
+ valueRequired: '保存前请先填入值。',
+ valueTooLong: '单个值不能超过 {max} 字节。',
+ tooManyValues: '这里最多可以保存 {max} 个变量。',
+ save: '保存',
+ saveSuccess: '已保存。值已存好,之后不会再显示。',
+ saveFailed: '保存失败。',
+ delete: '删除',
+ deleteConfirm: '删除 {name}?之后在这个沙盒上运行的东西都不会再带上它。',
+ deleteSuccess: '变量已删除。',
+ clear: '清除我的值',
+ clearConfirm: '清除你为 {name} 设置的值?之后会重新使用空间共用值(如果有)。',
+ clearSuccess: '已清除你的值。',
+ updatedAt: '你于 {time} 设置'
+ },
memoryWorkspaceSettings: {
title: '长期记忆',
description: '让助手跨会话记住成员说过的个人信息、偏好、事实与在办事项。',
@@ -5215,6 +5254,25 @@ export default {
skillError: '错误',
skillEnabled: '已启用技能',
skillDisabled: '已禁用技能',
+ skillEnv: {
+ toggle: '环境变量',
+ toggleHide: '收起环境变量',
+ none: '这个技能没有声明环境变量。',
+ workspaceTitle: '空间共用值',
+ workspaceHint: '所有没有填写自己值的成员都会用这里的值。成员可以在「设置 - 环境变量」里填自己的值。',
+ required: '必填',
+ isSet: '已设置',
+ notSet: '未设置',
+ placeholderSet: '已存值,填入新值即替换',
+ placeholderUnset: '填入值',
+ save: '保存',
+ saveSuccess: '空间共用值已保存',
+ saveFailed: '空间共用值保存失败。',
+ clear: '清除',
+ clearConfirm: '清除 {name} 的空间共用值?声明会保留,没有自己值的成员之后会缺少这个值。',
+ clearSuccess: '已清除空间共用值。',
+ valueTooLong: '单个值不能超过 {max} 字节。'
+ },
},
mcpService: 'MCP服务',
versionInfo: '版本信息',
diff --git a/frontend/src/views/settings/EnvVarSettings.vue b/frontend/src/views/settings/EnvVarSettings.vue
new file mode 100644
index 000000000..ebdd6d4d7
--- /dev/null
+++ b/frontend/src/views/settings/EnvVarSettings.vue
@@ -0,0 +1,646 @@
+<template>
+ <div class="env-settings">
+ <div class="section-header">
+ <h2>{{ t('envVarSettings.title') }}</h2>
+ <p class="section-description">{{ t('envVarSettings.description') }}</p>
+ </div>
+
+ <p v-if="loading" class="env-state">{{ t('envVarSettings.loading') }}</p>
+
+ <div v-else-if="loadError" class="env-state env-state--error">
+ <p class="env-state__text">{{ loadError }}</p>
+ <t-button variant="outline" size="small" @click="load()">
+ {{ t('envVarSettings.retry') }}
+ </t-button>
+ </div>
+
+ <div v-else-if="groups.length === 0" class="env-empty">
+ <p class="env-empty__title">{{ t('envVarSettings.noConfigTitle') }}</p>
+ <p class="env-empty__desc">{{ t('envVarSettings.noConfigDescription') }}</p>
+ </div>
+
+ <div v-else class="env-groups">
+ <section v-for="group in groups" :key="group.sandbox_config_id" class="env-group">
+ <h3 class="env-group__title">{{ configLabel(group) }}</h3>
+
+ <!-- Config-wide variables: the member-side counterpart of the admin's
+ sandbox env_vars, injected into every execution on this config. -->
+ <div class="env-block">
+ <div class="env-block__head">
+ <div>
+ <h4 class="env-block__title">{{ t('envVarSettings.sandboxTitle') }}</h4>
+ <p class="env-block__hint">{{ t('envVarSettings.sandboxHint') }}</p>
+ </div>
+ <t-button variant="text" size="small" @click="addRow(group.sandbox_config_id)">
+ <template #icon><t-icon name="add" /></template>
+ {{ t('envVarSettings.addRow') }}
+ </t-button>
+ </div>
+
+ <ul v-if="group.vars?.length" class="env-rows">
+ <li v-for="entry in group.vars" :key="entry.name" class="env-row">
+ <code class="env-row__name">{{ entry.name }}</code>
+ <t-input
+ v-model="drafts[sandboxKey(group.sandbox_config_id, entry.name)]"
+ type="password"
+ autocomplete="off"
+ :aria-label="entry.name"
+ :placeholder="t('envVarSettings.storedPlaceholder')"
+ class="env-row__value"
+ />
+ <t-button
+ theme="primary"
+ size="small"
+ :loading="busyKey === sandboxKey(group.sandbox_config_id, entry.name)"
+ @click="saveSandbox(group, entry.name)"
+ >
+ {{ t('envVarSettings.save') }}
+ </t-button>
+ <t-popconfirm
+ theme="warning"
+ :content="t('envVarSettings.deleteConfirm', { name: entry.name })"
+ :confirm-btn="{ content: t('envVarSettings.delete'), theme: 'danger' }"
+ :cancel-btn="{ content: t('common.cancel') }"
+ @confirm="deleteSandbox(group.sandbox_config_id, entry.name)"
+ >
+ <t-button
+ theme="danger"
+ variant="text"
+ size="small"
+ :loading="busyKey === sandboxKey(group.sandbox_config_id, entry.name)"
+ >
+ {{ t('envVarSettings.delete') }}
+ </t-button>
+ </t-popconfirm>
+ <p v-if="entry.updated_at" class="env-row__meta">
+ {{ t('envVarSettings.updatedAt', { time: formatTime(entry.updated_at) }) }}
+ </p>
+ </li>
+ </ul>
+ <p v-else-if="!newRows[group.sandbox_config_id]?.length" class="env-block__empty">
+ {{ t('envVarSettings.sandboxEmpty') }}
+ </p>
+
+ <div v-if="newRows[group.sandbox_config_id]?.length" class="env-new-rows">
+ <div
+ v-for="(row, index) in newRows[group.sandbox_config_id]"
+ :key="index"
+ class="env-new-row"
+ >
+ <t-input
+ v-model="row.name"
+ autocomplete="off"
+ :placeholder="t('envVarSettings.namePlaceholder')"
+ :status="row.name && !isValidEnvName(row.name) ? 'error' : undefined"
+ class="env-new-row__name"
+ />
+ <t-input
+ v-model="row.value"
+ type="password"
+ autocomplete="off"
+ :placeholder="t('envVarSettings.valuePlaceholder')"
+ class="env-new-row__value"
+ />
+ <t-button
+ theme="primary"
+ size="small"
+ :loading="busyKey === sandboxKey(group.sandbox_config_id, row.name)"
+ @click="saveNewRow(group, index)"
+ >
+ {{ t('envVarSettings.save') }}
+ </t-button>
+ <t-button
+ variant="text"
+ shape="square"
+ size="small"
+ :aria-label="t('common.delete')"
+ @click="removeRow(group.sandbox_config_id, index)"
+ >
+ <t-icon name="close" />
+ </t-button>
+ </div>
+ <p class="env-block__rule">{{ t('envVarSettings.nameRule') }}</p>
+ </div>
+ </div>
+
+ <!-- Skill credentials: only what a skill declared, injected when a tool
+ names that skill. -->
+ <div v-if="group.skills?.length" class="env-block">
+ <h4 class="env-block__title">{{ t('envVarSettings.skillTitle') }}</h4>
+ <p class="env-block__hint">{{ t('envVarSettings.skillHint') }}</p>
+
+ <div v-for="skill in group.skills" :key="skill.skill_id" class="env-skill">
+ <h5 class="env-skill__title">{{ skill.skill_name || skill.skill_id }}</h5>
+ <ul class="env-rows">
+ <li
+ v-for="entry in skill.vars"
+ :key="entry.name"
+ class="env-row env-row--declared"
+ :class="{ 'env-row--blocking': statusOf(entry).blocking }"
+ >
+ <div class="env-row__head">
+ <code class="env-row__name">{{ entry.name }}</code>
+ <span v-if="entry.required" class="env-tag env-tag--required">
+ {{ t('envVarSettings.requiredTag') }}
+ </span>
+ <span class="env-tag" :class="`env-tag--${statusOf(entry).key}`">
+ {{ t(STATUS_LABEL[statusOf(entry).key]) }}
+ </span>
+ </div>
+
+ <p v-if="entry.description" class="env-row__desc">{{ entry.description }}</p>
+
+ <p v-if="statusOf(entry).blocking" class="env-row__blocking">
+ <t-icon name="error-circle-filled" />
+ <span>{{ t('envVarSettings.blocking') }}</span>
+ </p>
+
+ <p v-if="entry.updated_at" class="env-row__meta">
+ {{ t('envVarSettings.updatedAt', { time: formatTime(entry.updated_at) }) }}
+ </p>
+
+ <div class="env-row__editor">
+ <t-input
+ v-model="drafts[skillKey(skill.skill_id, entry.name)]"
+ type="password"
+ autocomplete="off"
+ :aria-label="entry.name"
+ :placeholder="t('envVarSettings.valuePlaceholder')"
+ />
+ <t-button
+ theme="primary"
+ size="small"
+ :loading="busyKey === skillKey(skill.skill_id, entry.name)"
+ @click="saveSkill(skill, entry)"
+ >
+ {{ t('envVarSettings.save') }}
+ </t-button>
+ <t-popconfirm
+ v-if="statusOf(entry).key === 'user'"
+ theme="warning"
+ :content="t('envVarSettings.clearConfirm', { name: entry.name })"
+ :confirm-btn="{ content: t('envVarSettings.clear'), theme: 'danger' }"
+ :cancel-btn="{ content: t('common.cancel') }"
+ @confirm="deleteSkill(skill.skill_id, entry.name)"
+ >
+ <t-button
+ theme="danger"
+ variant="text"
+ size="small"
+ :loading="busyKey === skillKey(skill.skill_id, entry.name)"
+ >
+ {{ t('envVarSettings.clear') }}
+ </t-button>
+ </t-popconfirm>
+ </div>
+ </li>
+ </ul>
+ </div>
+ </div>
+ </section>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { onMounted, reactive, ref } from 'vue'
+import { MessagePlugin } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
+import {
+ deleteMySandboxEnv,
+ deleteMySkillEnv,
+ listMyEnvVars,
+ setMySandboxEnv,
+ setMySkillEnv,
+ type ConfigEnvGroup,
+ type EnvVarSource,
+ type EnvVarView,
+ type SkillEnvGroup,
+} from '@/api/env-vars'
+import {
+ MAX_ENV_VALUE_BYTES,
+ MAX_USER_ENV_VARS_PER_SCOPE,
+ canAddEnvVar,
+ configLabel,
+ isValidEnvName,
+ isValidEnvValueLength,
+ sortedConfigGroups,
+ statusOf,
+} from './envVarState'
+
+const { t, locale } = useI18n()
+
+const STATUS_LABEL: Record<EnvVarSource, string> = {
+ unset: 'envVarSettings.statusUnset',
+ workspace: 'envVarSettings.statusWorkspace',
+ user: 'envVarSettings.statusUser',
+}
+
+const loading = ref(true)
+const loadError = ref('')
+const groups = ref<ConfigEnvGroup[]>([])
+
+// Drafts are keyed by scope and name rather than held on the row, so a reload
+// cannot silently discard what is half-typed elsewhere on the page.
+const drafts = reactive<Record<string, string>>({})
+const newRows = reactive<Record<string, Array<{ name: string; value: string }>>>({})
+const busyKey = ref('')
+
+function skillKey(skillId: string, name: string): string {
+ return `skill:${skillId}:${name}`
+}
+
+function sandboxKey(configId: string, name: string): string {
+ return `sandbox:${configId}:${name}`
+}
+
+function formatTime(value: string): string {
+ const date = new Date(value)
+ if (Number.isNaN(date.getTime())) return value
+ return date.toLocaleString(locale.value)
+}
+
+async function load() {
+ loading.value = true
+ loadError.value = ''
+ try {
+ const res = await listMyEnvVars()
+ groups.value = sortedConfigGroups(res?.data || [])
+ } catch (e: any) {
+ groups.value = []
+ loadError.value = e?.message || t('envVarSettings.loadFailed')
+ } finally {
+ loading.value = false
+ }
+}
+
+/** Shared guard for both scopes: a value is required and bounded. */
+function rejectBadValue(value: string): boolean {
+ if (!value) {
+ MessagePlugin.warning(t('envVarSettings.valueRequired'))
+ return true
+ }
+ if (!isValidEnvValueLength(value)) {
+ MessagePlugin.error(t('envVarSettings.valueTooLong', { max: MAX_ENV_VALUE_BYTES }))
+ return true
+ }
+ return false
+}
+
+async function submit(key: string, action: () => Promise<unknown>, successMessage: string) {
+ busyKey.value = key
+ try {
+ await action()
+ // Write-only by design: the value is stored and never echoed, so leaving it
+ // in the input would keep a secret in the DOM for no benefit.
+ delete drafts[key]
+ MessagePlugin.success(successMessage)
+ await load()
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('envVarSettings.saveFailed'))
+ } finally {
+ busyKey.value = ''
+ }
+}
+
+async function saveSkill(skill: SkillEnvGroup, entry: EnvVarView) {
+ const key = skillKey(skill.skill_id, entry.name)
+ const value = drafts[key] || ''
+ if (rejectBadValue(value)) return
+ await submit(
+ key,
+ () => setMySkillEnv(skill.skill_id, entry.name, value),
+ t('envVarSettings.saveSuccess'),
+ )
+}
+
+async function deleteSkill(skillId: string, name: string) {
+ await submit(
+ skillKey(skillId, name),
+ () => deleteMySkillEnv(skillId, name),
+ t('envVarSettings.clearSuccess'),
+ )
+}
+
+async function saveSandbox(group: ConfigEnvGroup, name: string) {
+ const key = sandboxKey(group.sandbox_config_id, name)
+ const value = drafts[key] || ''
+ if (rejectBadValue(value)) return
+ await submit(
+ key,
+ () => setMySandboxEnv(group.sandbox_config_id, name, value),
+ t('envVarSettings.saveSuccess'),
+ )
+}
+
+async function deleteSandbox(configId: string, name: string) {
+ await submit(
+ sandboxKey(configId, name),
+ () => deleteMySandboxEnv(configId, name),
+ t('envVarSettings.deleteSuccess'),
+ )
+}
+
+function addRow(configId: string) {
+ if (!newRows[configId]) newRows[configId] = []
+ newRows[configId].push({ name: '', value: '' })
+}
+
+function removeRow(configId: string, index: number) {
+ newRows[configId]?.splice(index, 1)
+}
+
+async function saveNewRow(group: ConfigEnvGroup, index: number) {
+ const row = newRows[group.sandbox_config_id]?.[index]
+ if (!row) return
+ const name = row.name.trim()
+ if (!isValidEnvName(name)) {
+ MessagePlugin.error(t('envVarSettings.nameInvalid'))
+ return
+ }
+ if (group.vars?.some((v) => v.name === name)) {
+ MessagePlugin.error(t('envVarSettings.nameDuplicate'))
+ return
+ }
+ if (rejectBadValue(row.value)) return
+ if (!canAddEnvVar(group.vars || [], name)) {
+ MessagePlugin.error(t('envVarSettings.tooManyValues', { max: MAX_USER_ENV_VARS_PER_SCOPE }))
+ return
+ }
+ const key = sandboxKey(group.sandbox_config_id, name)
+ busyKey.value = key
+ try {
+ await setMySandboxEnv(group.sandbox_config_id, name, row.value)
+ removeRow(group.sandbox_config_id, index)
+ MessagePlugin.success(t('envVarSettings.saveSuccess'))
+ await load()
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('envVarSettings.saveFailed'))
+ } finally {
+ busyKey.value = ''
+ }
+}
+
+onMounted(() => {
+ void load()
+})
+</script>
+
+<style lang="less" scoped>
+.env-settings {
+ width: 100%;
+}
+
+.section-header {
+ margin-bottom: 24px;
+
+ h2 {
+ font-size: 20px;
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+ margin: 0 0 8px 0;
+ }
+
+ .section-description {
+ font-size: 14px;
+ color: var(--td-text-color-secondary);
+ margin: 0;
+ line-height: 1.6;
+ }
+}
+
+.env-state {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ font-size: 13px;
+ color: var(--td-text-color-secondary);
+ margin: 0;
+}
+
+.env-state--error .env-state__text {
+ margin: 0;
+ color: var(--td-error-color);
+}
+
+.env-empty {
+ background: var(--td-bg-color-secondarycontainer);
+ border-radius: 8px;
+ padding: 24px;
+ text-align: center;
+}
+
+.env-empty__title {
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--td-text-color-secondary);
+ margin: 0 0 4px 0;
+}
+
+.env-empty__desc {
+ font-size: 13px;
+ color: var(--td-text-color-placeholder);
+ margin: 0;
+}
+
+.env-groups {
+ display: flex;
+ flex-direction: column;
+ gap: 20px;
+}
+
+.env-group {
+ border: 1px solid var(--td-component-stroke);
+ border-radius: 8px;
+ padding: 16px;
+ background: var(--td-bg-color-container);
+}
+
+.env-group__title {
+ font-size: 15px;
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+ margin: 0 0 12px 0;
+}
+
+.env-block + .env-block {
+ margin-top: 16px;
+ padding-top: 12px;
+ border-top: 1px solid var(--td-component-stroke);
+}
+
+.env-block__head {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.env-block__title {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+ margin: 0;
+}
+
+.env-block__hint {
+ margin: 2px 0 0;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--td-text-color-secondary);
+}
+
+.env-block__empty,
+.env-block__rule {
+ margin: 8px 0 0;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--td-text-color-placeholder);
+}
+
+.env-rows {
+ margin: 10px 0 0;
+ padding: 0;
+ list-style: none;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.env-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+
+.env-row--declared {
+ display: block;
+ border: 1px solid var(--td-component-stroke);
+ border-radius: 6px;
+ padding: 12px;
+}
+
+// A required variable nobody has filled in stops the skill from running, so it
+// reads as an error rather than as one more grey "not set" row.
+.env-row--blocking {
+ border-color: var(--td-error-color);
+ background: var(--td-error-color-light);
+}
+
+.env-row__head {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+.env-row__name {
+ font-family: var(--td-font-family-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);
+ font-size: 13px;
+ color: var(--td-text-color-primary);
+ overflow-wrap: anywhere;
+ flex: 0 0 30%;
+}
+
+.env-row--declared .env-row__name {
+ flex: initial;
+}
+
+.env-row__value {
+ flex: 1;
+ min-width: 0;
+}
+
+.env-tag {
+ font-size: 12px;
+ line-height: 18px;
+ padding: 0 8px;
+ border-radius: 10px;
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-text-color-secondary);
+}
+
+.env-tag--required {
+ background: var(--td-warning-color-light);
+ color: var(--td-warning-color);
+}
+
+.env-tag--user {
+ background: var(--td-success-color-light);
+ color: var(--td-success-color);
+}
+
+.env-tag--workspace {
+ background: var(--td-brand-color-light);
+ color: var(--td-brand-color);
+}
+
+.env-row__desc,
+.env-row__meta {
+ margin: 6px 0 0;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--td-text-color-secondary);
+}
+
+.env-row__meta {
+ color: var(--td-text-color-placeholder);
+ flex-basis: 100%;
+}
+
+.env-row__blocking {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin: 6px 0 0;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--td-error-color);
+}
+
+.env-row__editor {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 10px;
+}
+
+.env-row__editor :deep(.t-input__wrap) {
+ flex: 1;
+ min-width: 0;
+}
+
+.env-skill {
+ margin-top: 12px;
+}
+
+.env-skill__title {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+ margin: 0;
+}
+
+.env-new-rows {
+ margin-top: 10px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.env-new-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.env-new-row__name {
+ flex: 0 0 30%;
+}
+
+.env-new-row__value {
+ flex: 1;
+ min-width: 0;
+}
+</style>
diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vue
index 741f55fcf..75242713a 100644
--- a/frontend/src/views/settings/Settings.vue
+++ b/frontend/src/views/settings/Settings.vue
@@ -133,6 +133,11 @@
<MemorySettings />
</div>
+ <!-- 技能凭据(成员自己的技能环境变量) -->
+ <div v-if="currentSection === 'envvars'" class="section">
+ <EnvVarSettings />
+ </div>
+
<!-- 向量数据库引擎 -->
<div v-if="currentSection === 'vectorstore'" class="section">
<VectorStoreSettings />
@@ -230,6 +235,7 @@ import McpSettings from './McpSettings.vue'
import WebSearchSettings from './WebSearchSettings.vue'
import ChatHistorySettings from './ChatHistorySettings.vue'
import MemorySettings from './MemorySettings.vue'
+import EnvVarSettings from './EnvVarSettings.vue'
import MemoryWorkspaceSettings from './MemoryWorkspaceSettings.vue'
import VectorStoreSettings from './VectorStoreSettings.vue'
import ParserEngineSettings from './ParserEngineSettings.vue'
@@ -373,6 +379,7 @@ const navItems = computed(() => {
{ key: 'system-audit-log', icon: 'history', label: t('system.globalSettings.audit.tabLabel') },
{ key: 'userprofile', icon: 'user', label: t('userProfile.title') },
{ key: 'mymemory', icon: 'bookmark', label: t('memorySettings.title') },
+ { key: 'envvars', icon: 'lock-on', label: t('envVarSettings.title') },
{ key: 'tenant', icon: 'user-circle', label: t('settings.tenantInfo') },
{ key: 'members', icon: 'usergroup', label: t('tenantMember.title') },
...integrationItems,
@@ -397,7 +404,7 @@ const navGroups = computed<NavGroup[]>(() => {
{
key: 'account',
label: t('settings.navGroups.account'),
- items: pickItems(['general', 'userprofile', 'mymemory']),
+ items: pickItems(['general', 'userprofile', 'mymemory', 'envvars']),
},
{
key: 'workspace',
diff --git a/frontend/src/views/settings/envVarState.test.ts b/frontend/src/views/settings/envVarState.test.ts
new file mode 100644
index 000000000..fa2a73ad7
--- /dev/null
+++ b/frontend/src/views/settings/envVarState.test.ts
@@ -0,0 +1,233 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+
+import type { ConfigEnvGroup, EnvVarView, SkillEnvGroup } from '@/api/env-vars'
+import {
+ MAX_ENV_VALUE_BYTES,
+ MAX_USER_ENV_VARS_PER_SCOPE,
+ RESERVED_ENV_NAMES,
+ addSkillEnvSaveInFlight,
+ adminSkillEnvClearPayload,
+ canAddEnvVar,
+ canClearAdminSkillEnv,
+ clearSkillEnvSaveInFlight,
+ clearSubmittedSkillEnvDrafts,
+ configLabel,
+ editedSkillEnvPayload,
+ isSkillEnvSaveInFlight,
+ isValidEnvName,
+ isValidEnvValueLength,
+ sortedConfigGroups,
+ statusOf,
+} from './envVarState'
+
+function envVar(overrides: Partial<EnvVarView> & { name: string }): EnvVarView {
+ return { source: 'unset', ...overrides }
+}
+
+function skill(skillId: string, skillName: string, vars: EnvVarView[]): SkillEnvGroup {
+ return { skill_id: skillId, skill_name: skillName, vars }
+}
+
+function config(
+ configId: string,
+ configName: string,
+ vars: EnvVarView[] = [],
+ skills: SkillEnvGroup[] = [],
+): ConfigEnvGroup {
+ return {
+ sandbox_config_id: configId,
+ sandbox_config_name: configName,
+ vars,
+ skills,
+ }
+}
+
+test('statusOf reports which of the three sources supplies the value', () => {
+ assert.deepEqual(statusOf(envVar({ name: 'A', source: 'unset' })), {
+ key: 'unset',
+ blocking: false,
+ })
+ assert.deepEqual(statusOf(envVar({ name: 'A', source: 'workspace' })), {
+ key: 'workspace',
+ blocking: false,
+ })
+ assert.deepEqual(statusOf(envVar({ name: 'A', source: 'user' })), {
+ key: 'user',
+ blocking: false,
+ })
+})
+
+test('statusOf blocks only when a required variable has no value at all', () => {
+ assert.equal(statusOf(envVar({ name: 'A', source: 'unset', required: true })).blocking, true)
+ // A workspace value satisfies a required variable: the skill can run.
+ assert.equal(statusOf(envVar({ name: 'A', source: 'workspace', required: true })).blocking, false)
+ assert.equal(statusOf(envVar({ name: 'A', source: 'user', required: true })).blocking, false)
+ // Optional and unset is a normal state, not a problem to flag.
+ assert.equal(statusOf(envVar({ name: 'A', source: 'unset', required: false })).blocking, false)
+ assert.equal(statusOf(envVar({ name: 'A', source: 'unset' })).blocking, false)
+})
+
+test('configLabel falls back to the config id when the name is blank', () => {
+ assert.equal(configLabel(config('cfg-1', 'Production')), 'Production')
+ assert.equal(configLabel(config('cfg-1', ' ')), 'cfg-1')
+ assert.equal(configLabel(config('cfg-1', '')), 'cfg-1')
+})
+
+test('sortedConfigGroups orders by config name', () => {
+ const groups = [config('c1', 'Staging'), config('c2', 'Production')]
+
+ assert.deepEqual(
+ sortedConfigGroups(groups).map((g) => g.sandbox_config_name),
+ ['Production', 'Staging'],
+ )
+})
+
+test('sortedConfigGroups falls back to the id so equal names keep a stable order', () => {
+ const groups = [config('c2', 'Same'), config('c1', 'Same')]
+
+ assert.deepEqual(
+ sortedConfigGroups(groups).map((g) => g.sandbox_config_id),
+ ['c1', 'c2'],
+ )
+})
+
+test('sortedConfigGroups does not mutate its input', () => {
+ const groups = [config('c1', 'Staging'), config('c2', 'Production')]
+ const before = groups.map((g) => g.sandbox_config_id)
+
+ sortedConfigGroups(groups)
+
+ assert.deepEqual(groups.map((g) => g.sandbox_config_id), before)
+})
+
+test('isValidEnvName accepts UPPER_SNAKE_CASE names', () => {
+ assert.equal(isValidEnvName('MY_KEY'), true)
+ assert.equal(isValidEnvName('K'), true)
+ assert.equal(isValidEnvName('_LEADING'), true)
+ assert.equal(isValidEnvName('A1_B2'), true)
+})
+
+test('isValidEnvName rejects what the server rejects', () => {
+ assert.equal(isValidEnvName('PATH'), false)
+ assert.equal(isValidEnvName('LD_PRELOAD'), false)
+ assert.equal(isValidEnvName('WEKNORA_ANYTHING'), false)
+ assert.equal(isValidEnvName('my_key'), false)
+ assert.equal(isValidEnvName('MY KEY'), false)
+ assert.equal(isValidEnvName(''), false)
+ assert.equal(isValidEnvName('1KEY'), false)
+ assert.equal(isValidEnvName('MY-KEY'), false)
+ assert.equal(isValidEnvName(`A${'B'.repeat(128)}`), false)
+})
+
+test('RESERVED_ENV_NAMES mirrors the sandbox reserved list', () => {
+ assert.deepEqual([...RESERVED_ENV_NAMES].sort(), [
+ 'HOME',
+ 'LD_LIBRARY_PATH',
+ 'LD_PRELOAD',
+ 'NODE_OPTIONS',
+ 'PATH',
+ 'PYTHONHOME',
+ 'PYTHONPATH',
+ 'SHELL',
+ 'USER',
+ ])
+})
+
+test('isValidEnvValueLength measures UTF-8 bytes, not JavaScript characters', () => {
+ assert.equal(isValidEnvValueLength('x'.repeat(MAX_ENV_VALUE_BYTES)), true)
+ assert.equal(isValidEnvValueLength('x'.repeat(MAX_ENV_VALUE_BYTES + 1)), false)
+
+ const nonAscii = '你'.repeat(3000)
+ assert.equal(nonAscii.length < MAX_ENV_VALUE_BYTES, true)
+ assert.equal(isValidEnvValueLength(nonAscii), false)
+})
+
+test('canAddEnvVar allows overwrites at the per-scope limit but rejects a new name', () => {
+ const existing = Array.from({ length: MAX_USER_ENV_VARS_PER_SCOPE }, (_, index) =>
+ envVar({ name: `KEY_${index}`, source: 'user' }),
+ )
+
+ assert.equal(canAddEnvVar(existing, 'KEY_0'), true)
+ assert.equal(canAddEnvVar(existing, 'NEW_KEY'), false)
+})
+
+test('canAddEnvVar counts only values owned by the current user', () => {
+ const existing = [
+ ...Array.from({ length: MAX_USER_ENV_VARS_PER_SCOPE - 1 }, (_, index) =>
+ envVar({ name: `KEY_${index}`, source: 'user' }),
+ ),
+ envVar({ name: 'WORKSPACE_KEY', source: 'workspace' }),
+ envVar({ name: 'UNSET_KEY', source: 'unset' }),
+ ]
+
+ assert.equal(canAddEnvVar(existing, 'NEW_KEY'), true)
+})
+
+test('adminSkillEnvClearPayload sends an empty string so the declaration stays', () => {
+ assert.deepEqual(adminSkillEnvClearPayload('API_TOKEN'), { API_TOKEN: '' })
+})
+
+test('canClearAdminSkillEnv is only true once a workspace value is stored', () => {
+ assert.equal(canClearAdminSkillEnv({ is_set: true }), true)
+ assert.equal(canClearAdminSkillEnv({ is_set: false }), false)
+ assert.equal(canClearAdminSkillEnv({}), false)
+})
+
+test('editedSkillEnvPayload includes only drafted names declared by the skill', () => {
+ assert.deepEqual(
+ editedSkillEnvPayload(['TOKEN', 'EMPTY'], {
+ TOKEN: 'new-token',
+ EMPTY: '',
+ UNDECLARED: 'must-not-submit',
+ }),
+ { TOKEN: 'new-token', EMPTY: '' },
+ )
+})
+
+test('editedSkillEnvPayload excludes untouched declared inputs so they cannot be cleared', () => {
+ assert.deepEqual(editedSkillEnvPayload(['TOKEN', 'PASSWORD'], { TOKEN: 'new-token' }), {
+ TOKEN: 'new-token',
+ })
+})
+
+test('clearSubmittedSkillEnvDrafts clears only unchanged submitted values', () => {
+ assert.deepEqual(
+ clearSubmittedSkillEnvDrafts(
+ {
+ TOKEN: 'newer-token',
+ EMPTY: '',
+ OTHER: 'typed-later',
+ },
+ {
+ TOKEN: 'submitted-token',
+ EMPTY: '',
+ },
+ ),
+ {
+ TOKEN: 'newer-token',
+ OTHER: 'typed-later',
+ },
+ )
+})
+
+test('skill env save in-flight state is scoped by config and skill', () => {
+ const inFlight = addSkillEnvSaveInFlight({}, 'cfg-a', 'skill-s')
+
+ assert.equal(isSkillEnvSaveInFlight(inFlight, 'cfg-a', 'skill-s'), true)
+ assert.equal(isSkillEnvSaveInFlight(inFlight, 'cfg-a', 'other-skill'), false)
+ assert.equal(isSkillEnvSaveInFlight(inFlight, 'cfg-b', 'skill-s'), false)
+})
+
+test('skill env save completion removes exactly its own in-flight entry', () => {
+ const inFlight = addSkillEnvSaveInFlight(
+ addSkillEnvSaveInFlight({}, 'cfg-a', 'skill-s'),
+ 'cfg-b',
+ 'skill-t',
+ )
+
+ const remaining = clearSkillEnvSaveInFlight(inFlight, 'cfg-a', 'skill-s')
+
+ assert.equal(isSkillEnvSaveInFlight(remaining, 'cfg-a', 'skill-s'), false)
+ assert.equal(isSkillEnvSaveInFlight(remaining, 'cfg-b', 'skill-t'), true)
+})
diff --git a/frontend/src/views/settings/envVarState.ts b/frontend/src/views/settings/envVarState.ts
new file mode 100644
index 000000000..7a0332d97
--- /dev/null
+++ b/frontend/src/views/settings/envVarState.ts
@@ -0,0 +1,162 @@
+import type { ConfigEnvGroup, EnvVarSource, EnvVarView } from '@/api/env-vars'
+
+/**
+ * Pure state helpers for the environment variable UIs.
+ *
+ * Everything a reviewer would want to assert lives here rather than in the
+ * `.vue` files, because this repo tests plain TypeScript on `node:test` and
+ * does not do component testing.
+ */
+
+/**
+ * Mirror `MaxEnvValueBytes` and `MaxUserEnvVarsPerScope` in
+ * `internal/application/service/tenant_skill_env_declare.go`. The server
+ * remains authoritative; these browser checks only turn a round trip into
+ * immediate feedback.
+ */
+export const MAX_ENV_VALUE_BYTES = 8192
+export const MAX_USER_ENV_VARS_PER_SCOPE = 50
+
+export function isValidEnvValueLength(value: string): boolean {
+ return new TextEncoder().encode(value).length <= MAX_ENV_VALUE_BYTES
+}
+
+/**
+ * Overwriting a name the member already owns remains valid at the limit, so
+ * values can still be rotated.
+ */
+export function canAddEnvVar(existing: EnvVarView[], name: string): boolean {
+ const owned = existing.filter((entry) => entry.source === 'user')
+ return (
+ owned.some((entry) => entry.name === name) || owned.length < MAX_USER_ENV_VARS_PER_SCOPE
+ )
+}
+
+/** Builds the admin PATCH body from edited drafts intersected with declarations. */
+export function editedSkillEnvPayload(
+ declaredNames: string[],
+ drafts: Record<string, string> | undefined,
+): Record<string, string> {
+ if (!drafts) return {}
+ const declared = new Set(declaredNames)
+ return Object.fromEntries(
+ Object.entries(drafts).filter(([name]) => declared.has(name)),
+ )
+}
+
+/** Admin PATCH body that clears one stored value and keeps the declaration. */
+export function adminSkillEnvClearPayload(name: string): Record<string, string> {
+ return { [name]: '' }
+}
+
+/** The clear control is only meaningful when a workspace value is already stored. */
+export function canClearAdminSkillEnv(env: { is_set?: boolean }): boolean {
+ return env.is_set === true
+}
+
+/**
+ * Removes a submitted draft only if it still equals the sent value. New input
+ * typed while the request was in flight always wins over response cleanup.
+ */
+export function clearSubmittedSkillEnvDrafts(
+ currentDrafts: Record<string, string>,
+ submitted: Record<string, string>,
+): Record<string, string> {
+ const remaining = { ...currentDrafts }
+ for (const [name, value] of Object.entries(submitted)) {
+ if (remaining[name] === value) delete remaining[name]
+ }
+ return remaining
+}
+
+export type SkillEnvSavesInFlight = Record<string, true>
+
+function skillEnvSaveKey(configId: string, skillId: string): string {
+ return JSON.stringify([configId, skillId])
+}
+
+export function isSkillEnvSaveInFlight(
+ inFlight: Readonly<SkillEnvSavesInFlight>,
+ configId: string,
+ skillId: string,
+): boolean {
+ return inFlight[skillEnvSaveKey(configId, skillId)] === true
+}
+
+export function addSkillEnvSaveInFlight(
+ inFlight: Readonly<SkillEnvSavesInFlight>,
+ configId: string,
+ skillId: string,
+): SkillEnvSavesInFlight {
+ return { ...inFlight, [skillEnvSaveKey(configId, skillId)]: true }
+}
+
+export function clearSkillEnvSaveInFlight(
+ inFlight: Readonly<SkillEnvSavesInFlight>,
+ configId: string,
+ skillId: string,
+): SkillEnvSavesInFlight {
+ const remaining = { ...inFlight }
+ delete remaining[skillEnvSaveKey(configId, skillId)]
+ return remaining
+}
+
+/**
+ * Names the sandbox refuses, mirroring `reservedEnvNames` in
+ * `internal/application/service/tenant_skill_env_declare.go`. Rejecting them
+ * in the browser is not a security boundary — the server checks again — it
+ * just turns a 400 into an inline hint before the user hits save.
+ */
+export const RESERVED_ENV_NAMES: Set<string> = new Set([
+ 'PATH',
+ 'HOME',
+ 'USER',
+ 'SHELL',
+ 'LD_PRELOAD',
+ 'LD_LIBRARY_PATH',
+ 'PYTHONPATH',
+ 'PYTHONHOME',
+ 'NODE_OPTIONS',
+])
+
+/** The sandbox hands the skill its artifact directory through this prefix. */
+const RESERVED_ENV_PREFIX = 'WEKNORA_'
+
+/** Mirrors `envNamePattern` server-side: UPPER_SNAKE_CASE, at most 128 chars. */
+const ENV_NAME_PATTERN = /^[A-Z_][A-Z0-9_]{0,127}$/
+
+export function isValidEnvName(name: string): boolean {
+ if (!ENV_NAME_PATTERN.test(name)) return false
+ if (RESERVED_ENV_NAMES.has(name)) return false
+ return !name.startsWith(RESERVED_ENV_PREFIX)
+}
+
+export interface EnvStatus {
+ key: EnvVarSource
+ /** True only when the skill cannot run without this variable and nothing supplies it. */
+ blocking: boolean
+}
+
+export function statusOf(v: EnvVarView): EnvStatus {
+ const key: EnvVarSource =
+ v.source === 'user' || v.source === 'workspace' ? v.source : 'unset'
+ return { key, blocking: key === 'unset' && v.required === true }
+}
+
+/** The config's display name, falling back to its id so a group is never nameless. */
+export function configLabel(group: Pick<ConfigEnvGroup, 'sandbox_config_id' | 'sandbox_config_name'>): string {
+ return group.sandbox_config_name?.trim() || group.sandbox_config_id
+}
+
+/**
+ * Groups ordered by config name, on a copy. The list is re-read after every
+ * write, and reordering the array the caller still holds would move rows out
+ * from under a half-filled input.
+ */
+export function sortedConfigGroups(groups: ConfigEnvGroup[]): ConfigEnvGroup[] {
+ return [...groups].sort((a, b) => {
+ const byName = configLabel(a).localeCompare(configLabel(b))
+ if (byName !== 0) return byName
+ return a.sandbox_config_id.localeCompare(b.sandbox_config_id)
+ })
+}
diff --git a/internal/agent/skills/env_resolver.go b/internal/agent/skills/env_resolver.go
new file mode 100644
index 000000000..890447871
--- /dev/null
+++ b/internal/agent/skills/env_resolver.go
@@ -0,0 +1,61 @@
+package skills
+
+import (
+ "context"
+ "fmt"
+ "strings"
+)
+
+// SkillEnvResolver produces the environment one execution gets. It is separate
+// from SkillSource because the values are per-caller: the same skill, in the
+// same image, hands a different key to a different Principal. The implementation
+// lives in the service layer, which can reach the repository.
+//
+// It is keyed by skill NAME rather than id because every path into the manager
+// is name-addressed: ExecuteScript receives the name the model wrote, and the
+// row id is an implementation detail of the installed-skill source.
+type SkillEnvResolver interface {
+ // ResolveEnv returns the values to inject and the names of any required
+ // variable that neither the admin nor this caller has filled in. An empty
+ // skillName asks for the caller's config-wide variables alone. The caller's
+ // identity is taken from ctx, never from a parameter.
+ ResolveEnv(ctx context.Context, skillName string) (env map[string]string, missing []string, err error)
+}
+
+// MissingSkillEnvError reports that execution was refused because a required
+// variable has no value at either layer. It is typed so the agent loop can
+// relay a sentence a person can act on instead of the KeyError or 401 the
+// script would otherwise produce.
+type MissingSkillEnvError struct {
+ SkillName string
+ Names []string
+}
+
+func (e *MissingSkillEnvError) Error() string {
+ // English, like every other error in this codebase: the agent relays this
+ // to the user and translates it into whatever language they are speaking.
+ return fmt.Sprintf(
+ "skill %q needs the environment variable(s) %s, which nobody has set yet. "+
+ "Set them under Settings → Environment variables and try again, "+
+ "or just tell me the env directly.",
+ e.SkillName, strings.Join(e.Names, ", "),
+ )
+}
+
+// applyResolvedEnv overlays resolved onto env WITHOUT displacing anything env
+// already carries.
+//
+// This is the second layer of reserved-name protection. Task 2's write-time
+// blacklist is the first, but a value written before that blacklist existed
+// would still be in the database, and letting it land on
+// WEKNORA_SKILL_OUTPUT_DIR would silently redirect the turn's artifacts to a
+// directory nobody drains. Skipping existing keys makes that impossible
+// regardless of what is stored.
+func applyResolvedEnv(env, resolved map[string]string) {
+ for name, value := range resolved {
+ if _, taken := env[name]; taken {
+ continue
+ }
+ env[name] = value
+ }
+}
diff --git a/internal/agent/skills/env_resolver_test.go b/internal/agent/skills/env_resolver_test.go
new file mode 100644
index 000000000..cfe22d158
--- /dev/null
+++ b/internal/agent/skills/env_resolver_test.go
@@ -0,0 +1,145 @@
+package skills
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// The runtime seeds the artifact directory variables before the resolver runs.
+// Whatever a user stored, those keys must survive untouched: they are how the
+// turn's products are collected.
+func TestApplyResolvedEnvAddsNewKeysAndKeepsExistingOnes(t *testing.T) {
+ env := map[string]string{
+ artifactOutputEnvVar: "/workspace/output",
+ artifactHistoryEnvVar: "/workspace/output",
+ }
+
+ applyResolvedEnv(env, map[string]string{
+ "TAVILY_API_KEY": "user-key",
+ artifactOutputEnvVar: "/tmp/hijacked",
+ artifactHistoryEnvVar: "/tmp/hijacked",
+ })
+
+ require.Equal(t, "user-key", env["TAVILY_API_KEY"])
+ require.Equal(t, "/workspace/output", env[artifactOutputEnvVar])
+ require.Equal(t, "/workspace/output", env[artifactHistoryEnvVar])
+}
+
+func TestApplyResolvedEnvToleratesNilResolved(t *testing.T) {
+ env := map[string]string{artifactOutputEnvVar: "/workspace/output"}
+
+ applyResolvedEnv(env, nil)
+
+ require.Equal(t, map[string]string{artifactOutputEnvVar: "/workspace/output"}, env)
+}
+
+// The message is read by the agent and relayed verbatim to a person, so it has
+// to name the skill, the variables, and where to go and fix it.
+func TestMissingSkillEnvErrorMessageNamesSkillVarsAndWhereToSetThem(t *testing.T) {
+ err := error(&MissingSkillEnvError{
+ SkillName: "web-search",
+ Names: []string{"TAVILY_API_KEY", "SERP_TOKEN"},
+ })
+
+ msg := err.Error()
+ require.Contains(t, msg, "web-search")
+ require.Contains(t, msg, "TAVILY_API_KEY")
+ require.Contains(t, msg, "SERP_TOKEN")
+ require.Contains(t, msg, "Environment variables")
+
+ var typed *MissingSkillEnvError
+ require.True(t, errors.As(err, &typed))
+ require.Equal(t, "web-search", typed.SkillName)
+ require.Equal(t, []string{"TAVILY_API_KEY", "SERP_TOKEN"}, typed.Names)
+}
+
+// stubEnvResolver records what ExecuteScript asked it for.
+type stubEnvResolver struct {
+ env map[string]string
+ missing []string
+ err error
+
+ calls []string
+}
+
+func (r *stubEnvResolver) ResolveEnv(
+ _ context.Context, skillName string,
+) (map[string]string, []string, error) {
+ r.calls = append(r.calls, skillName)
+ return r.env, r.missing, r.err
+}
+
+func TestExecuteScriptBlocksOnMissingRequiredEnv(t *testing.T) {
+ dir := preloadedSkillDir(t, "web-search", "search the web")
+ sandboxMgr := &recordingSandboxManager{}
+ resolver := &stubEnvResolver{missing: []string{"TAVILY_API_KEY"}}
+ mgr := NewManager(&ManagerConfig{SkillDirs: []string{dir}, Enabled: true}, sandboxMgr).
+ WithEnvResolver(resolver)
+ require.NoError(t, mgr.Initialize(context.Background()))
+
+ result, err := mgr.ExecuteScript(context.Background(), "web-search", "scripts/run.py", nil, "")
+
+ require.Nil(t, result)
+ var missing *MissingSkillEnvError
+ require.ErrorAs(t, err, &missing)
+ require.Equal(t, "web-search", missing.SkillName)
+ require.Equal(t, []string{"TAVILY_API_KEY"}, missing.Names)
+ // The whole point of blocking is that the script never runs.
+ require.Zero(t, sandboxMgr.calls)
+ require.Nil(t, sandboxMgr.config)
+}
+
+func TestExecuteScriptPropagatesResolverError(t *testing.T) {
+ dir := preloadedSkillDir(t, "web-search", "search the web")
+ sandboxMgr := &recordingSandboxManager{}
+ boom := errors.New("load user envs: connection refused")
+ mgr := NewManager(&ManagerConfig{SkillDirs: []string{dir}, Enabled: true}, sandboxMgr).
+ WithEnvResolver(&stubEnvResolver{err: boom})
+ require.NoError(t, mgr.Initialize(context.Background()))
+
+ _, err := mgr.ExecuteScript(context.Background(), "web-search", "scripts/run.py", nil, "")
+
+ require.ErrorIs(t, err, boom)
+ require.Zero(t, sandboxMgr.calls)
+}
+
+func TestExecuteScriptInjectsResolvedEnvOnceKeyedBySkillName(t *testing.T) {
+ dir := preloadedSkillDir(t, "web-search", "search the web")
+ sandboxMgr := &recordingSandboxManager{}
+ resolver := &stubEnvResolver{env: map[string]string{
+ "TAVILY_API_KEY": "user-key",
+ artifactOutputEnvVar: "/tmp/hijacked",
+ }}
+ mgr := NewManager(&ManagerConfig{SkillDirs: []string{dir}, Enabled: true}, sandboxMgr).
+ WithEnvResolver(resolver)
+ require.NoError(t, mgr.Initialize(context.Background()))
+
+ _, err := mgr.ExecuteScript(context.Background(), "web-search", "scripts/run.py", nil, "")
+
+ require.NoError(t, err)
+ require.Equal(t, []string{"web-search"}, resolver.calls)
+ require.Equal(t, 1, sandboxMgr.calls)
+ require.NotNil(t, sandboxMgr.config)
+ require.Equal(t, "user-key", sandboxMgr.config.Env["TAVILY_API_KEY"])
+ require.Equal(t, "/workspace/output", sandboxMgr.config.Env[artifactOutputEnvVar])
+}
+
+// Without a resolver the execution path must stay exactly as it was.
+func TestExecuteScriptWithoutResolverInjectsNothingExtra(t *testing.T) {
+ dir := preloadedSkillDir(t, "web-search", "search the web")
+ sandboxMgr := &recordingSandboxManager{}
+ mgr := NewManager(&ManagerConfig{SkillDirs: []string{dir}, Enabled: true}, sandboxMgr)
+ require.NoError(t, mgr.Initialize(context.Background()))
+
+ _, err := mgr.ExecuteScript(context.Background(), "web-search", "scripts/run.py", nil, "")
+
+ require.NoError(t, err)
+ require.Equal(t, 1, sandboxMgr.calls)
+ for key := range sandboxMgr.config.Env {
+ require.True(t, strings.HasPrefix(key, "WEKNORA_"), "unexpected env key %q", key)
+ }
+}
diff --git a/internal/agent/skills/manager.go b/internal/agent/skills/manager.go
index 8f0235cc4..899b66c94 100644
--- a/internal/agent/skills/manager.go
+++ b/internal/agent/skills/manager.go
@@ -82,6 +82,11 @@ type Manager struct {
// inside the sandbox.
tenantSource SkillSource
+ // envResolver supplies the per-caller environment for one execution. It
+ // is nil when the run has no installed skills, in which case execution
+ // keeps exactly its previous behaviour.
+ envResolver SkillEnvResolver
+
// Configuration
skillDirs []string
allowedSkills []string // Empty means all skills are allowed
@@ -130,6 +135,14 @@ func (m *Manager) WithTenantSource(source SkillSource) *Manager {
return m
}
+// WithEnvResolver attaches the per-caller environment resolver. Like
+// WithTenantSource it is part of construction and must be invoked before
+// Initialize, so it takes no lock.
+func (m *Manager) WithEnvResolver(resolver SkillEnvResolver) *Manager {
+ m.envResolver = resolver
+ return m
+}
+
// resolveSource decides which source owns one skill name. An installed image
// is the only copy the sandbox can run: falling back to a host preloaded
// skill would advertise files that are not in the image.
@@ -343,6 +356,29 @@ func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath strin
}
}
+ // Per-caller values are resolved here rather than baked into the sandbox
+ // at creation: an IM thread can have several people sharing one sandbox,
+ // so each turn's values must belong to that turn's speaker and must not
+ // linger where the next person could read them with `env`.
+ //
+ // The resolver runs after the two artifact keys above are seeded, so
+ // applyResolvedEnv's skip-existing rule protects exactly those two. It is
+ // NOT a blanket guarantee over every WEKNORA_ key: sessionInputEnvVar is
+ // only seeded when a session file store exists, and skillDirEnvVar is set
+ // later inside buildSkillExecuteConfig and so relies on that unconditional
+ // write instead. The write-time WEKNORA_ prefix blacklist
+ // (service.validateUserEnvName) is what covers those two.
+ if m.envResolver != nil {
+ resolved, missing, err := m.envResolver.ResolveEnv(ctx, skillName)
+ if err != nil {
+ return nil, err
+ }
+ if len(missing) > 0 {
+ return nil, &MissingSkillEnvError{SkillName: skillName, Names: missing}
+ }
+ applyResolvedEnv(env, resolved)
+ }
+
config, err := buildSkillExecuteConfig(
source, skillName, scriptPath, basePath, args, stdin, env, sessionID,
)
diff --git a/internal/agent/skills/tenant_source_test.go b/internal/agent/skills/tenant_source_test.go
index 0e5f5a233..a672ddfb4 100644
--- a/internal/agent/skills/tenant_source_test.go
+++ b/internal/agent/skills/tenant_source_test.go
@@ -292,11 +292,13 @@ func TestManagerKeepsPreloadedSkillExecutionWhenNoTenantSource(t *testing.T) {
type recordingSandboxManager struct {
config *sandbox.ExecuteConfig
+ calls int
}
func (m *recordingSandboxManager) Execute(
_ context.Context, config *sandbox.ExecuteConfig,
) (*sandbox.ExecuteResult, error) {
+ m.calls++
m.config = config
return &sandbox.ExecuteResult{ExitCode: 0}, nil
}
diff --git a/internal/agent/tools/shell_env_extract.go b/internal/agent/tools/shell_env_extract.go
new file mode 100644
index 000000000..a10e34597
--- /dev/null
+++ b/internal/agent/tools/shell_env_extract.go
@@ -0,0 +1,75 @@
+package tools
+
+import (
+ "regexp"
+ "strings"
+ "unicode"
+
+ "github.com/Tencent/WeKnora/internal/sandbox"
+)
+
+// assignmentPattern finds NAME=value in a model-built shell command.
+// It is not used on user chat text. The name must be UPPER_SNAKE_CASE so
+// flags like --model and URLs are not treated as environment variables.
+var assignmentPattern = regexp.MustCompile(
+ `(?:^|[;|&\s])(?:export\s+)?([A-Z_][A-Z0-9_]{0,127})=(?:"([^"]*)"|'([^']*)'|([^\s;|&]+))`,
+)
+
+func extractExportedEnv(command string) map[string]string {
+ out := map[string]string{}
+ for _, match := range assignmentPattern.FindAllStringSubmatch(command, -1) {
+ name := match[1]
+ value := match[2] + match[3] + match[4]
+ if name == "" || value == "" {
+ continue
+ }
+ out[name] = value
+ }
+ return out
+}
+
+func collectUsedSkillEnv(command string, toolEnv map[string]string) map[string]string {
+ out := extractExportedEnv(command)
+ for name, value := range toolEnv {
+ if strings.TrimSpace(value) == "" {
+ continue
+ }
+ out[name] = value
+ }
+ return out
+}
+
+func inferSkillName(explicit, command string) string {
+ if sandbox.IsValidSkillName(strings.TrimSpace(explicit)) {
+ return strings.TrimSpace(explicit)
+ }
+ prefix := sandbox.SkillsImageRoot + "/"
+ from := 0
+ for {
+ idx := strings.Index(command[from:], prefix)
+ if idx < 0 {
+ return ""
+ }
+ idx += from
+ name, ok := firstPathSegment(command[idx+len(prefix):])
+ if ok && sandbox.IsValidSkillName(name) {
+ return name
+ }
+ from = idx + len(prefix)
+ }
+}
+
+func firstPathSegment(rest string) (string, bool) {
+ end := 0
+ for end < len(rest) {
+ r := rune(rest[end])
+ if r == '/' || unicode.IsSpace(r) || r == '"' || r == '\'' || r == ';' || r == '&' || r == '|' {
+ break
+ }
+ end++
+ }
+ if end == 0 {
+ return "", false
+ }
+ return rest[:end], true
+}
diff --git a/internal/agent/tools/shell_env_extract_test.go b/internal/agent/tools/shell_env_extract_test.go
new file mode 100644
index 000000000..cdb3111bd
--- /dev/null
+++ b/internal/agent/tools/shell_env_extract_test.go
@@ -0,0 +1,67 @@
+package tools
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestExtractExportedEnvFromExportAndPrefixAssignment(t *testing.T) {
+ command := `unset HTTP_PROXY; export BIGMODEL_API_KEY="sk-abc.def"; cd /workspace && ./run`
+
+ got := extractExportedEnv(command)
+
+ require.Equal(t, "sk-abc.def", got["BIGMODEL_API_KEY"])
+ assert.NotContains(t, got, "HTTP_PROXY")
+}
+
+func TestExtractExportedEnvKeepsUnquotedAndSingleQuotedValues(t *testing.T) {
+ command := `export FOO=bare-value; export BAR='quoted value'; BAZ=prefix ./cmd`
+
+ got := extractExportedEnv(command)
+
+ assert.Equal(t, "bare-value", got["FOO"])
+ assert.Equal(t, "quoted value", got["BAR"])
+ assert.Equal(t, "prefix", got["BAZ"])
+}
+
+func TestExtractExportedEnvIgnoresFlagsAndURLs(t *testing.T) {
+ command := `python generate.py --model cogview-4 --size 1792x1024 https://example.com/x`
+
+ got := extractExportedEnv(command)
+
+ assert.Empty(t, got)
+}
+
+func TestCollectUsedSkillEnvOverlaysToolEnvOnExports(t *testing.T) {
+ command := `export BIGMODEL_API_KEY="from-command"; cd /opt/weknora/tenant/skills/bigmodel-image-video && python x.py`
+ toolEnv := map[string]string{"BIGMODEL_API_KEY": "from-tool", "EXTRA": "e"}
+
+ got := collectUsedSkillEnv(command, toolEnv)
+
+ assert.Equal(t, "from-tool", got["BIGMODEL_API_KEY"])
+ assert.Equal(t, "e", got["EXTRA"])
+}
+
+func TestInferSkillNamePrefersExplicitToolField(t *testing.T) {
+ command := `cd /opt/weknora/tenant/skills/other-skill && python x.py`
+
+ assert.Equal(t, "pdf-tools", inferSkillName("pdf-tools", command))
+}
+
+func TestInferSkillNameFromCdIntoSkillsRoot(t *testing.T) {
+ command := `cd /opt/weknora/tenant/skills/bigmodel-image-video && .venv/bin/python scripts/generate.py "草原"`
+
+ assert.Equal(t, "bigmodel-image-video", inferSkillName("", command))
+}
+
+func TestInferSkillNameFromScriptPath(t *testing.T) {
+ command := `/opt/weknora/tenant/skills/bigmodel-image-video/.venv/bin/python /opt/weknora/tenant/skills/bigmodel-image-video/scripts/generate.py`
+
+ assert.Equal(t, "bigmodel-image-video", inferSkillName("", command))
+}
+
+func TestInferSkillNameEmptyWhenCommandDoesNotTouchSkillsRoot(t *testing.T) {
+ assert.Empty(t, inferSkillName("", "ls /workspace"))
+}
diff --git a/internal/agent/tools/shell_exec.go b/internal/agent/tools/shell_exec.go
index bdc47fb46..36a892ede 100644
--- a/internal/agent/tools/shell_exec.go
+++ b/internal/agent/tools/shell_exec.go
@@ -39,6 +39,7 @@ import (
"time"
"unicode/utf8"
+ "github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
@@ -146,9 +147,6 @@ var shellExecTool = BaseTool{
intermediate files for later commands or skills.
## When NOT to Use
-- DO NOT use this to run a skill's main script — use ` + "`execute_skill_script`" + `
- which handles skill lookup, artifact collection, and proper interpreter
- selection.
- DO NOT judge a skill's dependencies with a bare ` + "`python3 -c`" + ` or
` + "`node -e`" + `: each skill keeps its dependencies in its own virtualenv or
node_modules, which neither of those resolves from here. ` + "`read_skill`" + `
@@ -170,6 +168,10 @@ var shellExecTool = BaseTool{
The complete visible result is always capped at 65536 bytes.
- ` + "`env`" + ` (optional): extra environment variables merged on top of the
sandbox's base env, e.g. ` + "`{\"PIP_INDEX_URL\": \"https://mirrors.tencent.com/pypi/simple\"}`" + `.
+- ` + "`skill_name`" + ` (optional): name of a skill whose environment variables should
+ be injected into this command's process only. Use when running a skill's
+ command by hand that needs its credentials; values are scoped to the current
+ caller and do not persist. Omit for ordinary commands.
## Returns
- ` + "`exit_code`" + `: 0 on success, non-zero on failure. Non-zero is NOT a tool
@@ -214,6 +216,12 @@ type ShellExecInput struct {
MaxStderrBytes int `json:"max_stderr_bytes,omitempty" jsonschema:"Maximum bytes returned from stderr. Defaults to 8192, hard-capped at 16384."`
// Env carries extra environment variables merged into the shell's env.
Env map[string]string `json:"env,omitempty" jsonschema:"Optional extra environment variables, e.g. {\"PIP_INDEX_URL\":\"https://mirrors.example.com/pypi/simple\"}."`
+ // SkillName, when set, pulls that skill's scoped environment variables
+ // (API keys) into this one command's process only. Resolution
+ // reuses the same SkillEnvResolver path as execute_skill_script, so values
+ // are per-caller (taken from ctx) and never persist. Omitting it leaves
+ // shell_exec's behaviour unchanged.
+ SkillName string `json:"skill_name,omitempty" jsonschema:"Optional skill name. When set, that skill's environment variables are injected into this command's process only (same resolution as execute_skill_script). Omit for ordinary commands."`
}
// SandboxInstallCommandExecutor is the privileged counterpart of
@@ -266,15 +274,29 @@ type ShellExecTool struct {
// sessions keep the 120s default; install mode uses the 10-minute cap
// because dependency installs routinely exceed two minutes.
defaultTimeout time.Duration
+ // envResolver, when non-nil, lets a call carrying SkillName pull that
+ // skill's per-caller env into the one command it runs. Nil means no skill
+ // env is ever injected — identical to today's behaviour.
+ envResolver skills.SkillEnvResolver
+ // envCapture, when non-nil, records declared skill credentials a
+ // successful ordinary command already used so the next named run can
+ // inject them. Install-mode tools never invoke it.
+ envCapture SkillEnvCapture
}
+// SkillEnvCapture records NAME=value pairs a successful shell_exec already
+// used for one skill. The tools package does not persist them; the agent
+// service supplies the write. Values must not be logged by the caller.
+type SkillEnvCapture func(ctx context.Context, skillName string, pairs map[string]string)
+
// NewShellExecTool constructs the tool. `executor` MUST NOT be nil:
// callers should feature-gate registration when the sandbox backend
// does not support ad-hoc shell execution (i.e. is not Cube).
-func NewShellExecTool(executor SandboxCommandExecutor) *ShellExecTool {
+func NewShellExecTool(executor SandboxCommandExecutor, envResolver skills.SkillEnvResolver) *ShellExecTool {
return &ShellExecTool{
BaseTool: shellExecTool,
executor: executor,
+ envResolver: envResolver,
workDirRoots: []string{defaultShellExecWorkDir},
}
}
@@ -291,6 +313,15 @@ func NewInstallShellExecTool(executor SandboxInstallCommandExecutor) *ShellExecT
}
}
+// WithEnvCapture attaches an optional capture hook. A nil hook is a no-op so
+// callers can pass the wiring result through without a nil check.
+func (t *ShellExecTool) WithEnvCapture(capture SkillEnvCapture) *ShellExecTool {
+ if t != nil {
+ t.envCapture = capture
+ }
+ return t
+}
+
// OutputLimitChars lets ToolRegistry preserve shell_exec's explicitly bounded,
// caller-configurable output instead of applying its lower generic limit again.
func (t *ShellExecTool) OutputLimitChars(args json.RawMessage) int {
@@ -375,7 +406,34 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typ
logger.Infof(ctx, "[Tool][ShellExec] session=%s work_dir=%s timeout=%s command=%q",
sessionID, workDir, timeout, command)
- res, err := t.executor.ExecShellCommand(ctx, sessionID, command, workDir, timeout, input.Env)
+ // The caller's config-wide variables apply to every command; a skill's
+ // declared credentials are added only when the model names the skill.
+ // Values come from ctx (the current principal), live only for this process,
+ // and are overlaid without displacing anything the model passed via env.
+ env := input.Env
+ if t.envResolver != nil {
+ resolved, missing, rerr := t.envResolver.ResolveEnv(ctx, input.SkillName)
+ if rerr != nil {
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf("failed to resolve environment variables: %v", rerr),
+ }, nil
+ }
+ if len(missing) > 0 {
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf(
+ "skill %q needs the environment variable(s) %s, which nobody has set yet. "+
+ "Set them under Settings → Environment variables and try again.",
+ input.SkillName, strings.Join(missing, ", ")),
+ }, nil
+ }
+ if len(resolved) > 0 && env == nil {
+ env = make(map[string]string)
+ }
+ overlayResolvedEnv(env, resolved)
+ }
+ res, err := t.executor.ExecShellCommand(ctx, sessionID, command, workDir, timeout, env)
if err != nil {
logger.Warnf(ctx, "[Tool][ShellExec] execution error: session=%s err=%v", sessionID, err)
errorText, _ := truncateShellStream(fmt.Sprintf("shell_exec failed: %v", err), maxShellExecErrorBytes)
@@ -385,6 +443,8 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typ
}, nil
}
+ t.maybeCaptureSkillEnv(ctx, input, res)
+
outputLimit := resolveShellOutputLimit(input.MaxOutputBytes)
stderrLimit := resolveShellStderrLimit(input.MaxStderrBytes)
stdout, stdoutTruncated, stdoutBinary := prepareShellStream(res.Stdout, outputLimit)
@@ -480,6 +540,49 @@ func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*typ
}, nil
}
+func (t *ShellExecTool) maybeCaptureSkillEnv(
+ ctx context.Context, input ShellExecInput, res *sandbox.ExecuteResult,
+) {
+ if t == nil || t.envCapture == nil || t.isInstallMode() {
+ return
+ }
+ if res == nil || res.ExitCode != 0 {
+ return
+ }
+ skillName := inferSkillName(input.SkillName, input.Command)
+ if skillName == "" {
+ return
+ }
+ pairs := collectUsedSkillEnv(input.Command, input.Env)
+ if len(pairs) == 0 {
+ return
+ }
+ t.envCapture(ctx, skillName, pairs)
+}
+
+func (t *ShellExecTool) isInstallMode() bool {
+ for _, root := range t.workDirRoots {
+ if root == sandbox.SkillsImageRoot {
+ return true
+ }
+ }
+ return false
+}
+
+// overlayResolvedEnv merges resolved skill-scoped variables into env WITHOUT
+// displacing any key env already carries. Model-supplied values (via the env
+// parameter) therefore take precedence over resolved ones, matching the
+// existing execute_skill_script contract. It mirrors skills.applyResolvedEnv,
+// duplicated here to avoid exporting that helper from the skills package.
+func overlayResolvedEnv(env, resolved map[string]string) {
+ for name, value := range resolved {
+ if _, taken := env[name]; taken {
+ continue
+ }
+ env[name] = value
+ }
+}
+
// allowedWorkDirRoots defaults to /workspace so a zero-value tool (or one
// built before install mode existed) keeps the ordinary contract.
func (t *ShellExecTool) allowedWorkDirRoots() []string {
diff --git a/internal/agent/tools/shell_exec_test.go b/internal/agent/tools/shell_exec_test.go
index 9dc7a51de..43926ec17 100644
--- a/internal/agent/tools/shell_exec_test.go
+++ b/internal/agent/tools/shell_exec_test.go
@@ -43,7 +43,7 @@ func shellExecTestContext() context.Context {
func TestShellExecRejectsWorkDirOutsideWorkspace(t *testing.T) {
executor := &fakeShellExecutor{}
- tool := NewShellExecTool(executor)
+ tool := NewShellExecTool(executor, nil)
result, err := tool.Execute(shellExecTestContext(), json.RawMessage(
`{"command":"pwd","work_dir":"/etc"}`,
@@ -57,7 +57,7 @@ func TestShellExecRejectsWorkDirOutsideWorkspace(t *testing.T) {
func TestShellExecTimeoutHonorsAndCapsRequestedValue(t *testing.T) {
executor := &fakeShellExecutor{}
- tool := NewShellExecTool(executor)
+ tool := NewShellExecTool(executor, nil)
result, err := tool.Execute(shellExecTestContext(), json.RawMessage(
`{"command":"sleep 1","timeout_sec":999}`,
@@ -100,7 +100,7 @@ func TestShellExecConfigurableOutputAndRegistryOverride(t *testing.T) {
ExitCode: 0,
}}
registry := NewToolRegistry()
- registry.RegisterTool(NewShellExecTool(executor))
+ registry.RegisterTool(NewShellExecTool(executor, nil))
result, err := registry.ExecuteTool(shellExecTestContext(), ToolShellExec, json.RawMessage(
`{"command":"cat large.txt","max_output_bytes":32768}`,
@@ -115,7 +115,7 @@ func TestShellExecConfigurableOutputAndRegistryOverride(t *testing.T) {
}
func TestShellExecOutputLimitIsHardCapped(t *testing.T) {
- tool := NewShellExecTool(&fakeShellExecutor{})
+ tool := NewShellExecTool(&fakeShellExecutor{}, nil)
limit := tool.OutputLimitChars(json.RawMessage(`{"max_output_bytes":999999}`))
@@ -129,7 +129,7 @@ func TestShellExecSuppressesBinaryStreams(t *testing.T) {
Stderr: "text error",
ExitCode: 0,
}}
- tool := NewShellExecTool(executor)
+ tool := NewShellExecTool(executor, nil)
result, err := tool.Execute(shellExecTestContext(), json.RawMessage(`{"command":"cat image.bin"}`))
@@ -144,7 +144,7 @@ func TestShellExecSuppressesBinaryStreams(t *testing.T) {
}
func TestShellExecDescriptionSupportsGeneralExploration(t *testing.T) {
- description := NewShellExecTool(&fakeShellExecutor{}).Description()
+ description := NewShellExecTool(&fakeShellExecutor{}, nil).Description()
for _, command := range []string{"find", "file", "sed", "head", "tail", "cat", "grep", "awk"} {
assert.Contains(t, description, command)
@@ -160,7 +160,7 @@ func TestShellExecBoundsStdoutStderrErrorAndTotal(t *testing.T) {
Error: strings.Repeat("e", 8*1024),
}}
- result, err := NewShellExecTool(executor).Execute(
+ result, err := NewShellExecTool(executor, nil).Execute(
shellExecTestContext(),
json.RawMessage(`{"command":"noisy","max_output_bytes":999999,"max_stderr_bytes":999999}`),
)
@@ -180,7 +180,7 @@ func TestShellExecBoundsStdoutStderrErrorAndTotal(t *testing.T) {
func TestShellExecBoundsExecutorErrors(t *testing.T) {
executor := &fakeShellExecutor{err: errors.New(strings.Repeat("network failure ", 1024))}
- result, err := NewShellExecTool(executor).Execute(
+ result, err := NewShellExecTool(executor, nil).Execute(
shellExecTestContext(),
json.RawMessage(`{"command":"echo hi"}`),
)
@@ -198,3 +198,72 @@ func TestTruncateShellStreamIncludesMarkerWithinLimit(t *testing.T) {
assert.LessOrEqual(t, len(output), 100)
assert.Contains(t, output, "truncated")
}
+
+type recordedCapture struct {
+ skillName string
+ pairs map[string]string
+ calls int
+}
+
+func (r *recordedCapture) capture(_ context.Context, skillName string, pairs map[string]string) {
+ r.calls++
+ r.skillName = skillName
+ r.pairs = pairs
+}
+
+func TestShellExecCapturesUsedEnvAfterSuccessfulCommand(t *testing.T) {
+ recorder := &recordedCapture{}
+ tool := NewShellExecTool(&fakeShellExecutor{}, nil).WithEnvCapture(recorder.capture)
+
+ result, err := tool.Execute(shellExecTestContext(), json.RawMessage(
+ `{"command":"export USER_TOKEN=from-command; cd /opt/weknora/tenant/skills/pdf-tools && python x.py","env":{"EXTRA_TOKEN":"from-tool"}}`,
+ ))
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ require.Equal(t, 1, recorder.calls)
+ require.Equal(t, "pdf-tools", recorder.skillName)
+ require.Equal(t, "from-command", recorder.pairs["USER_TOKEN"])
+ require.Equal(t, "from-tool", recorder.pairs["EXTRA_TOKEN"])
+}
+
+func TestShellExecDoesNotCaptureWhenCommandFails(t *testing.T) {
+ recorder := &recordedCapture{}
+ tool := NewShellExecTool(&fakeShellExecutor{result: &sandbox.ExecuteResult{ExitCode: 1}}, nil).
+ WithEnvCapture(recorder.capture)
+
+ result, err := tool.Execute(shellExecTestContext(), json.RawMessage(
+ `{"command":"export USER_TOKEN=x; cd /opt/weknora/tenant/skills/pdf-tools && false"}`,
+ ))
+
+ require.NoError(t, err)
+ require.True(t, result.Success, "non-zero exit is still a successful tool call")
+ require.Zero(t, recorder.calls)
+}
+
+func TestShellExecDoesNotCaptureWhenExecutorErrors(t *testing.T) {
+ recorder := &recordedCapture{}
+ tool := NewShellExecTool(&fakeShellExecutor{err: errors.New("sandbox down")}, nil).
+ WithEnvCapture(recorder.capture)
+
+ result, err := tool.Execute(shellExecTestContext(), json.RawMessage(
+ `{"command":"export USER_TOKEN=x; cd /opt/weknora/tenant/skills/pdf-tools && true"}`,
+ ))
+
+ require.NoError(t, err)
+ require.False(t, result.Success)
+ require.Zero(t, recorder.calls)
+}
+
+func TestInstallShellExecDoesNotCapture(t *testing.T) {
+ recorder := &recordedCapture{}
+ tool := NewInstallShellExecTool(&fakeInstallShellExecutor{}).WithEnvCapture(recorder.capture)
+
+ result, err := tool.Execute(shellExecTestContext(), json.RawMessage(
+ `{"command":"export USER_TOKEN=x; cd /opt/weknora/tenant/skills/pdf-tools && pip install x"}`,
+ ))
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ require.Zero(t, recorder.calls)
+}
diff --git a/internal/application/repository/tenant_skill.go b/internal/application/repository/tenant_skill.go
index fb44c69de..ce6c285da 100644
--- a/internal/application/repository/tenant_skill.go
+++ b/internal/application/repository/tenant_skill.go
@@ -7,6 +7,7 @@ import (
"github.com/Tencent/WeKnora/internal/types"
"gorm.io/gorm"
+ "gorm.io/gorm/clause"
)
// TenantSkillRepository persists skills installed onto sandbox configs and the
@@ -21,9 +22,15 @@ type TenantSkillRepository interface {
GetSkillByName(ctx context.Context, tenantID uint64, configID, name string) (*types.TenantSkillEntity, error)
// ListSkillsByConfig returns the installed skill projection for one sandbox config.
ListSkillsByConfig(ctx context.Context, tenantID uint64, configID string) ([]*types.TenantSkillEntity, error)
+ // ListSkillsByTenant spans every sandbox config of one workspace, for the
+ // views that are about the user rather than about a config.
+ ListSkillsByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantSkillEntity, error)
// UpdateSkill writes the mutable projection fields after install/remove state changes.
UpdateSkill(ctx context.Context, e *types.TenantSkillEntity) error
- // DeleteSkill soft-deletes metadata only; image cleanup is represented by snapshots.
+ // DeleteSkill soft-deletes the metadata row and, in the same transaction,
+ // hard-deletes the per-principal env values hanging off it. Image cleanup is
+ // represented by snapshots. When the scoped key matches no skill, nothing is
+ // deleted and the call succeeds.
DeleteSkill(ctx context.Context, tenantID uint64, configID, skillID string) error
// ListStaleInstalling finds abandoned install/remove runs for the reaper.
ListStaleInstalling(ctx context.Context, olderThan time.Time) ([]*types.TenantSkillEntity, error)
@@ -38,6 +45,28 @@ type TenantSkillRepository interface {
// config is deleted and its provider-side snapshots are already gone; never
// call this during an ordinary image switch (old snapshots stay in the ledger).
DeleteSnapshotRowsByConfig(ctx context.Context, tenantID uint64, configID string) error
+
+ // ListUserEnvVars returns one principal's own values for one scope,
+ // decrypted. An empty skillID selects the config-wide variables.
+ ListUserEnvVars(
+ ctx context.Context, tenantID uint64, p types.Principal, configID, skillID string,
+ ) ([]*types.TenantUserEnvVar, error)
+ // ListUserEnvVarsByConfig returns every scope at once, for the settings
+ // page that renders a whole config in one go.
+ ListUserEnvVarsByConfig(
+ ctx context.Context, tenantID uint64, p types.Principal, configID string,
+ ) ([]*types.TenantUserEnvVar, error)
+ // UpsertUserEnvVar writes a principal's value, replacing any previous one
+ // for the same (tenant, principal, config, skill, name).
+ UpsertUserEnvVar(ctx context.Context, e *types.TenantUserEnvVar) error
+ // DeleteUserEnvVar removes one value, returning types.ErrEnvVarNotFound
+ // when there was nothing to remove.
+ DeleteUserEnvVar(
+ ctx context.Context, tenantID uint64, p types.Principal, configID, skillID, name string,
+ ) error
+ // DeleteUserEnvVarsByConfig removes every principal's values for a config,
+ // including the config-wide ones DeleteSkill never sees.
+ DeleteUserEnvVarsByConfig(ctx context.Context, tenantID uint64, configID string) error
}
type tenantSkillRepository struct{ db *gorm.DB }
@@ -97,6 +126,20 @@ func (r *tenantSkillRepository) ListSkillsByConfig(
return list, nil
}
+func (r *tenantSkillRepository) ListSkillsByTenant(
+ ctx context.Context, tenantID uint64,
+) ([]*types.TenantSkillEntity, error) {
+ var list []*types.TenantSkillEntity
+ err := r.db.WithContext(ctx).
+ Where("tenant_id = ?", tenantID).
+ Order("created_at ASC").
+ Find(&list).Error
+ if err != nil {
+ return nil, err
+ }
+ return list, nil
+}
+
// UpdateSkill writes the mutable columns explicitly so a zero-valued field on
// the passed entity cannot silently wipe state written by a concurrent job.
func (r *tenantSkillRepository) UpdateSkill(ctx context.Context, e *types.TenantSkillEntity) error {
@@ -111,6 +154,7 @@ func (r *tenantSkillRepository) UpdateSkill(ctx context.Context, e *types.Tenant
"bundle_ref": e.BundleRef,
"bundle_sha256": e.BundleSHA256,
"enabled": e.Enabled,
+ "envs": e.Envs,
"installed_snapshot_id": e.InstalledSnapshotID,
"install_session_id": e.InstallSessionID,
"install_message_id": e.InstallMessageID,
@@ -121,12 +165,30 @@ func (r *tenantSkillRepository) UpdateSkill(ctx context.Context, e *types.Tenant
}).Error
}
+// DeleteSkill soft-deletes the skill and hard-deletes the user values that
+// belonged to it, in one transaction. The cleanup cannot be a cascading foreign
+// key: tenant_skills is soft-deleted, so ON DELETE CASCADE would never fire and
+// the credentials would outlive the skill they were entered for.
func (r *tenantSkillRepository) DeleteSkill(
ctx context.Context, tenantID uint64, configID, skillID string,
) error {
- return r.db.WithContext(ctx).
- Where("tenant_id = ? AND sandbox_config_id = ? AND id = ?", tenantID, configID, skillID).
- Delete(&types.TenantSkillEntity{}).Error
+ return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ res := tx.
+ Where("tenant_id = ? AND sandbox_config_id = ? AND id = ?", tenantID, configID, skillID).
+ Delete(&types.TenantSkillEntity{})
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected == 0 {
+ return nil
+ }
+ if err := tx.
+ Where("tenant_id = ? AND skill_id = ?", tenantID, skillID).
+ Delete(&types.TenantUserEnvVar{}).Error; err != nil {
+ return err
+ }
+ return nil
+ })
}
func (r *tenantSkillRepository) ListStaleInstalling(
@@ -195,3 +257,83 @@ func (r *tenantSkillRepository) DeleteSnapshotRowsByConfig(
Where("tenant_id = ? AND sandbox_config_id = ?", tenantID, configID).
Delete(&types.TenantSkillSnapshotEntity{}).Error
}
+
+func (r *tenantSkillRepository) ListUserEnvVars(
+ ctx context.Context, tenantID uint64, p types.Principal, configID, skillID string,
+) ([]*types.TenantUserEnvVar, error) {
+ p = p.Normalize()
+ var list []*types.TenantUserEnvVar
+ err := r.db.WithContext(ctx).
+ Where("tenant_id = ? AND principal_type = ? AND principal_id = ?"+
+ " AND sandbox_config_id = ? AND skill_id = ?",
+ tenantID, p.Type, p.ID, configID, skillID).
+ Order("name ASC").
+ Find(&list).Error
+ if err != nil {
+ return nil, err
+ }
+ return list, nil
+}
+
+func (r *tenantSkillRepository) ListUserEnvVarsByConfig(
+ ctx context.Context, tenantID uint64, p types.Principal, configID string,
+) ([]*types.TenantUserEnvVar, error) {
+ p = p.Normalize()
+ var list []*types.TenantUserEnvVar
+ err := r.db.WithContext(ctx).
+ Where("tenant_id = ? AND principal_type = ? AND principal_id = ? AND sandbox_config_id = ?",
+ tenantID, p.Type, p.ID, configID).
+ Order("skill_id ASC, name ASC").
+ Find(&list).Error
+ if err != nil {
+ return nil, err
+ }
+ return list, nil
+}
+
+// UpsertUserEnvVar conflicts on the unique index columns so a re-entered value
+// replaces the previous one instead of accumulating rows.
+func (r *tenantSkillRepository) UpsertUserEnvVar(
+ ctx context.Context, e *types.TenantUserEnvVar,
+) error {
+ // Persist a copy: BeforeSave encrypts the receiver in place, and the
+ // caller keeps holding the plaintext it passed in.
+ stored := *e
+ p := types.Principal{Type: stored.PrincipalType, ID: stored.PrincipalID}.Normalize()
+ stored.PrincipalType, stored.PrincipalID = p.Type, p.ID
+ return r.db.WithContext(ctx).
+ Clauses(clause.OnConflict{
+ Columns: []clause.Column{
+ {Name: "tenant_id"}, {Name: "principal_type"}, {Name: "principal_id"},
+ {Name: "sandbox_config_id"}, {Name: "skill_id"}, {Name: "name"},
+ },
+ DoUpdates: clause.AssignmentColumns([]string{"value", "updated_at"}),
+ }).
+ Create(&stored).Error
+}
+
+func (r *tenantSkillRepository) DeleteUserEnvVar(
+ ctx context.Context, tenantID uint64, p types.Principal, configID, skillID, name string,
+) error {
+ p = p.Normalize()
+ res := r.db.WithContext(ctx).
+ Where("tenant_id = ? AND principal_type = ? AND principal_id = ?"+
+ " AND sandbox_config_id = ? AND skill_id = ? AND name = ?",
+ tenantID, p.Type, p.ID, configID, skillID, name).
+ Delete(&types.TenantUserEnvVar{})
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected == 0 {
+ return types.ErrEnvVarNotFound
+ }
+ return nil
+}
+
+func (r *tenantSkillRepository) DeleteUserEnvVarsByConfig(
+ ctx context.Context, tenantID uint64, configID string,
+) error {
+ return r.db.WithContext(ctx).
+ Where("tenant_id = ? AND sandbox_config_id = ?", tenantID, configID).
+ Delete(&types.TenantUserEnvVar{}).Error
+}
diff --git a/internal/application/repository/tenant_skill_test.go b/internal/application/repository/tenant_skill_test.go
index adae048b5..cf9f47f5a 100644
--- a/internal/application/repository/tenant_skill_test.go
+++ b/internal/application/repository/tenant_skill_test.go
@@ -13,18 +13,27 @@ import (
)
func newSkillTestRepo(t *testing.T) TenantSkillRepository {
+ t.Helper()
+ repo, _ := newSkillTestRepoWithDB(t)
+ return repo
+}
+
+// newSkillTestRepoWithDB also hands back the handle, for the tests that must
+// read a column raw to prove a secret is encrypted at rest.
+func newSkillTestRepoWithDB(t *testing.T) (TenantSkillRepository, *gorm.DB) {
t.Helper()
db, err := gorm.Open(sqlite.Open("file:"+uuid.NewString()+"?mode=memory&cache=shared"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(
&types.TenantSkillEntity{}, &types.TenantSkillSnapshotEntity{},
+ &types.TenantUserEnvVar{},
))
// AutoMigrate cannot express the partial unique index, so add it here to
// match the production migration.
require.NoError(t, db.Exec(
`CREATE UNIQUE INDEX IF NOT EXISTS uq_tenant_skills_config_name
ON tenant_skills (sandbox_config_id, name) WHERE deleted_at IS NULL`).Error)
- return NewTenantSkillRepository(db)
+ return NewTenantSkillRepository(db), db
}
func skillRow(id, configID, name string) *types.TenantSkillEntity {
@@ -166,3 +175,232 @@ func TestMarkSnapshotStateIsTenantScoped(t *testing.T) {
"a snapshot row must not move when the caller is a different tenant")
require.Empty(t, rows[0].SnapshotID)
}
+
+// skillEnvTestAESKey is exactly 32 bytes, the only length GetAESKey accepts.
+const skillEnvTestAESKey = "0123456789abcdef0123456789abcdef"
+
+func userEnvRow(p types.Principal, skillID, name, value string) *types.TenantUserEnvVar {
+ return &types.TenantUserEnvVar{
+ TenantID: 7, PrincipalType: p.Type, PrincipalID: p.ID,
+ SandboxConfigID: "cfg-1", SkillID: skillID, Name: name, Value: value,
+ }
+}
+
+func TestSkillRepoUpdatePersistsEnvs(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", skillEnvTestAESKey)
+ repo, db := newSkillTestRepoWithDB(t)
+ ctx := context.Background()
+ require.NoError(t, repo.CreateSkill(ctx, skillRow("sk-a", "cfg-1", "pdf")))
+
+ row, err := repo.GetSkill(ctx, 7, "cfg-1", "sk-a")
+ require.NoError(t, err)
+ row.Envs = types.SkillEnvVars{
+ {Name: "TAVILY_API_KEY", Description: "search key", Required: true, Value: "tvly-admin"},
+ {Name: "OPTIONAL_KEY"},
+ }
+ require.NoError(t, repo.UpdateSkill(ctx, row))
+
+ got, err := repo.GetSkill(ctx, 7, "cfg-1", "sk-a")
+ require.NoError(t, err)
+ require.Len(t, got.Envs, 2)
+ require.Equal(t, "TAVILY_API_KEY", got.Envs[0].Name)
+ require.True(t, got.Envs[0].Required)
+ require.Equal(t, "tvly-admin", got.Envs[0].Value)
+ require.Empty(t, got.Envs[1].Value)
+
+ var stored string
+ require.NoError(t, db.Raw(`SELECT envs FROM tenant_skills WHERE id = ?`, "sk-a").Scan(&stored).Error)
+ require.NotContains(t, stored, "tvly-admin", "the admin value must be encrypted at rest")
+ require.Contains(t, stored, "TAVILY_API_KEY", "the declaration stays readable without a key")
+}
+
+func TestUpsertUserEnvIsIdempotentPerPrincipalSkillAndName(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", skillEnvTestAESKey)
+ repo, db := newSkillTestRepoWithDB(t)
+ ctx := context.Background()
+ alice := types.Principal{Type: types.PrincipalWebUser, ID: "u-alice"}
+
+ first := userEnvRow(alice, "sk-a", "TAVILY_API_KEY", "first")
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, first))
+ require.Equal(t, "first", first.Value,
+ "persisting an encrypted value must not replace the caller's plaintext")
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(alice, "sk-a", "TAVILY_API_KEY", "second")))
+
+ list, err := repo.ListUserEnvVars(ctx, 7, alice, "cfg-1", "sk-a")
+ require.NoError(t, err)
+ require.Len(t, list, 1, "a second write to the same tuple replaces the value, it does not add a row")
+ require.Equal(t, "second", list[0].Value)
+
+ var stored string
+ require.NoError(t, db.Raw(`SELECT value FROM tenant_user_env_vars`).Scan(&stored).Error)
+ require.NotContains(t, stored, "second", "the user value must be encrypted at rest")
+}
+
+func TestUserEnvsAreIsolatedBetweenPrincipals(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", skillEnvTestAESKey)
+ repo := newSkillTestRepo(t)
+ ctx := context.Background()
+ alice := types.Principal{Type: types.PrincipalWebUser, ID: "u-alice"}
+ // Same ID, different type: the IM path's synthetic account is why the key
+ // is the whole principal rather than a user id.
+ imUser := types.Principal{Type: types.PrincipalIMUser, ID: "u-alice"}
+
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(alice, "sk-a", "TAVILY_API_KEY", "alice-key")))
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(imUser, "sk-a", "TAVILY_API_KEY", "im-key")))
+
+ aliceEnvs, err := repo.ListUserEnvVars(ctx, 7, alice, "cfg-1", "sk-a")
+ require.NoError(t, err)
+ require.Len(t, aliceEnvs, 1)
+ require.Equal(t, "alice-key", aliceEnvs[0].Value)
+
+ imEnvs, err := repo.ListUserEnvVars(ctx, 7, imUser, "cfg-1", "sk-a")
+ require.NoError(t, err)
+ require.Len(t, imEnvs, 1)
+ require.Equal(t, "im-key", imEnvs[0].Value)
+}
+
+func TestDeleteSkillRemovesOnlyThatSkillsUserEnvs(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", skillEnvTestAESKey)
+ repo := newSkillTestRepo(t)
+ ctx := context.Background()
+ alice := types.Principal{Type: types.PrincipalWebUser, ID: "u-alice"}
+
+ require.NoError(t, repo.CreateSkill(ctx, skillRow("sk-a", "cfg-1", "pdf")))
+ require.NoError(t, repo.CreateSkill(ctx, skillRow("sk-b", "cfg-1", "search")))
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(alice, "sk-a", "TAVILY_API_KEY", "a")))
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(alice, "sk-b", "TAVILY_API_KEY", "b")))
+
+ require.NoError(t, repo.DeleteSkill(ctx, 7, "cfg-1", "sk-a"))
+
+ // tenant_skills is soft-deleted, so a cascading foreign key would never
+ // fire; the delete has to be explicit or the values outlive the skill.
+ gone, err := repo.ListUserEnvVars(ctx, 7, alice, "cfg-1", "sk-a")
+ require.NoError(t, err)
+ require.Empty(t, gone, "deleting a skill must take its user values with it")
+
+ kept, err := repo.ListUserEnvVars(ctx, 7, alice, "cfg-1", "sk-b")
+ require.NoError(t, err)
+ require.Len(t, kept, 1, "another skill's values must survive")
+ require.Equal(t, "b", kept[0].Value)
+}
+
+func TestDeleteSkillWithMismatchedConfigKeepsSkillAndUserEnvs(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", skillEnvTestAESKey)
+ repo := newSkillTestRepo(t)
+ ctx := context.Background()
+ alice := types.Principal{Type: types.PrincipalWebUser, ID: "u-alice"}
+
+ require.NoError(t, repo.CreateSkill(ctx, skillRow("sk-a", "cfg-1", "pdf")))
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(alice, "sk-a", "TAVILY_API_KEY", "secret")))
+
+ require.NoError(t, repo.DeleteSkill(ctx, 7, "cfg-stale", "sk-a"),
+ "a missing scoped row remains an idempotent no-op")
+
+ skill, err := repo.GetSkill(ctx, 7, "cfg-1", "sk-a")
+ require.NoError(t, err)
+ require.NotNil(t, skill, "the mismatched config must not soft-delete the skill")
+
+ kept, err := repo.ListUserEnvVars(ctx, 7, alice, "cfg-1", "sk-a")
+ require.NoError(t, err)
+ require.Len(t, kept, 1,
+ "user values must survive when the scoped soft delete affects no rows")
+ require.Equal(t, "secret", kept[0].Value)
+}
+
+func TestDeleteUserEnvReportsAnAlreadyDeletedRow(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", skillEnvTestAESKey)
+ repo := newSkillTestRepo(t)
+ ctx := context.Background()
+ alice := types.Principal{Type: types.PrincipalWebUser, ID: "u-alice"}
+
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(alice, "sk-a", "TAVILY_API_KEY", "a")))
+ require.NoError(t, repo.DeleteUserEnvVar(ctx, 7, alice, "cfg-1", "sk-a", "TAVILY_API_KEY"))
+
+ err := repo.DeleteUserEnvVar(ctx, 7, alice, "cfg-1", "sk-a", "TAVILY_API_KEY")
+ require.ErrorIs(t, err, types.ErrEnvVarNotFound)
+}
+
+func TestListUserEnvVarsByConfigSpansScopesForOnePrincipal(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", skillEnvTestAESKey)
+ repo := newSkillTestRepo(t)
+ ctx := context.Background()
+ alice := types.Principal{Type: types.PrincipalWebUser, ID: "u-alice"}
+ bob := types.Principal{Type: types.PrincipalWebUser, ID: "u-bob"}
+
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(alice, "sk-a", "ONE", "1")))
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(alice, "", "HTTP_PROXY", "2")))
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(bob, "sk-a", "ONE", "3")))
+
+ list, err := repo.ListUserEnvVarsByConfig(ctx, 7, alice, "cfg-1")
+
+ require.NoError(t, err)
+ require.Len(t, list, 2, "both the config-wide and the skill-scoped value belong to alice")
+ require.Equal(t, "", list[0].SkillID, "the config-wide row sorts first")
+ require.Equal(t, "HTTP_PROXY", list[0].Name)
+ require.Equal(t, "sk-a", list[1].SkillID)
+}
+
+// The same name in two scopes is two values: the config-wide one applies to
+// every execution, the skill-scoped one only when a tool names that skill.
+func TestUserEnvVarsKeepScopesApart(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", skillEnvTestAESKey)
+ repo := newSkillTestRepo(t)
+ ctx := context.Background()
+ alice := types.Principal{Type: types.PrincipalWebUser, ID: "u-alice"}
+
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(alice, "", "TOKEN", "config-wide")))
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(alice, "sk-a", "TOKEN", "skill-scoped")))
+
+ wide, err := repo.ListUserEnvVars(ctx, 7, alice, "cfg-1", "")
+ require.NoError(t, err)
+ require.Len(t, wide, 1)
+ require.Equal(t, "config-wide", wide[0].Value)
+
+ scoped, err := repo.ListUserEnvVars(ctx, 7, alice, "cfg-1", "sk-a")
+ require.NoError(t, err)
+ require.Len(t, scoped, 1)
+ require.Equal(t, "skill-scoped", scoped[0].Value)
+}
+
+// Deleting a config must take the config-wide rows too: DeleteSkill only ever
+// sees rows filed under a skill.
+func TestDeleteUserEnvVarsByConfigTakesEveryScopeAndPrincipal(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", skillEnvTestAESKey)
+ repo := newSkillTestRepo(t)
+ ctx := context.Background()
+ alice := types.Principal{Type: types.PrincipalWebUser, ID: "u-alice"}
+ bob := types.Principal{Type: types.PrincipalWebUser, ID: "u-bob"}
+
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(alice, "", "HTTP_PROXY", "a")))
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(alice, "sk-a", "TOKEN", "b")))
+ require.NoError(t, repo.UpsertUserEnvVar(ctx, userEnvRow(bob, "", "HTTP_PROXY", "c")))
+
+ require.NoError(t, repo.DeleteUserEnvVarsByConfig(ctx, 7, "cfg-1"))
+
+ aliceLeft, err := repo.ListUserEnvVarsByConfig(ctx, 7, alice, "cfg-1")
+ require.NoError(t, err)
+ require.Empty(t, aliceLeft)
+ bobLeft, err := repo.ListUserEnvVarsByConfig(ctx, 7, bob, "cfg-1")
+ require.NoError(t, err)
+ require.Empty(t, bobLeft)
+}
+
+func TestListSkillsByTenantSpansConfigsAndStopsAtTheTenant(t *testing.T) {
+ repo := newSkillTestRepo(t)
+ ctx := context.Background()
+
+ require.NoError(t, repo.CreateSkill(ctx, skillRow("sk-a", "cfg-1", "pdf")))
+ require.NoError(t, repo.CreateSkill(ctx, skillRow("sk-b", "cfg-2", "search")))
+ other := skillRow("sk-other", "cfg-3", "pdf")
+ other.TenantID = 8
+ require.NoError(t, repo.CreateSkill(ctx, other))
+
+ list, err := repo.ListSkillsByTenant(ctx, 7)
+ require.NoError(t, err)
+ ids := make([]string, 0, len(list))
+ for _, e := range list {
+ ids = append(ids, e.ID)
+ }
+ require.ElementsMatch(t, []string{"sk-a", "sk-b"}, ids,
+ "every config of the tenant, and nothing from another tenant")
+}
diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go
index 319b0407f..02a29a90f 100644
--- a/internal/application/service/agent_service.go
+++ b/internal/application/service/agent_service.go
@@ -11,6 +11,7 @@ import (
"github.com/Tencent/WeKnora/internal/agent/approval"
"github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/Tencent/WeKnora/internal/agent/tools"
+ "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
@@ -402,6 +403,9 @@ func (s *agentService) initializeSkillsManager(
if source := s.tenantSkillSource(ctx, config); source != nil {
skillsManager.WithTenantSource(source)
}
+ if resolver := s.userEnvResolver(ctx, config); resolver != nil {
+ skillsManager.WithEnvResolver(resolver)
+ }
// Initialize (discover skills)
if err := skillsManager.Initialize(ctx); err != nil {
@@ -444,7 +448,7 @@ func (s *agentService) initializeSkillsManager(
}
}
- registerSandboxShellTool(ctx, toolRegistry, sandboxMgr, config)
+ s.registerSandboxShellTool(ctx, toolRegistry, sandboxMgr, config)
}
return skillsManager, nil
@@ -478,6 +482,66 @@ func (s *agentService) tenantSkillSource(
})
}
+// userEnvResolver builds the per-caller environment resolver for this run, or
+// nil when there is no sandbox config to resolve against.
+//
+// It is built even when the run has no installed skills: the caller's
+// config-wide variables are injected into every execution, skills or not.
+//
+// The repository is constructed from s.db here rather than injected:
+// NewAgentService already takes 23 parameters, and this is the only place in
+// the agent path that touches the user env table.
+func (s *agentService) userEnvResolver(
+ ctx context.Context, config *types.AgentConfig,
+) skills.SkillEnvResolver {
+ configID := config.SandboxConfigID
+ if configID == "" {
+ return nil
+ }
+ rows := config.TenantSkills
+ if s.db == nil {
+ // Unreachable in production, but a wiring regression here would drop
+ // every admin and user value silently and present to a member as "my
+ // key stopped working" with nothing in the logs.
+ logger.Warnf(ctx,
+ "[skill] no database handle: sandbox config %s will run without "+
+ "any configured environment variable", configID)
+ return nil
+ }
+ // The workspace is read off a row for the same reason tenantSkillSource
+ // does it: the rows were fetched under the caller's workspace, and a value
+ // must never be looked up in a different one. With no rows there is nothing
+ // to disagree with the context.
+ tenantID, _ := types.TenantIDFromContext(ctx)
+ if len(rows) > 0 {
+ tenantID = rows[0].TenantID
+ }
+ if tenantID == 0 {
+ return nil
+ }
+ return NewUserEnvResolver(rows, repository.NewTenantSkillRepository(s.db), tenantID, configID)
+}
+
+// skillEnvCapture writes declared skill credentials a successful shell_exec
+// already used, for the current principal. Nil when there is nothing to write
+// against. Errors stay inside the callback so a failed persist cannot change
+// the tool result the model already received.
+func (s *agentService) skillEnvCapture(config *types.AgentConfig) tools.SkillEnvCapture {
+ if s.db == nil || config == nil || config.SandboxConfigID == "" {
+ return nil
+ }
+ configID := config.SandboxConfigID
+ return func(ctx context.Context, skillName string, pairs map[string]string) {
+ svc := NewUserEnvService(
+ repository.NewTenantSkillRepository(s.db),
+ repository.NewTenantSandboxConfigRepository(s.db),
+ )
+ if err := svc.CaptureSkillEnv(ctx, configID, skillName, pairs); err != nil {
+ logger.Warnf(ctx, "[skill] capture env for %s failed: %v", skillName, err)
+ }
+ }
+}
+
// readSkillBundle downloads one uploaded skill archive. It backs read_skill for
// installed skills: the image holds the executable copy, but reading a file out
// of it would need a live sandbox, and the archive is byte-identical to what
@@ -528,7 +592,7 @@ func (s *agentService) readSkillBundle(
// AgentConfig.SkillInstallMode is settable only through
// EnableSkillInstallMode, which refuses every agent but the built-in
// installer, so no tenant agent can reach this branch.
-func registerSandboxShellTool(
+func (s *agentService) registerSandboxShellTool(
ctx context.Context,
toolRegistry *tools.ToolRegistry,
sandboxMgr sandbox.Manager,
@@ -544,7 +608,10 @@ func registerSandboxShellTool(
return
}
if executor := sessionSandboxShellExecutor(sandboxMgr); executor != nil {
- toolRegistry.RegisterTool(tools.NewShellExecTool(executor))
+ resolver := s.userEnvResolver(ctx, config) // 现取,可能为 nil
+ toolRegistry.RegisterTool(
+ tools.NewShellExecTool(executor, resolver).WithEnvCapture(s.skillEnvCapture(config)),
+ )
logger.Infof(ctx, "Registered shell_exec tool")
} else {
logger.Infof(ctx, "Sandbox backend does not advertise remote shell capability; shell_exec not registered")
diff --git a/internal/application/service/agent_service_install_shell_test.go b/internal/application/service/agent_service_install_shell_test.go
index 81561bf30..ab9634746 100644
--- a/internal/application/service/agent_service_install_shell_test.go
+++ b/internal/application/service/agent_service_install_shell_test.go
@@ -41,7 +41,7 @@ func TestInstallerAgentGetsTheRootShellWithTheSkillsRoot(t *testing.T) {
config.EnableSkillInstallMode(types.BuiltinSkillInstallerID)
registry := tools.NewToolRegistry()
- registerSandboxShellTool(context.Background(), registry, mgr, config)
+ (&agentService{}).registerSandboxShellTool(context.Background(), registry, mgr, config)
result, err := registry.ExecuteTool(installShellToolContext(), tools.ToolShellExec,
json.RawMessage(`{"command":"pip install -r requirements.txt","work_dir":"`+
@@ -67,7 +67,7 @@ func TestOrdinaryAgentKeepsTheUnprivilegedShell(t *testing.T) {
}
registry := tools.NewToolRegistry()
- registerSandboxShellTool(context.Background(), registry, mgr, &types.AgentConfig{})
+ (&agentService{}).registerSandboxShellTool(context.Background(), registry, mgr, &types.AgentConfig{})
rejected, err := registry.ExecuteTool(installShellToolContext(), tools.ToolShellExec,
json.RawMessage(`{"command":"pip install x","work_dir":"`+sandbox.SkillsImageRoot+`/sk-1"}`))
diff --git a/internal/application/service/agent_service_user_env_test.go b/internal/application/service/agent_service_user_env_test.go
new file mode 100644
index 000000000..a6fce1afd
--- /dev/null
+++ b/internal/application/service/agent_service_user_env_test.go
@@ -0,0 +1,87 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+ "gorm.io/gorm"
+)
+
+// Without a sandbox config there is nothing to resolve against: no config-wide
+// scope to read and no installed skill to name.
+func TestAgentServiceUserEnvResolverNilWithoutASandboxConfig(t *testing.T) {
+ s := &agentService{db: &gorm.DB{}}
+
+ require.Nil(t, s.userEnvResolver(context.Background(), &types.AgentConfig{}))
+}
+
+func TestAgentServiceUserEnvResolverNilWithoutDB(t *testing.T) {
+ s := &agentService{}
+
+ resolver := s.userEnvResolver(context.Background(), &types.AgentConfig{
+ SandboxConfigID: "cfg-1",
+ TenantSkills: []*types.TenantSkillEntity{{ID: "sk-1", TenantID: 7, Name: "web-search"}},
+ })
+
+ require.Nil(t, resolver)
+}
+
+// The resolver exists even with no installed skills, so shell_exec still gets
+// the caller's config-wide variables.
+func TestAgentServiceUserEnvResolverBuiltWithoutInstalledSkills(t *testing.T) {
+ s := &agentService{db: &gorm.DB{}}
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+
+ resolver := s.userEnvResolver(ctx, &types.AgentConfig{SandboxConfigID: "cfg-1"})
+
+ require.NotNil(t, resolver)
+ typed, ok := resolver.(*userEnvResolver)
+ require.True(t, ok)
+ require.Equal(t, uint64(7), typed.tenantID)
+ require.Equal(t, "cfg-1", typed.configID)
+ require.Empty(t, typed.byName)
+}
+
+// The tenant id is read off the row, matching tenantSkillSource, so the lookup
+// cannot resolve into a different workspace.
+func TestAgentServiceUserEnvResolverIndexesByNameAndRowTenant(t *testing.T) {
+ s := &agentService{db: &gorm.DB{}}
+
+ resolver := s.userEnvResolver(context.Background(), &types.AgentConfig{
+ SandboxConfigID: "cfg-1",
+ TenantSkills: []*types.TenantSkillEntity{
+ {ID: "sk-1", TenantID: 7, Name: "web-search"},
+ {ID: "sk-2", TenantID: 7, Name: "pdf"},
+ },
+ })
+
+ require.NotNil(t, resolver)
+ typed, ok := resolver.(*userEnvResolver)
+ require.True(t, ok)
+ require.Equal(t, uint64(7), typed.tenantID)
+ require.Equal(t, "cfg-1", typed.configID)
+ require.Contains(t, typed.byName, "web-search")
+ require.Contains(t, typed.byName, "pdf")
+ require.Equal(t, "sk-1", typed.byName["web-search"].ID)
+}
+
+func TestAgentServiceSkillEnvCaptureNilWithoutASandboxConfig(t *testing.T) {
+ s := &agentService{db: &gorm.DB{}}
+
+ require.Nil(t, s.skillEnvCapture(&types.AgentConfig{}))
+ require.Nil(t, s.skillEnvCapture(nil))
+}
+
+func TestAgentServiceSkillEnvCaptureNilWithoutDB(t *testing.T) {
+ s := &agentService{}
+
+ require.Nil(t, s.skillEnvCapture(&types.AgentConfig{SandboxConfigID: "cfg-1"}))
+}
+
+func TestAgentServiceSkillEnvCaptureBuiltWithConfigAndDB(t *testing.T) {
+ s := &agentService{db: &gorm.DB{}}
+
+ require.NotNil(t, s.skillEnvCapture(&types.AgentConfig{SandboxConfigID: "cfg-1"}))
+}
diff --git a/internal/application/service/tenant_sandbox_config.go b/internal/application/service/tenant_sandbox_config.go
index d026798b7..db953584d 100644
--- a/internal/application/service/tenant_sandbox_config.go
+++ b/internal/application/service/tenant_sandbox_config.go
@@ -222,6 +222,7 @@ type sandboxConfigSkillStore interface {
ListSkillsByConfig(ctx context.Context, tenantID uint64, configID string) ([]*types.TenantSkillEntity, error)
DeleteSkill(ctx context.Context, tenantID uint64, configID, skillID string) error
DeleteSnapshotRowsByConfig(ctx context.Context, tenantID uint64, configID string) error
+ DeleteUserEnvVarsByConfig(ctx context.Context, tenantID uint64, configID string) error
}
// sandboxConfigBundleResolver locates the tenant file service so config
@@ -1288,6 +1289,12 @@ func (s *TenantSandboxConfigService) cleanupSkillMetadata(
logger.Warnf(ctx, "[sandbox] delete snapshot ledger for config %s failed: %v",
configID, err)
}
+ // DeleteSkill only takes the values filed under a skill; the config-wide
+ // ones have no skill to hang off and would outlive the config.
+ if err := s.skills.DeleteUserEnvVarsByConfig(ctx, tenantID, configID); err != nil {
+ logger.Warnf(ctx, "[sandbox] delete member env vars for config %s failed: %v",
+ configID, err)
+ }
}
func (s *TenantSandboxConfigService) deleteSkillBundleBestEffort(
diff --git a/internal/application/service/tenant_sandbox_config_test.go b/internal/application/service/tenant_sandbox_config_test.go
index 60fdb8aa4..96be778e6 100644
--- a/internal/application/service/tenant_sandbox_config_test.go
+++ b/internal/application/service/tenant_sandbox_config_test.go
@@ -3,6 +3,7 @@ package service
import (
"context"
stderrors "errors"
+ "fmt"
"io"
"mime/multipart"
"net/http"
@@ -1513,6 +1514,9 @@ func TestDeleteReleasesSkillSnapshotsBeforeSoftDelete(t *testing.T) {
require.Empty(t, fx.skills.skills, "tenant_skills rows must be dropped before SoftDelete")
require.True(t, fx.skills.ledgerCleared)
require.Equal(t, []string{"bundle://skill-a.zip"}, fx.files.deleted)
+ // DeleteSkill only takes values filed under a skill; the config-wide ones
+ // would outlive the config without this.
+ require.Equal(t, []string{"7:cfg-a"}, fx.skills.envVarsClearedFor)
}
func TestDeleteRefusesWhenSnapshotReleaseFailsWithoutForce(t *testing.T) {
@@ -1747,10 +1751,11 @@ func (c *snapshotReleaseClient) DeleteSnapshot(ctx context.Context, snapshotID s
}
type deleteSkillStore struct {
- snapshots []*types.TenantSkillSnapshotEntity
- skills []*types.TenantSkillEntity
- marks []string
- ledgerCleared bool
+ snapshots []*types.TenantSkillSnapshotEntity
+ skills []*types.TenantSkillEntity
+ marks []string
+ ledgerCleared bool
+ envVarsClearedFor []string
}
func (s *deleteSkillStore) snapshot(id string) *types.TenantSkillSnapshotEntity {
@@ -1846,6 +1851,16 @@ func (s *deleteSkillStore) DeleteSnapshotRowsByConfig(ctx context.Context, tenan
return nil
}
+func (s *deleteSkillStore) DeleteUserEnvVarsByConfig(
+ ctx context.Context, tenantID uint64, configID string,
+) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ s.envVarsClearedFor = append(s.envVarsClearedFor, fmt.Sprintf("%d:%s", tenantID, configID))
+ return nil
+}
+
type deleteBundleResolver struct {
deleted []string
}
diff --git a/internal/application/service/tenant_skill_admin.go b/internal/application/service/tenant_skill_admin.go
index e6453cc73..6eff88c2a 100644
--- a/internal/application/service/tenant_skill_admin.go
+++ b/internal/application/service/tenant_skill_admin.go
@@ -3,6 +3,7 @@ package service
import (
"context"
"encoding/json"
+ "fmt"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/types"
@@ -43,14 +44,42 @@ func (s *TenantSkillService) GetSkill(
return s.skills.GetSkill(ctx, tenantID, configID, skillID)
}
-// SetSkillEnabled hides or reveals an installed skill.
+// SkillAdminUpdate is everything one admin request may change about an
+// installed skill. Both fields are optional: a request carrying only values
+// must leave the visibility alone, and one carrying only the toggle must leave
+// every stored value alone.
+type SkillAdminUpdate struct {
+ // Enabled is nil when the request did not mention visibility.
+ Enabled *bool
+ // EnvValues holds only the names the request sent. A name it does not
+ // carry keeps whatever is stored.
+ EnvValues map[string]string
+}
+
+// UpdateSkillAdmin applies every admin-owned change of one request in a single
+// read-modify-write.
//
-// This is metadata only: the files stay in the image either way, which is what
-// makes it safe to toggle while the image is otherwise untouched. Removing the
-// files is RemoveSkill's job and needs a new snapshot. It returns nil when the
-// skill is not reachable for this workspace and config.
-func (s *TenantSkillService) SetSkillEnabled(
- ctx context.Context, tenantID uint64, configID, skillID string, enabled bool,
+// Doing both in one cycle is what makes a request all-or-nothing: applying the
+// toggle and the values as two updates can persist the first and then fail the
+// second, leaving a credential rotation (disable → clear → re-enable → set)
+// half applied while the admin is told it failed.
+//
+// Visibility is metadata only: the files stay in the image either way, which
+// is what makes it safe to toggle while the image is otherwise untouched.
+// Removing the files is RemoveSkill's job and needs a new snapshot.
+//
+// Of the values, only declared names are written, and a name outside the
+// declaration is ignored rather than refused: a stale settings tab must not
+// fail an otherwise valid save, and an invented variable would store a value
+// nothing reads while making the declaration — the record of what this skill
+// consumes — untrustworthy. An empty string clears the value and keeps the
+// declaration, because "nobody filled this in" and "this is not needed" are
+// different states.
+//
+// It returns nil when the skill is not reachable for this workspace and
+// config, so the handler renders the usual 404.
+func (s *TenantSkillService) UpdateSkillAdmin(
+ ctx context.Context, tenantID uint64, configID, skillID string, update SkillAdminUpdate,
) (*types.TenantSkillEntity, error) {
skill, err := s.skills.GetSkill(ctx, tenantID, configID, skillID)
if err != nil {
@@ -59,16 +88,58 @@ func (s *TenantSkillService) SetSkillEnabled(
if skill == nil {
return nil, nil
}
- if skill.Enabled == enabled {
+
+ // Every value is checked before any part of the request is applied, so a
+ // rejected entry cannot leave the declaration — or the toggle — half
+ // written.
+ for name, value := range update.EnvValues {
+ if _, declared := skill.Envs.Get(name); !declared {
+ continue
+ }
+ if len(value) > MaxEnvValueBytes {
+ return nil, apperrors.NewBadRequestError(fmt.Sprintf(
+ "value of %s cannot exceed %d bytes", name, MaxEnvValueBytes))
+ }
+ }
+
+ changed := false
+ if update.Enabled != nil && skill.Enabled != *update.Enabled {
+ skill.Enabled = *update.Enabled
+ changed = true
+ }
+ for i := range skill.Envs {
+ value, sent := update.EnvValues[skill.Envs[i].Name]
+ if !sent || skill.Envs[i].Value == value {
+ continue
+ }
+ skill.Envs[i].Value = value
+ changed = true
+ }
+ if !changed {
return skill, nil
}
- skill.Enabled = enabled
if err := s.skills.UpdateSkill(ctx, skill); err != nil {
return nil, err
}
return skill, nil
}
+// SetSkillEnabled hides or reveals an installed skill.
+func (s *TenantSkillService) SetSkillEnabled(
+ ctx context.Context, tenantID uint64, configID, skillID string, enabled bool,
+) (*types.TenantSkillEntity, error) {
+ return s.UpdateSkillAdmin(ctx, tenantID, configID, skillID,
+ SkillAdminUpdate{Enabled: &enabled})
+}
+
+// SetSkillEnvValues stores the workspace-wide values for one skill.
+func (s *TenantSkillService) SetSkillEnvValues(
+ ctx context.Context, tenantID uint64, configID, skillID string, values map[string]string,
+) (*types.TenantSkillEntity, error) {
+ return s.UpdateSkillAdmin(ctx, tenantID, configID, skillID,
+ SkillAdminUpdate{EnvValues: values})
+}
+
// SubscribeProgress follows one install or removal.
//
// A nil channel means there is no live stream to follow — without Redis
diff --git a/internal/application/service/tenant_skill_admin_test.go b/internal/application/service/tenant_skill_admin_test.go
index 56d050323..ec2c87b51 100644
--- a/internal/application/service/tenant_skill_admin_test.go
+++ b/internal/application/service/tenant_skill_admin_test.go
@@ -2,6 +2,7 @@ package service
import (
"context"
+ "strings"
"testing"
"github.com/stretchr/testify/require"
@@ -88,6 +89,154 @@ func TestSetSkillEnabledReturnsNilForAnotherWorkspace(t *testing.T) {
require.True(t, stored.Enabled, "a foreign workspace must not be able to hide this skill")
}
+// seedSkillEnvDeclaration puts a declaration on the fixture's skill, as a
+// finished install would have left it.
+func seedSkillEnvDeclaration(t *testing.T, fx *installFixture, envs types.SkillEnvVars) {
+ t.Helper()
+ skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
+ require.NoError(t, err)
+ skill.Envs = envs
+ require.NoError(t, fx.skillRepo.UpdateSkill(context.Background(), skill))
+}
+
+// A name outside the declaration is ignored rather than rejected: a stale UI
+// tab must not fail the whole save, and inventing a variable would store a
+// value nothing reads.
+func TestSetSkillEnvValuesWritesOnlyDeclaredNames(t *testing.T) {
+ fx := newInstallFixture(t)
+ ctx := context.Background()
+ seedSkillEnvDeclaration(t, fx, types.SkillEnvVars{
+ {Name: "API_TOKEN", Description: "token", Required: true},
+ {Name: "REGION"},
+ })
+
+ updated, err := fx.svc.SetSkillEnvValues(ctx, 7, "cfg-1", "sk-1", map[string]string{
+ "API_TOKEN": "secret-1",
+ "NOT_A_NAME": "ignored",
+ })
+ require.NoError(t, err)
+ require.NotNil(t, updated)
+
+ stored, err := fx.skillRepo.GetSkill(ctx, 7, "cfg-1", "sk-1")
+ require.NoError(t, err)
+ require.Len(t, stored.Envs, 2)
+ token, ok := stored.Envs.Get("API_TOKEN")
+ require.True(t, ok)
+ require.Equal(t, "secret-1", token.Value)
+ require.True(t, token.Required, "writing a value must not rewrite the declaration")
+ _, undeclared := stored.Envs.Get("NOT_A_NAME")
+ require.False(t, undeclared, "an undeclared name must not be added to the declaration")
+}
+
+// "The admin filled nothing in" and "this variable is not needed" are different
+// states, so clearing a value must keep the declaration.
+func TestSetSkillEnvValuesEmptyStringClearsTheValueKeepingTheDeclaration(t *testing.T) {
+ fx := newInstallFixture(t)
+ ctx := context.Background()
+ seedSkillEnvDeclaration(t, fx, types.SkillEnvVars{
+ {Name: "API_TOKEN", Description: "token", Required: true, Value: "secret-1"},
+ })
+
+ _, err := fx.svc.SetSkillEnvValues(ctx, 7, "cfg-1", "sk-1", map[string]string{"API_TOKEN": ""})
+ require.NoError(t, err)
+
+ stored, err := fx.skillRepo.GetSkill(ctx, 7, "cfg-1", "sk-1")
+ require.NoError(t, err)
+ require.Len(t, stored.Envs, 1)
+ token, ok := stored.Envs.Get("API_TOKEN")
+ require.True(t, ok)
+ require.Empty(t, token.Value)
+ require.Equal(t, "token", token.Description)
+ require.True(t, token.Required)
+}
+
+func TestSetSkillEnvValuesRefusesAnOversizedValue(t *testing.T) {
+ fx := newInstallFixture(t)
+ ctx := context.Background()
+ seedSkillEnvDeclaration(t, fx, types.SkillEnvVars{{Name: "API_TOKEN"}})
+
+ _, err := fx.svc.SetSkillEnvValues(ctx, 7, "cfg-1", "sk-1", map[string]string{
+ "API_TOKEN": strings.Repeat("x", MaxEnvValueBytes+1),
+ })
+ require.Error(t, err)
+
+ stored, err := fx.skillRepo.GetSkill(ctx, 7, "cfg-1", "sk-1")
+ require.NoError(t, err)
+ token, _ := stored.Envs.Get("API_TOKEN")
+ require.Empty(t, token.Value, "a rejected value must not be partially written")
+}
+
+// nil rather than an error, so the handler renders the same 404 every other
+// route of this resource renders.
+func TestSetSkillEnvValuesReturnsNilForAnUnreachableSkill(t *testing.T) {
+ fx := newInstallFixture(t)
+ seedSkillEnvDeclaration(t, fx, types.SkillEnvVars{{Name: "API_TOKEN"}})
+
+ updated, err := fx.svc.SetSkillEnvValues(context.Background(), 8, "cfg-1", "sk-1",
+ map[string]string{"API_TOKEN": "secret-1"})
+ require.NoError(t, err)
+ require.Nil(t, updated)
+
+ stored, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
+ require.NoError(t, err)
+ token, _ := stored.Envs.Get("API_TOKEN")
+ require.Empty(t, token.Value, "a foreign workspace must not be able to write this value")
+}
+
+// A request carrying both fields is applied as one state: the toggle and the
+// values land together, so a failure cannot persist half of a credential
+// rotation.
+func TestUpdateSkillAdminAppliesEnabledAndValuesAsOneState(t *testing.T) {
+ fx := newInstallFixture(t)
+ ctx := context.Background()
+ seedSkillEnvDeclaration(t, fx, types.SkillEnvVars{
+ {Name: "API_TOKEN", Description: "token", Required: true, Value: "old-secret"},
+ {Name: "REGION"},
+ })
+
+ enabled := false
+ updated, err := fx.svc.UpdateSkillAdmin(ctx, 7, "cfg-1", "sk-1", SkillAdminUpdate{
+ Enabled: &enabled,
+ EnvValues: map[string]string{"API_TOKEN": "new-secret"},
+ })
+ require.NoError(t, err)
+ require.NotNil(t, updated)
+ require.False(t, updated.Enabled)
+
+ stored, err := fx.skillRepo.GetSkill(ctx, 7, "cfg-1", "sk-1")
+ require.NoError(t, err)
+ require.False(t, stored.Enabled)
+ token, ok := stored.Envs.Get("API_TOKEN")
+ require.True(t, ok)
+ require.Equal(t, "new-secret", token.Value)
+ require.True(t, token.Required, "the declaration survives the write")
+ region, ok := stored.Envs.Get("REGION")
+ require.True(t, ok)
+ require.Empty(t, region.Value, "a name the request did not send keeps its stored value")
+}
+
+// A rejected value fails the whole request, including the visibility change it
+// was sent with: an admin told the save failed must not find the skill already
+// re-enabled with the old credential behind it.
+func TestUpdateSkillAdminRejectsTheWholeRequestOnAnOversizedValue(t *testing.T) {
+ fx := newInstallFixture(t)
+ ctx := context.Background()
+ seedSkillEnvDeclaration(t, fx, types.SkillEnvVars{{Name: "API_TOKEN", Value: "old-secret"}})
+
+ enabled := false
+ _, err := fx.svc.UpdateSkillAdmin(ctx, 7, "cfg-1", "sk-1", SkillAdminUpdate{
+ Enabled: &enabled,
+ EnvValues: map[string]string{"API_TOKEN": strings.Repeat("x", MaxEnvValueBytes+1)},
+ })
+ require.Error(t, err)
+
+ stored, err := fx.skillRepo.GetSkill(ctx, 7, "cfg-1", "sk-1")
+ require.NoError(t, err)
+ require.True(t, stored.Enabled, "the toggle must not persist when the values were refused")
+ token, _ := stored.Envs.Get("API_TOKEN")
+ require.Equal(t, "old-secret", token.Value)
+}
+
// Without Redis nothing publishes progress, so there is no stream to hand out.
// The closer must still be safe to call: every caller defers it.
func TestSubscribeProgressWithoutRedisYieldsNoStream(t *testing.T) {
diff --git a/internal/application/service/tenant_skill_env_declare.go b/internal/application/service/tenant_skill_env_declare.go
new file mode 100644
index 000000000..d74e4baa3
--- /dev/null
+++ b/internal/application/service/tenant_skill_env_declare.go
@@ -0,0 +1,207 @@
+package service
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "regexp"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+const (
+ // maxSkillEnvDeclarations bounds one skill's declaration. An agent that
+ // lists a hundred variables has misunderstood the task, and every entry
+ // becomes a form field somebody is asked to fill in.
+ maxSkillEnvDeclarations = 20
+
+ // maxSkillEnvDeclarationCandidates bounds bundle-scan cost, not correctness.
+ // The accepted-output cap remains independent so hallucinated names cannot
+ // shadow a later valid declaration.
+ maxSkillEnvDeclarationCandidates = 200
+
+ // MaxEnvValueBytes bounds one stored value. It is generous enough for a
+ // PEM-encoded key and far short of anything that belongs in a file.
+ MaxEnvValueBytes = 8 * 1024
+
+ // MaxUserEnvVarsPerScope bounds how many variables one principal may keep
+ // in one scope: a sandbox config, or one skill on it.
+ MaxUserEnvVarsPerScope = 50
+)
+
+// envNamePattern is the first validation layer. It rejects what an LLM
+// improvises: prose ("my key"), lowercase identifiers copied out of code, and
+// names long enough to be a paragraph.
+var envNamePattern = regexp.MustCompile(`^[A-Z_][A-Z0-9_]{0,127}$`)
+
+// reservedEnvNames is the third layer. It is NOT a security boundary — a skill
+// can already run arbitrary code in its sandbox, and values are injected only
+// into the one execution that asked for them. It is a guard against a
+// self-inflicted, undiagnosable failure: a user who fills in PATH displaces
+// the python inside the skill's own venv.
+var reservedEnvNames = map[string]bool{
+ "PATH": true,
+ "HOME": true,
+ "USER": true,
+ "SHELL": true,
+ "LD_PRELOAD": true,
+ "LD_LIBRARY_PATH": true,
+ "PYTHONPATH": true,
+ "PYTHONHOME": true,
+ "NODE_OPTIONS": true,
+}
+
+// reservedEnvPrefix is reserved because skills.Manager uses it to hand the
+// skill its artifact directory. Letting it be overridden breaks output
+// collection for reasons nobody would think to look for.
+const reservedEnvPrefix = "WEKNORA_"
+
+// declaredSkillEnv is one entry as the installer agent wrote it.
+//
+// Value exists only so that an agent which ignored the prompt and wrote a
+// value produces a parseable file whose value is then discarded — rather than
+// a file that fails to decode and takes every legitimate entry with it. No
+// declaration ever carries a value out of validateEnvDeclarations.
+type declaredSkillEnv struct {
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ Required bool `json:"required,omitempty"`
+ Value string `json:"value,omitempty"`
+}
+
+type skillEnvDeclarationFile struct {
+ Env []declaredSkillEnv `json:"env"`
+}
+
+// parseEnvDeclaration decodes the file the agent left in the sandbox. Its
+// error is the caller's signal to keep the declaration empty and carry on:
+// a chatty model that wrote a sentence instead of JSON must not fail an
+// otherwise complete install.
+func parseEnvDeclaration(raw []byte) ([]declaredSkillEnv, error) {
+ var encoded struct {
+ Env json.RawMessage `json:"env"`
+ }
+ if err := json.Unmarshal(raw, &encoded); err != nil {
+ return nil, fmt.Errorf("parse skill env declaration: %w", err)
+ }
+ if encoded.Env == nil || bytes.Equal(bytes.TrimSpace(encoded.Env), []byte("null")) {
+ return nil, fmt.Errorf("parse skill env declaration: env must be an explicit JSON array")
+ }
+
+ var declared []declaredSkillEnv
+ if err := json.Unmarshal(encoded.Env, &declared); err != nil {
+ return nil, fmt.Errorf("parse skill env declaration: env must be an array: %w", err)
+ }
+ if len(declared) > maxSkillEnvDeclarationCandidates {
+ return nil, fmt.Errorf(
+ "parse skill env declaration: too many entries (%d exceeds %d)",
+ len(declared), maxSkillEnvDeclarationCandidates,
+ )
+ }
+ return declared, nil
+}
+
+// validateEnvDeclarations applies the three layers in order — format, then
+// the name must appear literally somewhere in the uploaded bundle, then the
+// reserved list — and returns what survived.
+//
+// A rejected entry is dropped alone. One hallucinated name is not a reason to
+// discard the real ones beside it, and the whole point of the bundle match is
+// that hallucinated names are expected.
+func validateEnvDeclarations(declared []declaredSkillEnv, bundle *SkillBundle) types.SkillEnvVars {
+ var out types.SkillEnvVars
+ seen := map[string]bool{}
+ for _, entry := range declared {
+ if len(out) >= maxSkillEnvDeclarations {
+ break
+ }
+ name := strings.TrimSpace(entry.Name)
+ if seen[name] {
+ continue
+ }
+ if err := validateEnvNameFormat(name); err != nil {
+ continue
+ }
+ if !bundleMentionsEnvName(bundle, name) {
+ continue
+ }
+ if err := validateEnvNameNotReserved(name); err != nil {
+ continue
+ }
+ seen[name] = true
+ // Value is deliberately not copied: a declaration is metadata.
+ out = append(out, types.SkillEnvVar{
+ Name: name,
+ Description: strings.TrimSpace(entry.Description),
+ Required: entry.Required,
+ })
+ }
+ return out
+}
+
+// validateUserEnvName is the format and reserved-name check, without the
+// bundle match. The two are separate because a user typing a name into the
+// settings page must pass these layers but not the match: matching exists to
+// catch a model's invention, and a user filling a form is making a choice.
+func validateUserEnvName(name string) error {
+ if err := validateEnvNameFormat(name); err != nil {
+ return err
+ }
+ return validateEnvNameNotReserved(name)
+}
+
+func validateEnvNameFormat(name string) error {
+ if !envNamePattern.MatchString(name) {
+ return fmt.Errorf(
+ "environment variable name %q must be UPPER_SNAKE_CASE and at most 128 characters",
+ name,
+ )
+ }
+ return nil
+}
+
+func validateEnvNameNotReserved(name string) error {
+ if reservedEnvNames[name] || strings.HasPrefix(name, reservedEnvPrefix) {
+ return fmt.Errorf("environment variable name %q is reserved by the sandbox", name)
+ }
+ return nil
+}
+
+// bundleMentionsEnvName is the layer that removes hallucinations. It searches
+// every file of the bundle, not just SKILL.md: the place a variable a skill
+// actually reads appears is the script that reads it.
+func bundleMentionsEnvName(bundle *SkillBundle, name string) bool {
+ if bundle == nil {
+ return false
+ }
+ needle := []byte(name)
+ for _, content := range bundle.Files {
+ if bytes.Contains(content, needle) {
+ return true
+ }
+ }
+ return false
+}
+
+// mergeEnvDeclaration folds a fresh declaration onto the stored one.
+//
+// The declaration itself — which variables exist, what they are for, whether
+// they are required — is replaced wholesale, because it is a statement about
+// the version being installed: keeping a variable the new bundle no longer
+// reads would ask users forever for something nothing consumes. The admin's
+// value is carried across by name, because that is a credential a person
+// typed and re-installing a skill is not a request to delete it.
+func mergeEnvDeclaration(previous, declared types.SkillEnvVars) types.SkillEnvVars {
+ if len(declared) == 0 {
+ return nil
+ }
+ out := make(types.SkillEnvVars, 0, len(declared))
+ for _, entry := range declared {
+ if old, ok := previous.Get(entry.Name); ok && old.Value != "" {
+ entry.Value = old.Value
+ }
+ out = append(out, entry)
+ }
+ return out
+}
diff --git a/internal/application/service/tenant_skill_env_declare_test.go b/internal/application/service/tenant_skill_env_declare_test.go
new file mode 100644
index 000000000..60cfb2fde
--- /dev/null
+++ b/internal/application/service/tenant_skill_env_declare_test.go
@@ -0,0 +1,260 @@
+package service
+
+import (
+ "encoding/json"
+ "fmt"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+// declareBundle is the skill package every validation case is matched back
+// against. The interesting name lives in the script rather than in SKILL.md,
+// because that is where a variable a skill really reads shows up.
+func declareBundle() *SkillBundle {
+ return &SkillBundle{
+ Name: "pdf-tools",
+ Files: map[string][]byte{
+ "SKILL.md": []byte(
+ "Set DOC_ROOT before running. Do not touch PATH, path_prefix or " +
+ "WEKNORA_SKILL_DIR.\n",
+ ),
+ "scripts/extract.py": []byte(
+ "import os\nkey = os.environ[\"TAVILY_API_KEY\"]\n",
+ ),
+ },
+ }
+}
+
+func TestParseEnvDeclarationReadsTheAgentsFile(t *testing.T) {
+ declared, err := parseEnvDeclaration([]byte(`{"env":[
+ {"name":"TAVILY_API_KEY","description":"search key","required":true},
+ {"name":"DOC_ROOT"}
+ ]}`))
+
+ require.NoError(t, err)
+ require.Equal(t, []declaredSkillEnv{
+ {Name: "TAVILY_API_KEY", Description: "search key", Required: true},
+ {Name: "DOC_ROOT"},
+ }, declared)
+}
+
+func TestParseEnvDeclarationAcceptsAnEmptyList(t *testing.T) {
+ declared, err := parseEnvDeclaration([]byte(`{"env":[]}`))
+
+ require.NoError(t, err)
+ require.Empty(t, declared)
+}
+
+func TestParseEnvDeclarationRequiresAnExplicitArray(t *testing.T) {
+ for _, raw := range []string{`{}`, `{"env":null}`} {
+ t.Run(raw, func(t *testing.T) {
+ _, err := parseEnvDeclaration([]byte(raw))
+ require.Error(t, err)
+ })
+ }
+}
+
+func TestParseEnvDeclarationRejectsGarbage(t *testing.T) {
+ _, err := parseEnvDeclaration([]byte("I installed the skill, boss!"))
+ require.Error(t, err)
+}
+
+func TestParseEnvDeclarationRejectsAWrongShape(t *testing.T) {
+ _, err := parseEnvDeclaration([]byte(`{"env":"TAVILY_API_KEY"}`))
+ require.Error(t, err)
+}
+
+func TestParseEnvDeclarationRejectsAnImplausiblyLargeList(t *testing.T) {
+ entries := make([]declaredSkillEnv, maxSkillEnvDeclarationCandidates+1)
+ for i := range entries {
+ entries[i].Name = fmt.Sprintf("VAR_%03d", i)
+ }
+ raw, err := json.Marshal(skillEnvDeclarationFile{Env: entries})
+ require.NoError(t, err)
+
+ _, err = parseEnvDeclaration(raw)
+ require.Error(t, err)
+ require.ErrorContains(t, err, "too many")
+}
+
+func TestValidateUserEnvNameFormatLayer(t *testing.T) {
+ require.NoError(t, validateEnvNameFormat("PATH"),
+ "format validation must not accidentally include the reserved-name layer")
+ require.NoError(t, validateEnvNameFormat("_PRIVATE"))
+ require.Error(t, validateEnvNameFormat("path_prefix"))
+ require.Error(t, validateEnvNameFormat("HAS SPACE"))
+ require.Error(t, validateEnvNameFormat("1LEADING_DIGIT"))
+}
+
+func TestValidateUserEnvNameReservedLayer(t *testing.T) {
+ require.NoError(t, validateEnvNameNotReserved("TAVILY_API_KEY"))
+ require.NoError(t, validateEnvNameNotReserved("lowercase-is-a-format-concern"),
+ "reserved-name validation must remain independent of name format")
+ require.Error(t, validateEnvNameNotReserved("PATH"))
+ require.Error(t, validateEnvNameNotReserved("LD_PRELOAD"))
+ require.Error(t, validateEnvNameNotReserved("WEKNORA_SKILL_DIR"))
+}
+
+func TestValidateEnvDeclarationBundleMatchLayerSearchesEveryFile(t *testing.T) {
+ bundle := declareBundle()
+ require.True(t, bundleMentionsEnvName(bundle, "TAVILY_API_KEY"))
+ require.True(t, bundleMentionsEnvName(bundle, "DOC_ROOT"))
+ require.False(t, bundleMentionsEnvName(bundle, "OPENAI_API_KEY"))
+}
+
+func TestValidateEnvDeclarationsAppliesThreeLayers(t *testing.T) {
+ cases := []struct {
+ name string
+ declared []declaredSkillEnv
+ want types.SkillEnvVars
+ }{
+ {
+ name: "a name the script reads survives",
+ declared: []declaredSkillEnv{{Name: "TAVILY_API_KEY", Required: true}},
+ want: types.SkillEnvVars{{Name: "TAVILY_API_KEY", Required: true}},
+ },
+ {
+ name: "a name only SKILL.md mentions survives",
+ declared: []declaredSkillEnv{{Name: "DOC_ROOT", Description: "corpus root"}},
+ want: types.SkillEnvVars{{Name: "DOC_ROOT", Description: "corpus root"}},
+ },
+ {
+ name: "a name that appears nowhere in the bundle is a hallucination",
+ declared: []declaredSkillEnv{{Name: "OPENAI_API_KEY"}},
+ want: nil,
+ },
+ {
+ name: "PATH is reserved even though the bundle mentions it",
+ declared: []declaredSkillEnv{{Name: "PATH"}},
+ want: nil,
+ },
+ {
+ name: "the WEKNORA_ prefix is reserved",
+ declared: []declaredSkillEnv{{Name: "WEKNORA_SKILL_DIR"}},
+ want: nil,
+ },
+ {
+ name: "a lowercase name fails the format layer",
+ declared: []declaredSkillEnv{{Name: "path_prefix"}},
+ want: nil,
+ },
+ {
+ name: "a name with a space fails the format layer",
+ declared: []declaredSkillEnv{{Name: "TAVILY API KEY"}},
+ want: nil,
+ },
+ {
+ name: "one rejected entry does not take its neighbours with it",
+ declared: []declaredSkillEnv{
+ {Name: "OPENAI_API_KEY"},
+ {Name: "TAVILY_API_KEY", Required: true},
+ {Name: "PATH"},
+ {Name: "DOC_ROOT"},
+ },
+ want: types.SkillEnvVars{
+ {Name: "TAVILY_API_KEY", Required: true},
+ {Name: "DOC_ROOT"},
+ },
+ },
+ {
+ name: "a repeated name collapses onto the first declaration",
+ declared: []declaredSkillEnv{
+ {Name: "DOC_ROOT", Description: "first"},
+ {Name: "DOC_ROOT", Description: "second", Required: true},
+ },
+ want: types.SkillEnvVars{{Name: "DOC_ROOT", Description: "first"}},
+ },
+ {
+ name: "nothing declared yields nothing stored",
+ declared: nil,
+ want: nil,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ require.Equal(t, tc.want, validateEnvDeclarations(tc.declared, declareBundle()))
+ })
+ }
+}
+
+func TestValidateEnvDeclarationsTruncatesARunawayList(t *testing.T) {
+ bundle := declareBundle()
+ var declared []declaredSkillEnv
+ for i := 0; i < maxSkillEnvDeclarations+5; i++ {
+ name := fmt.Sprintf("VAR_%02d", i)
+ bundle.Files["scripts/extract.py"] = append(
+ bundle.Files["scripts/extract.py"], []byte("os.environ["+name+"]\n")...)
+ declared = append(declared, declaredSkillEnv{Name: name})
+ }
+
+ got := validateEnvDeclarations(declared, bundle)
+
+ require.Len(t, got, maxSkillEnvDeclarations)
+ require.Equal(t, "VAR_00", got[0].Name)
+ require.Equal(t, "VAR_19", got[maxSkillEnvDeclarations-1].Name)
+}
+
+// A declaration is metadata. The prompt forbids values outright; parsing one
+// and dropping it here is what keeps a disobedient agent from writing a
+// credential of its own invention into the workspace-wide slot.
+func TestValidateEnvDeclarationsNeverCarriesAValue(t *testing.T) {
+ got := validateEnvDeclarations([]declaredSkillEnv{
+ {Name: "TAVILY_API_KEY", Value: "tvly-guessed-by-the-model"},
+ }, declareBundle())
+
+ require.Equal(t, types.SkillEnvVars{{Name: "TAVILY_API_KEY"}}, got)
+}
+
+func TestMergeEnvDeclarationKeepsTheAdminValueByName(t *testing.T) {
+ previous := types.SkillEnvVars{
+ {Name: "TAVILY_API_KEY", Description: "old text", Required: false, Value: "tvly-real"},
+ {Name: "GONE_IN_THE_NEW_VERSION", Value: "orphan"},
+ }
+ declared := types.SkillEnvVars{
+ {Name: "TAVILY_API_KEY", Description: "new text", Required: true},
+ {Name: "DOC_ROOT"},
+ }
+
+ got := mergeEnvDeclaration(previous, declared)
+
+ require.Equal(t, types.SkillEnvVars{
+ {Name: "TAVILY_API_KEY", Description: "new text", Required: true, Value: "tvly-real"},
+ {Name: "DOC_ROOT"},
+ }, got, "metadata follows the new declaration; the value an admin typed survives it")
+}
+
+func TestMergeEnvDeclarationDropsWhatTheNewVersionNoLongerReads(t *testing.T) {
+ got := mergeEnvDeclaration(
+ types.SkillEnvVars{{Name: "GONE", Value: "orphan"}},
+ types.SkillEnvVars{{Name: "DOC_ROOT"}},
+ )
+
+ require.Equal(t, types.SkillEnvVars{{Name: "DOC_ROOT"}}, got,
+ "asking a user forever for a variable nothing reads is worse than losing it")
+}
+
+func TestMergeEnvDeclarationWithoutADeclarationStoresNothing(t *testing.T) {
+ require.Nil(t, mergeEnvDeclaration(types.SkillEnvVars{{Name: "OLD", Value: "v"}}, nil))
+}
+
+func TestValidateUserEnvNameAcceptsAndRejects(t *testing.T) {
+ require.NoError(t, validateUserEnvName("TAVILY_API_KEY"))
+ require.NoError(t, validateUserEnvName("_PRIVATE"))
+
+ require.Error(t, validateUserEnvName(""))
+ require.Error(t, validateUserEnvName("path_prefix"))
+ require.Error(t, validateUserEnvName("HAS SPACE"))
+ require.Error(t, validateUserEnvName("1LEADING_DIGIT"))
+ require.Error(t, validateUserEnvName("PATH"))
+ require.Error(t, validateUserEnvName("LD_PRELOAD"))
+ require.Error(t, validateUserEnvName("WEKNORA_SKILL_DIR"))
+}
+
+// The user path deliberately skips the bundle match: matching exists to catch
+// an LLM's invention, and a user filling a form is not guessing.
+func TestValidateUserEnvNameDoesNotRequireTheNameToBeInAnyBundle(t *testing.T) {
+ require.NoError(t, validateUserEnvName("SOMETHING_NO_SKILL_MENTIONS"))
+}
diff --git a/internal/application/service/tenant_skill_install.go b/internal/application/service/tenant_skill_install.go
index 957a9fa3e..ce493542b 100644
--- a/internal/application/service/tenant_skill_install.go
+++ b/internal/application/service/tenant_skill_install.go
@@ -367,6 +367,10 @@ func (s *TenantSkillService) runInstall(
if err := s.writeManifestEntry(ctx, mgr, sess.ID, skillID, bundle); err != nil {
return err
}
+ // Read before the scratch wipe. requirements.json lives under skillDir and
+ // is not scratch, but reading it first removes an implicit dependency on
+ // what cleanImageScratch happens to delete.
+ s.recordEnvDeclaration(ctx, mgr, sess.ID, tenantID, configID, skillID, bundle)
s.publishProgress(ctx, tenantID, configID, skillID, SkillProgress{Percent: 90, Stage: "verified"})
// 6. Wipe the scratch state. It must happen BEFORE the snapshot, or the
@@ -1446,8 +1450,10 @@ func snapshotBelongsToOtherConfig(snap sandbox.RemoteSnapshotRef, prefix string)
func buildInstallPrompt(skillDir string, bundle *SkillBundle, uvAvailable bool) string {
skillMD := ""
+ requirementsPath := ""
if bundle != nil {
skillMD = string(bundle.Files["SKILL.md"])
+ requirementsPath = sandbox.SkillRequirementsPath(bundle.Name)
}
return fmt.Sprintf(`Install this WeKnora skill into the sandbox image.
@@ -1461,6 +1467,15 @@ Hard requirements:
- Use shell_exec only. You may set work_dir to %s.
- Each command has a 10-minute budget; you do not need to set timeout_sec.
- When finished, report what you installed and any global/system packages you changed.
+- Declare the environment variables this skill reads AT RUN TIME. Read its scripts to decide;
+ ignore anything only the installation itself needed. Run mkdir -p on the directory first, then
+ write the declaration to %s as JSON of this exact shape:
+ {"env":[{"name":"TAVILY_API_KEY","description":"what the skill uses it for","required":true}]}
+ Each name must be UPPER_SNAKE_CASE and must appear literally somewhere in the skill's own files.
+ Never write any value, placeholder or example credential: this file declares what is needed, and
+ a value you invent would be stored as this workspace's real credential. If one environment
+ variable is required, set required to true; if it is optional, set required to false. If the
+ skill needs no environment variables, write {"env":[]}.
The server verifies the result itself before the image is kept, so report what
you did rather than whether it passed. Verification parses every script with
@@ -1470,7 +1485,8 @@ venv. It never runs the skill's code, so nothing is expected to answer --help.
SKILL.md:
%s
-`, skillDir, uvAvailable, skillDir, skillDir, skillDir, skillMD)
+`, skillDir, uvAvailable, skillDir, skillDir, skillDir,
+ requirementsPath, skillMD)
}
func (s *TenantSkillService) probeUv(ctx context.Context, mgr sandbox.Manager, sessionID string) bool {
@@ -1619,6 +1635,75 @@ func (s *TenantSkillService) writeManifestEntry(
return store.WriteSessionFile(ctx, sessionID, sandbox.SkillsManifestPath, payload)
}
+// recordEnvDeclaration reads the environment variables the installer agent
+// declared and stores the ones that survive validation.
+//
+// It returns nothing because none of its failures is a failed install. The
+// agent may not have written the file, may have written prose, or may have
+// listed nothing that exists in the bundle; in every case the skill is
+// installed and working, and the missing declaration costs an admin one manual
+// entry in the settings page. Failing the install over it would throw away the
+// minutes of dependency installation that already succeeded.
+func (s *TenantSkillService) recordEnvDeclaration(
+ ctx context.Context, mgr sandbox.Manager, sessionID string,
+ tenantID uint64, configID, skillID string, bundle *SkillBundle,
+) {
+ if bundle == nil {
+ return
+ }
+ reader, ok := mgr.(sandbox.SessionFileReader)
+ if !ok {
+ logger.Warnf(ctx,
+ "[skill] sandbox backend cannot read files back; skill %s keeps no env declaration",
+ skillID)
+ return
+ }
+ requirementsPath := sandbox.SkillRequirementsPath(bundle.Name)
+ if requirementsPath == "" {
+ return
+ }
+ raw, err := reader.ReadSessionFile(ctx, sessionID, requirementsPath)
+ if err != nil {
+ // A skill that needs no credentials writes no file at all, so an
+ // absent one is normal. Any other read failure means a declaration
+ // may exist and was lost, which an operator has to be able to see.
+ if sandbox.IsRemoteNotFound(err) {
+ logger.Infof(ctx, "[skill] %s declared no environment variables (no %s)",
+ skillID, requirementsPath)
+ return
+ }
+ logger.Warnf(ctx, "[skill] %s: reading its env declaration at %s failed: %v",
+ skillID, requirementsPath, err)
+ return
+ }
+ declared, err := parseEnvDeclaration(raw)
+ if err != nil {
+ logger.Warnf(ctx, "[skill] %s wrote an unreadable env declaration: %v", skillID, err)
+ return
+ }
+ envs := validateEnvDeclarations(declared, bundle)
+ if len(envs) == 0 && len(declared) > 0 {
+ // The original count is the only clue an admin has for "why is my
+ // variable not in the list": every name was rejected, not ignored.
+ // Learning nothing usable must not erase a value already stored.
+ logger.Warnf(ctx,
+ "[skill] all %d environment variable(s) declared for %s were rejected "+
+ "(bad name, not mentioned anywhere in the bundle, or reserved)",
+ len(declared), skillID)
+ return
+ }
+
+ skill, err := s.skills.GetSkill(ctx, tenantID, configID, skillID)
+ if err != nil || skill == nil {
+ logger.Warnf(ctx, "[skill] load %s to store its env declaration failed: %v", skillID, err)
+ return
+ }
+ skill.Envs = mergeEnvDeclaration(skill.Envs, envs)
+ if err := s.skills.UpdateSkill(ctx, skill); err != nil {
+ logger.Warnf(ctx, "[skill] store the env declaration of %s failed: %v", skillID, err)
+ }
+}
+
type skillImageManifest struct {
Skills []skillImageManifestEntry `json:"skills"`
}
diff --git a/internal/application/service/tenant_skill_install_test.go b/internal/application/service/tenant_skill_install_test.go
index f206308e3..3ed231f32 100644
--- a/internal/application/service/tenant_skill_install_test.go
+++ b/internal/application/service/tenant_skill_install_test.go
@@ -9,6 +9,7 @@ import (
"fmt"
"io"
"mime/multipart"
+ "os"
"path"
"path/filepath"
"sort"
@@ -29,6 +30,7 @@ import (
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/google/uuid"
"github.com/stretchr/testify/require"
)
@@ -276,6 +278,204 @@ func TestRunInstallAbortsWhenTheSkillRowWasRemoved(t *testing.T) {
require.Nil(t, skill)
}
+// declareEnvFile presets the file the installer agent is asked to write, so
+// the fixture exercises the same air gap production uses: bytes in the
+// sandbox, parsing and storage server-side.
+func (f *installFixture) declareEnvFile(body string) {
+ f.t.Helper()
+ if f.sandboxMgr.files == nil {
+ f.sandboxMgr.files = map[string][]byte{}
+ }
+ f.sandboxMgr.files[sandbox.SkillRequirementsPath(f.bundle.Name)] = []byte(body)
+}
+
+// readsTavilyKey makes the bundle actually mention the variable, which is what
+// the bundle-match layer looks for.
+func (f *installFixture) readsTavilyKey() {
+ f.bundle.Files["scripts/extract.py"] = []byte("import os\nos.environ[\"TAVILY_API_KEY\"]\n")
+}
+
+func TestRunInstallRecordsTheDeclaredEnvVars(t *testing.T) {
+ fx := newInstallFixture(t)
+ fx.readsTavilyKey()
+ fx.declareEnvFile(`{"env":[
+ {"name":"TAVILY_API_KEY","description":"search key","required":true,"value":"tvly-invented"},
+ {"name":"OPENAI_API_KEY","required":true}
+ ]}`)
+
+ require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
+
+ skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
+ require.NoError(t, err)
+ require.Equal(t, types.SkillStatusReady, skill.Status)
+ require.Equal(t, types.SkillEnvVars{
+ {Name: "TAVILY_API_KEY", Description: "search key", Required: true},
+ }, skill.Envs,
+ "the hallucinated name is dropped and no agent-invented value is ever stored")
+}
+
+func TestRunInstallSucceedsWithoutAnEnvDeclaration(t *testing.T) {
+ fx := newInstallFixture(t)
+
+ require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
+
+ skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
+ require.NoError(t, err)
+ require.Equal(t, types.SkillStatusReady, skill.Status,
+ "getting the skill into the image is the goal; a missing declaration is not a failure")
+ require.Empty(t, skill.Envs)
+}
+
+func TestRunInstallSucceedsWhenTheEnvDeclarationIsUnparseable(t *testing.T) {
+ fx := newInstallFixture(t)
+ fx.declareEnvFile("I installed the skill, boss!")
+
+ require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
+
+ skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
+ require.NoError(t, err)
+ require.Equal(t, types.SkillStatusReady, skill.Status)
+ require.Empty(t, skill.Envs)
+}
+
+func TestRunInstallSucceedsWhenEveryDeclaredEnvVarIsRejected(t *testing.T) {
+ fx := newInstallFixture(t)
+ fx.declareEnvFile(`{"env":[{"name":"OPENAI_API_KEY"},{"name":"PATH"}]}`)
+
+ require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
+
+ skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
+ require.NoError(t, err)
+ require.Equal(t, types.SkillStatusReady, skill.Status)
+ require.Empty(t, skill.Envs)
+}
+
+// Re-installing must not destroy a credential an admin typed in, and must not
+// keep asking for a variable the new version no longer reads.
+func TestRunInstallReinstallKeepsTheAdminValueAndDropsStaleVars(t *testing.T) {
+ fx := newInstallFixture(t)
+ fx.readsTavilyKey()
+ require.NoError(t, fx.svc.updateSkillFields(context.Background(), 7, "cfg-1", "sk-1",
+ func(e *types.TenantSkillEntity) {
+ e.Envs = types.SkillEnvVars{
+ {Name: "TAVILY_API_KEY", Description: "old text", Value: "tvly-typed-by-admin"},
+ {Name: "LEGACY_TOKEN", Required: true, Value: "stale"},
+ }
+ }))
+ fx.declareEnvFile(`{"env":[{"name":"TAVILY_API_KEY","description":"new text","required":true}]}`)
+
+ require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
+
+ skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
+ require.NoError(t, err)
+ require.Equal(t, types.SkillEnvVars{{
+ Name: "TAVILY_API_KEY", Description: "new text", Required: true,
+ Value: "tvly-typed-by-admin",
+ }}, skill.Envs)
+}
+
+func TestRunInstallReinstallOnlyClearsEnvsForAnExplicitEmptyDeclaration(t *testing.T) {
+ cases := []struct {
+ name string
+ body string
+ writeFile bool
+ wantEnvs types.SkillEnvVars
+ }{
+ {
+ name: "missing declaration preserves stored value",
+ wantEnvs: storedAdminEnv(),
+ },
+ {
+ name: "unparseable declaration preserves stored value",
+ body: "I installed the skill, boss!",
+ writeFile: true,
+ wantEnvs: storedAdminEnv(),
+ },
+ {
+ name: "fully rejected declaration preserves stored value",
+ body: `{"env":[{"name":"tavily_api_key"},{"name":"PATH"}]}`,
+ writeFile: true,
+ wantEnvs: storedAdminEnv(),
+ },
+ {
+ name: "explicit empty declaration clears stored value",
+ body: `{"env":[]}`,
+ writeFile: true,
+ wantEnvs: nil,
+ },
+ {
+ name: "missing env field preserves stored value",
+ body: `{}`,
+ writeFile: true,
+ wantEnvs: storedAdminEnv(),
+ },
+ {
+ name: "null env field preserves stored value",
+ body: `{"env":null}`,
+ writeFile: true,
+ wantEnvs: storedAdminEnv(),
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ fx := newInstallFixture(t)
+ require.NoError(t, fx.svc.updateSkillFields(context.Background(), 7, "cfg-1", "sk-1",
+ func(e *types.TenantSkillEntity) {
+ e.Envs = storedAdminEnv()
+ }))
+ if tc.writeFile {
+ fx.declareEnvFile(tc.body)
+ }
+
+ require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
+
+ skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
+ require.NoError(t, err)
+ require.Equal(t, types.SkillStatusReady, skill.Status)
+ require.Equal(t, tc.wantEnvs, skill.Envs)
+ })
+ }
+}
+
+func storedAdminEnv() types.SkillEnvVars {
+ return types.SkillEnvVars{{
+ Name: "TAVILY_API_KEY", Description: "old text", Required: true,
+ Value: "tvly-typed-by-admin",
+ }}
+}
+
+func TestBuildInstallPromptAsksForADeclarationWithoutValues(t *testing.T) {
+ fx := newInstallFixture(t)
+
+ prompt := buildInstallPrompt(installSkillDir, fx.bundle, true)
+
+ require.Contains(t, prompt, sandbox.SkillRequirementsPath(fx.bundle.Name))
+ require.Contains(t, prompt, ".weknora/requirements.json")
+ require.Contains(t, prompt, `{"env":[]}`)
+ require.Contains(t, prompt, "Never write any value",
+ "a value the model invents would be stored as the workspace credential")
+}
+
+func TestInstallSkillRepoNormalizesStoredUserEnvPrincipal(t *testing.T) {
+ repo := &installSkillRepo{}
+ row := &types.TenantUserEnvVar{
+ TenantID: 7, PrincipalType: " web_user ", PrincipalID: " user-1 ",
+ SandboxConfigID: "cfg-1", SkillID: "sk-1", Name: "API_KEY", Value: "secret",
+ }
+
+ require.NoError(t, repo.UpsertUserEnvVar(context.Background(), row))
+
+ got, err := repo.ListUserEnvVars(
+ context.Background(), 7,
+ types.Principal{Type: types.PrincipalWebUser, ID: "user-1"}, "cfg-1", "sk-1",
+ )
+ require.NoError(t, err)
+ require.Len(t, got, 1)
+ require.Equal(t, types.PrincipalWebUser, got[0].PrincipalType)
+ require.Equal(t, "user-1", got[0].PrincipalID)
+}
+
func TestWriteReadySkillStateDoesNotStampANewerBundle(t *testing.T) {
fx := newInstallFixture(t)
newer := strings.Repeat("b", 64)
@@ -1660,6 +1860,10 @@ type installSkillRepo struct {
// listing and one whose listing failed are different bugs, and the skill
// derivation tests turn on telling them apart.
listCalls int
+ // userEnvs is a real store rather than a stub: the env-var flows are about
+ // which principal's value wins, so a fake that cannot distinguish
+ // principals would let the interesting bugs through.
+ userEnvs []*types.TenantUserEnvVar
}
func newInstallSkillRepo() *installSkillRepo {
@@ -1775,7 +1979,24 @@ func (r *installSkillRepo) DeleteSkill(
if r.deleteSkillErr != nil {
return r.deleteSkillErr
}
- delete(r.skills, skillKey(tenantID, configID, skillID))
+ key := skillKey(tenantID, configID, skillID)
+ if _, matched := r.skills[key]; !matched {
+ // Mirrors the real repository: when the scoped key matches no skill,
+ // nothing is deleted at all. Deleting the user values here anyway would
+ // hide the exact data-loss bug the real DeleteSkill was fixed to avoid.
+ return nil
+ }
+ delete(r.skills, key)
+ // Mirrors the real repository's transaction: a skill's user values go with
+ // it, because the soft delete means no cascade can do it for us.
+ kept := r.userEnvs[:0]
+ for _, e := range r.userEnvs {
+ if e.TenantID == tenantID && e.SkillID == skillID {
+ continue
+ }
+ kept = append(kept, e)
+ }
+ r.userEnvs = kept
return nil
}
@@ -1835,6 +2056,138 @@ func (r *installSkillRepo) DeleteSnapshotRowsByConfig(context.Context, uint64, s
return nil
}
+func (r *installSkillRepo) ListSkillsByTenant(
+ ctx context.Context, tenantID uint64,
+) ([]*types.TenantSkillEntity, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ var out []*types.TenantSkillEntity
+ for _, e := range r.skills {
+ if e.TenantID == tenantID {
+ cp := *e
+ out = append(out, &cp)
+ }
+ }
+ return out, nil
+}
+
+// userEnvMatches mirrors the real repository's unique index, minus the name,
+// which the per-row callers add.
+func userEnvMatches(
+ e *types.TenantUserEnvVar, tenantID uint64, p types.Principal, configID, skillID string,
+) bool {
+ p = p.Normalize()
+ return e.TenantID == tenantID && e.PrincipalType == p.Type &&
+ e.PrincipalID == p.ID && e.SandboxConfigID == configID && e.SkillID == skillID
+}
+
+func (r *installSkillRepo) ListUserEnvVars(
+ ctx context.Context, tenantID uint64, p types.Principal, configID, skillID string,
+) ([]*types.TenantUserEnvVar, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ var out []*types.TenantUserEnvVar
+ for _, e := range r.userEnvs {
+ if userEnvMatches(e, tenantID, p, configID, skillID) {
+ cp := *e
+ out = append(out, &cp)
+ }
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
+ return out, nil
+}
+
+func (r *installSkillRepo) ListUserEnvVarsByConfig(
+ ctx context.Context, tenantID uint64, p types.Principal, configID string,
+) ([]*types.TenantUserEnvVar, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ p = p.Normalize()
+ var out []*types.TenantUserEnvVar
+ for _, e := range r.userEnvs {
+ if e.TenantID == tenantID && e.PrincipalType == p.Type &&
+ e.PrincipalID == p.ID && e.SandboxConfigID == configID {
+ cp := *e
+ out = append(out, &cp)
+ }
+ }
+ sort.Slice(out, func(i, j int) bool {
+ if out[i].SkillID != out[j].SkillID {
+ return out[i].SkillID < out[j].SkillID
+ }
+ return out[i].Name < out[j].Name
+ })
+ return out, nil
+}
+
+func (r *installSkillRepo) UpsertUserEnvVar(ctx context.Context, e *types.TenantUserEnvVar) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ p := types.Principal{Type: e.PrincipalType, ID: e.PrincipalID}.Normalize()
+ for _, existing := range r.userEnvs {
+ if userEnvMatches(existing, e.TenantID, p, e.SandboxConfigID, e.SkillID) &&
+ existing.Name == e.Name {
+ existing.Value = e.Value
+ return nil
+ }
+ }
+ cp := *e
+ cp.PrincipalType, cp.PrincipalID = p.Type, p.ID
+ if cp.ID == "" {
+ cp.ID = uuid.NewString()
+ }
+ r.userEnvs = append(r.userEnvs, &cp)
+ return nil
+}
+
+func (r *installSkillRepo) DeleteUserEnvVar(
+ ctx context.Context, tenantID uint64, p types.Principal, configID, skillID, name string,
+) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ for i, e := range r.userEnvs {
+ if userEnvMatches(e, tenantID, p, configID, skillID) && e.Name == name {
+ r.userEnvs = append(r.userEnvs[:i], r.userEnvs[i+1:]...)
+ return nil
+ }
+ }
+ return types.ErrEnvVarNotFound
+}
+
+func (r *installSkillRepo) DeleteUserEnvVarsByConfig(
+ ctx context.Context, tenantID uint64, configID string,
+) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ kept := r.userEnvs[:0]
+ for _, e := range r.userEnvs {
+ if e.TenantID == tenantID && e.SandboxConfigID == configID {
+ continue
+ }
+ kept = append(kept, e)
+ }
+ r.userEnvs = kept
+ return nil
+}
+
var _ repository.TenantSkillRepository = (*installSkillRepo)(nil)
type installSandboxResolver struct {
@@ -1854,6 +2207,10 @@ type installSandboxManager struct {
writeContents map[string][]byte
// manifest is the file the image already carries at SkillsManifestPath.
manifest []byte
+ // files are the other files the image already carries, keyed by absolute
+ // path. The env declaration crosses from the sandbox to the server as one
+ // of these, never as a tool call.
+ files map[string][]byte
}
func (m *installSandboxManager) sortedWrites() []string {
@@ -1892,7 +2249,13 @@ func (m *installSandboxManager) ReadSessionFile(
if filePath == sandbox.SkillsManifestPath && m.manifest != nil {
return m.manifest, nil
}
- return nil, nil
+ if content, ok := m.files[filePath]; ok {
+ return content, nil
+ }
+ // A miss is reported the way a real backend reports one. Returning empty
+ // bytes with no error would make "the agent wrote nothing" indistinguishable
+ // from "the agent wrote an empty file".
+ return nil, os.ErrNotExist
}
func (m *installSandboxManager) WriteSessionInputFile(
diff --git a/internal/application/service/tenant_skill_reaper_test.go b/internal/application/service/tenant_skill_reaper_test.go
index 3c105b7d6..1a34d9ce1 100644
--- a/internal/application/service/tenant_skill_reaper_test.go
+++ b/internal/application/service/tenant_skill_reaper_test.go
@@ -857,6 +857,30 @@ func (r *reaperSkillStore) MarkSnapshotState(
func (r *reaperSkillStore) DeleteSnapshotRowsByConfig(context.Context, uint64, string) error {
panic("DeleteSnapshotRowsByConfig is outside the reaper surface")
}
+func (r *reaperSkillStore) ListSkillsByTenant(context.Context, uint64) ([]*types.TenantSkillEntity, error) {
+ panic("ListSkillsByTenant is outside the reaper surface")
+}
+func (r *reaperSkillStore) ListUserEnvVars(
+ context.Context, uint64, types.Principal, string, string,
+) ([]*types.TenantUserEnvVar, error) {
+ panic("ListUserEnvVars is outside the reaper surface")
+}
+func (r *reaperSkillStore) ListUserEnvVarsByConfig(
+ context.Context, uint64, types.Principal, string,
+) ([]*types.TenantUserEnvVar, error) {
+ panic("ListUserEnvVarsByConfig is outside the reaper surface")
+}
+func (r *reaperSkillStore) UpsertUserEnvVar(context.Context, *types.TenantUserEnvVar) error {
+ panic("UpsertUserEnvVar is outside the reaper surface")
+}
+func (r *reaperSkillStore) DeleteUserEnvVar(
+ context.Context, uint64, types.Principal, string, string, string,
+) error {
+ panic("DeleteUserEnvVar is outside the reaper surface")
+}
+func (r *reaperSkillStore) DeleteUserEnvVarsByConfig(context.Context, uint64, string) error {
+ panic("DeleteUserEnvVarsByConfig is outside the reaper surface")
+}
type reaperConfigStore struct {
entity *types.TenantSandboxConfigEntity
diff --git a/internal/application/service/user_env.go b/internal/application/service/user_env.go
new file mode 100644
index 000000000..ddea21cf0
--- /dev/null
+++ b/internal/application/service/user_env.go
@@ -0,0 +1,465 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/application/repository"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// Where the value a skill would actually receive comes from. The three states
+// are distinct on purpose: "the workspace filled this in for everybody" and "I
+// filled this in for myself" lead to different actions, and neither is "nobody
+// has filled this in".
+const (
+ EnvSourceUnset = "unset"
+ EnvSourceWorkspace = "workspace"
+ EnvSourceUser = "user"
+)
+
+// EnvVarView is one variable as its owner may see it. There is deliberately no
+// value field: this view exists so a member can tell what is still missing, and
+// a stored value is never read back out.
+type EnvVarView struct {
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ Required bool `json:"required,omitempty"`
+ Source string `json:"source"`
+ // UpdatedAt is set only for the caller's own value; a workspace value has
+ // no per-variable timestamp to report.
+ UpdatedAt *time.Time `json:"updated_at,omitempty"`
+}
+
+// SkillEnvGroup is one skill's declared credentials. It carries the skill's
+// identity and nothing else about it — not the instructions, not the bundle,
+// not the install state, all of which are Admin+ disclosure.
+type SkillEnvGroup struct {
+ SkillID string `json:"skill_id"`
+ SkillName string `json:"skill_name"`
+ Vars []EnvVarView `json:"vars"`
+}
+
+// ConfigEnvGroup is one sandbox config: the caller's own config-wide variables
+// plus the declared credentials of the skills installed on it.
+type ConfigEnvGroup struct {
+ SandboxConfigID string `json:"sandbox_config_id"`
+ SandboxConfigName string `json:"sandbox_config_name"`
+ Vars []EnvVarView `json:"vars"`
+ Skills []SkillEnvGroup `json:"skills"`
+}
+
+// UserEnvService serves the values one identity keeps for itself, in both
+// scopes: config-wide variables and the credentials a skill declared.
+//
+// It is separate from TenantSkillService because its authority is different in
+// kind. Every method derives the workspace and the identity from the context
+// alone and touches only rows keyed by that identity, which is what makes the
+// endpoints safe for any logged-in member while install and listing stay Admin+.
+type UserEnvService struct {
+ skills repository.TenantSkillRepository
+ configs repository.TenantSandboxConfigRepository
+}
+
+func NewUserEnvService(
+ skills repository.TenantSkillRepository,
+ configs repository.TenantSandboxConfigRepository,
+) *UserEnvService {
+ return &UserEnvService{skills: skills, configs: configs}
+}
+
+// caller resolves whose values this call may touch. A missing principal is an
+// error rather than a default: falling back to any other identity would let one
+// member read or overwrite another's values.
+func (s *UserEnvService) caller(ctx context.Context) (uint64, types.Principal, error) {
+ tenantID, ok := types.TenantIDFromContext(ctx)
+ if !ok || tenantID == 0 {
+ return 0, types.Principal{}, apperrors.NewUnauthorizedError(
+ "workspace context is required to access environment variables")
+ }
+ principal, ok := types.PrincipalFromContext(ctx)
+ if !ok {
+ return 0, types.Principal{}, apperrors.NewUnauthorizedError(
+ "principal context is required to access environment variables")
+ }
+ return tenantID, principal, nil
+}
+
+// ListMine returns every sandbox config of the workspace with the caller's own
+// config-wide variables and the credentials its skills declared.
+//
+// A config is listed even when it carries nothing, because the config-wide
+// editor has to be reachable. A skill is listed only when it declared
+// something: an empty declaration has nothing to ask for.
+//
+// Only enabled, ready skills are listed. A disabled or half-installed skill is
+// never handed to the agent, so asking for its credential asks for something
+// nothing reads.
+func (s *UserEnvService) ListMine(ctx context.Context) ([]ConfigEnvGroup, error) {
+ tenantID, principal, err := s.caller(ctx)
+ if err != nil {
+ return nil, err
+ }
+ configs, err := s.configs.ListByTenant(ctx, tenantID)
+ if err != nil {
+ return nil, err
+ }
+ skills, err := s.skills.ListSkillsByTenant(ctx, tenantID)
+ if err != nil {
+ return nil, err
+ }
+
+ skillsByConfig := map[string][]*types.TenantSkillEntity{}
+ for _, row := range skills {
+ if skillAcceptsUserEnvs(row) && len(row.Envs) > 0 {
+ skillsByConfig[row.SandboxConfigID] = append(skillsByConfig[row.SandboxConfigID], row)
+ }
+ }
+
+ groups := make([]ConfigEnvGroup, 0, len(configs))
+ for _, cfg := range configs {
+ if cfg == nil {
+ continue
+ }
+ owned, err := s.skills.ListUserEnvVarsByConfig(ctx, tenantID, principal, cfg.ID)
+ if err != nil {
+ return nil, err
+ }
+ mineBySkill := map[string]map[string]*types.TenantUserEnvVar{}
+ for _, row := range owned {
+ if row == nil {
+ continue
+ }
+ if mineBySkill[row.SkillID] == nil {
+ mineBySkill[row.SkillID] = map[string]*types.TenantUserEnvVar{}
+ }
+ mineBySkill[row.SkillID][row.Name] = row
+ }
+
+ // Both lists are initialised so they marshal as [] rather than null:
+ // the settings page reads .length off them.
+ group := ConfigEnvGroup{
+ SandboxConfigID: cfg.ID,
+ SandboxConfigName: cfg.Name,
+ Vars: configWideViews(mineBySkill[""]),
+ Skills: make([]SkillEnvGroup, 0, len(skillsByConfig[cfg.ID])),
+ }
+ for _, row := range skillsByConfig[cfg.ID] {
+ group.Skills = append(group.Skills, SkillEnvGroup{
+ SkillID: row.ID,
+ SkillName: row.Name,
+ Vars: declaredViews(row.Envs, mineBySkill[row.ID]),
+ })
+ }
+ // The repository orders skills by creation; sorting by name is what
+ // keeps the page stable when two were installed in one batch.
+ sort.SliceStable(group.Skills, func(i, j int) bool {
+ if group.Skills[i].SkillName != group.Skills[j].SkillName {
+ return group.Skills[i].SkillName < group.Skills[j].SkillName
+ }
+ return group.Skills[i].SkillID < group.Skills[j].SkillID
+ })
+ groups = append(groups, group)
+ }
+ sort.SliceStable(groups, func(i, j int) bool {
+ if groups[i].SandboxConfigName != groups[j].SandboxConfigName {
+ return groups[i].SandboxConfigName < groups[j].SandboxConfigName
+ }
+ return groups[i].SandboxConfigID < groups[j].SandboxConfigID
+ })
+ return groups, nil
+}
+
+// configWideViews lists the caller's own config-wide variables. They have no
+// declaration behind them, so every one of them is theirs by definition.
+func configWideViews(mine map[string]*types.TenantUserEnvVar) []EnvVarView {
+ views := make([]EnvVarView, 0, len(mine))
+ for _, row := range mine {
+ view := EnvVarView{Name: row.Name, Source: EnvSourceUnset}
+ applyOwnValue(&view, row)
+ views = append(views, view)
+ }
+ sort.Slice(views, func(i, j int) bool { return views[i].Name < views[j].Name })
+ return views
+}
+
+// declaredViews layers the caller's own values onto the declaration in the same
+// order the resolver injects them, so what a member sees is what a run gets.
+func declaredViews(
+ declared types.SkillEnvVars, mine map[string]*types.TenantUserEnvVar,
+) []EnvVarView {
+ views := make([]EnvVarView, 0, len(declared))
+ for _, entry := range declared {
+ view := EnvVarView{
+ Name: entry.Name,
+ Description: entry.Description,
+ Required: entry.Required,
+ Source: EnvSourceUnset,
+ }
+ if entry.Value != "" {
+ view.Source = EnvSourceWorkspace
+ }
+ applyOwnValue(&view, mine[entry.Name])
+ views = append(views, view)
+ }
+ return views
+}
+
+// applyOwnValue promotes a view to the user source. A row whose value came back
+// empty stays at its previous source: that only happens when the stored secret
+// could not be decrypted, and reporting it as set would hide the one thing the
+// member needs to do about it.
+func applyOwnValue(view *EnvVarView, own *types.TenantUserEnvVar) {
+ if own == nil || own.Value == "" {
+ return
+ }
+ view.Source = EnvSourceUser
+ updated := own.UpdatedAt
+ view.UpdatedAt = &updated
+}
+
+// CaptureSkillEnv stores values a successful skill run already used, for the
+// current principal only. It writes only names that skill declared; reserved
+// names and a value that already matches the stored user row or the workspace
+// admin value are skipped. Unknown or unusable skills are a no-op so a
+// mis-inferred name cannot create a row.
+func (s *UserEnvService) CaptureSkillEnv(
+ ctx context.Context, configID, skillName string, pairs map[string]string,
+) error {
+ if len(pairs) == 0 || strings.TrimSpace(skillName) == "" {
+ return nil
+ }
+ tenantID, principal, err := s.caller(ctx)
+ if err != nil {
+ return err
+ }
+ configID, err = s.visibleConfigID(ctx, tenantID, configID)
+ if err != nil {
+ return err
+ }
+ skill, err := s.skills.GetSkillByName(ctx, tenantID, configID, strings.TrimSpace(skillName))
+ if err != nil {
+ return err
+ }
+ if !skillAcceptsUserEnvs(skill) {
+ return nil
+ }
+
+ owned, err := s.skills.ListUserEnvVars(ctx, tenantID, principal, configID, skill.ID)
+ if err != nil {
+ return err
+ }
+ mine := map[string]*types.TenantUserEnvVar{}
+ for _, row := range owned {
+ if row != nil {
+ mine[row.Name] = row
+ }
+ }
+
+ for name, value := range pairs {
+ name = strings.TrimSpace(name)
+ if value == "" || validateUserEnvName(name) != nil {
+ continue
+ }
+ declared, ok := skill.Envs.Get(name)
+ if !ok {
+ continue
+ }
+ if declared.Value != "" && declared.Value == value {
+ continue
+ }
+ if existing := mine[name]; existing != nil && existing.Value == value {
+ continue
+ }
+ if err := s.upsertMine(ctx, tenantID, principal, configID, skill.ID, name, value); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// SetMineSkill stores the caller's own value for one variable a skill declared.
+// A name outside the declaration is refused: free-form names belong to the
+// config-wide scope, which is not tied to any one skill.
+func (s *UserEnvService) SetMineSkill(ctx context.Context, skillID, name, value string) error {
+ tenantID, principal, err := s.caller(ctx)
+ if err != nil {
+ return err
+ }
+ skill, err := s.findVisibleSkill(ctx, tenantID, strings.TrimSpace(skillID))
+ if err != nil {
+ return err
+ }
+ name = strings.TrimSpace(name)
+ if _, declared := skill.Envs.Get(name); !declared {
+ return apperrors.NewBadRequestError(
+ fmt.Sprintf("skill %s does not declare %s", skill.Name, name))
+ }
+ return s.upsertMine(ctx, tenantID, principal, skill.SandboxConfigID, skill.ID, name, value)
+}
+
+// DeleteMineSkill removes one of the caller's own skill values.
+//
+// It deliberately does not require the skill to be visible: the delete is
+// already scoped to rows this identity owns, and revoking a credential must keep
+// working after an admin disables the skill it was entered for — which is
+// precisely when somebody is most likely to want it gone.
+func (s *UserEnvService) DeleteMineSkill(ctx context.Context, skillID, name string) error {
+ tenantID, principal, err := s.caller(ctx)
+ if err != nil {
+ return err
+ }
+ skillID, name = strings.TrimSpace(skillID), strings.TrimSpace(name)
+ if skillID == "" || name == "" {
+ return apperrors.NewBadRequestError("skill_id and name are required")
+ }
+ // The config is read off the caller's own row rather than the request, so a
+ // delete cannot be aimed at another config.
+ rows, err := s.skills.ListSkillsByTenant(ctx, tenantID)
+ if err != nil {
+ return err
+ }
+ for _, row := range rows {
+ if row != nil && row.ID == skillID {
+ return s.skills.DeleteUserEnvVar(
+ ctx, tenantID, principal, row.SandboxConfigID, skillID, name)
+ }
+ }
+ return types.ErrEnvVarNotFound
+}
+
+// SetMineSandbox stores the caller's own value for one config-wide variable.
+// The name is free-form: this is the member-side counterpart of the admin's
+// sandbox env_vars, not something a skill declared.
+func (s *UserEnvService) SetMineSandbox(ctx context.Context, configID, name, value string) error {
+ tenantID, principal, err := s.caller(ctx)
+ if err != nil {
+ return err
+ }
+ configID, err = s.visibleConfigID(ctx, tenantID, configID)
+ if err != nil {
+ return err
+ }
+ return s.upsertMine(ctx, tenantID, principal, configID, "", strings.TrimSpace(name), value)
+}
+
+// DeleteMineSandbox removes one of the caller's own config-wide variables.
+func (s *UserEnvService) DeleteMineSandbox(ctx context.Context, configID, name string) error {
+ tenantID, principal, err := s.caller(ctx)
+ if err != nil {
+ return err
+ }
+ configID, name = strings.TrimSpace(configID), strings.TrimSpace(name)
+ if configID == "" || name == "" {
+ return apperrors.NewBadRequestError("sandbox_config_id and name are required")
+ }
+ return s.skills.DeleteUserEnvVar(ctx, tenantID, principal, configID, "", name)
+}
+
+// upsertMine is the one write path both scopes share: same validation, same
+// quota, same row shape. Only the scope key differs.
+func (s *UserEnvService) upsertMine(
+ ctx context.Context,
+ tenantID uint64,
+ principal types.Principal,
+ configID, skillID, name, value string,
+) error {
+ if err := validateUserEnvName(name); err != nil {
+ return apperrors.NewBadRequestError(err.Error())
+ }
+ if value == "" {
+ return apperrors.NewBadRequestError(
+ fmt.Sprintf("a value is required; delete %s to clear it", name))
+ }
+ if len(value) > MaxEnvValueBytes {
+ return apperrors.NewBadRequestError(
+ fmt.Sprintf("value of %s cannot exceed %d bytes", name, MaxEnvValueBytes))
+ }
+
+ owned, err := s.skills.ListUserEnvVars(ctx, tenantID, principal, configID, skillID)
+ if err != nil {
+ return err
+ }
+ // The quota bounds how many names one identity keeps in one scope, so an
+ // overwrite is exempt: a user already at the limit must still be able to
+ // rotate a key they hold.
+ overwrite := false
+ for _, e := range owned {
+ if e != nil && e.Name == name {
+ overwrite = true
+ break
+ }
+ }
+ if !overwrite && len(owned) >= MaxUserEnvVarsPerScope {
+ return apperrors.NewBadRequestError(fmt.Sprintf(
+ "you can keep at most %d environment variables here", MaxUserEnvVarsPerScope))
+ }
+
+ return s.skills.UpsertUserEnvVar(ctx, &types.TenantUserEnvVar{
+ TenantID: tenantID,
+ PrincipalType: principal.Type,
+ PrincipalID: principal.ID,
+ SandboxConfigID: configID,
+ SkillID: skillID,
+ Name: name,
+ Value: value,
+ })
+}
+
+// visibleConfigID resolves a sandbox config against the caller's own workspace.
+// Without it an ID from another workspace would be accepted and a row written
+// against it, which that workspace's runs would then read.
+func (s *UserEnvService) visibleConfigID(
+ ctx context.Context, tenantID uint64, configID string,
+) (string, error) {
+ configID = strings.TrimSpace(configID)
+ if configID == "" {
+ return "", apperrors.NewBadRequestError("sandbox_config_id is required")
+ }
+ cfg, err := s.configs.GetByID(ctx, tenantID, configID)
+ if err != nil {
+ return "", err
+ }
+ if cfg == nil {
+ return "", apperrors.NewBadRequestError(
+ fmt.Sprintf("sandbox config %s is not available in this workspace", configID))
+ }
+ return cfg.ID, nil
+}
+
+// findVisibleSkill resolves a skill ID against the caller's own workspace.
+//
+// Without this an ID from another workspace would be accepted and a row written
+// against it, which the resolver of that workspace's run would then read. The
+// lookup spans configs because the member-facing surface is about the person,
+// not about one sandbox config.
+func (s *UserEnvService) findVisibleSkill(
+ ctx context.Context, tenantID uint64, skillID string,
+) (*types.TenantSkillEntity, error) {
+ if skillID == "" {
+ return nil, apperrors.NewBadRequestError("skill_id is required")
+ }
+ rows, err := s.skills.ListSkillsByTenant(ctx, tenantID)
+ if err != nil {
+ return nil, err
+ }
+ for _, row := range rows {
+ if row != nil && row.ID == skillID && skillAcceptsUserEnvs(row) {
+ return row, nil
+ }
+ }
+ // One message for "not yours", "not installed" and "not usable": which of
+ // the three it is would itself be a disclosure.
+ return nil, apperrors.NewBadRequestError(
+ fmt.Sprintf("skill %s is not available in this workspace", skillID))
+}
+
+// skillAcceptsUserEnvs reports whether a skill is one the agent can actually
+// run, which is the only kind worth asking a member for a credential for.
+func skillAcceptsUserEnvs(row *types.TenantSkillEntity) bool {
+ return row != nil && row.Enabled && row.Status == types.SkillStatusReady
+}
diff --git a/internal/application/service/user_env_resolver.go b/internal/application/service/user_env_resolver.go
new file mode 100644
index 000000000..193fb06ca
--- /dev/null
+++ b/internal/application/service/user_env_resolver.go
@@ -0,0 +1,116 @@
+package service
+
+import (
+ "context"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// userEnvReader is the slice of the repository this resolver needs. Narrowing it
+// keeps the resolver testable without a database and makes the queries it
+// issues per execution visible in the type.
+type userEnvReader interface {
+ ListUserEnvVars(
+ ctx context.Context, tenantID uint64, p types.Principal, configID, skillID string,
+ ) ([]*types.TenantUserEnvVar, error)
+}
+
+// userEnvResolver answers skills.SkillEnvResolver from the skill rows this turn
+// already loaded plus the caller's own values.
+type userEnvResolver struct {
+ // byName indexes the rows by the name the model addresses skills with.
+ byName map[string]*types.TenantSkillEntity
+ userEnvs userEnvReader
+ // tenantID and configID are the scope the rows came from, not whatever the
+ // context happens to hold, so a lookup cannot resolve into another
+ // workspace or another config.
+ tenantID uint64
+ configID string
+}
+
+// NewUserEnvResolver builds the resolver for one agent run. rows are this run's
+// installed skills, already carrying their declarations and admin values; they
+// may be empty, in which case only config-wide variables are resolved.
+func NewUserEnvResolver(
+ rows []*types.TenantSkillEntity, userEnvs userEnvReader, tenantID uint64, configID string,
+) *userEnvResolver {
+ byName := make(map[string]*types.TenantSkillEntity, len(rows))
+ for _, row := range rows {
+ if row != nil {
+ byName[row.Name] = row
+ }
+ }
+ return &userEnvResolver{
+ byName: byName, userEnvs: userEnvs, tenantID: tenantID, configID: configID,
+ }
+}
+
+// ResolveEnv layers the sources in a fixed order, each overwriting the last:
+// the admin's workspace-wide skill values, then this caller's config-wide
+// variables, then this caller's values for that skill. Mine beat the
+// workspace's; among mine, the skill-specific one beats the config-wide one.
+//
+// An empty skillName resolves only the config-wide variables, which is what
+// shell_exec gets when the model names no skill. An unknown name behaves the
+// same way: preloaded skills reach here too and carry no declaration.
+func (r *userEnvResolver) ResolveEnv(
+ ctx context.Context, skillName string,
+) (map[string]string, []string, error) {
+ // The identity is the Principal from the context and nothing else. A user
+ // id would give every IM caller in a workspace the same synthetic account
+ // and therefore the same values.
+ principal, hasPrincipal := types.PrincipalFromContext(ctx)
+ canReadMine := hasPrincipal && r.userEnvs != nil
+
+ env := map[string]string{}
+ row := r.byName[skillName]
+ if row != nil {
+ for _, declared := range row.Envs {
+ // An empty admin value means unset; injecting it would make an
+ // unconfigured variable indistinguishable from one set to "".
+ if declared.Value != "" {
+ env[declared.Name] = declared.Value
+ }
+ }
+ }
+
+ if canReadMine {
+ if err := r.overlayMine(ctx, principal, "", env); err != nil {
+ return nil, nil, err
+ }
+ if row != nil {
+ if err := r.overlayMine(ctx, principal, row.ID, env); err != nil {
+ return nil, nil, err
+ }
+ }
+ }
+
+ var missing []string
+ if row != nil {
+ for _, declared := range row.Envs {
+ if declared.Required && env[declared.Name] == "" {
+ missing = append(missing, declared.Name)
+ }
+ }
+ }
+ return env, missing, nil
+}
+
+// overlayMine writes the caller's own values for one scope over env. A failure
+// is never degraded to the admin value: running a skill with somebody else's
+// key is worse than not running it.
+func (r *userEnvResolver) overlayMine(
+ ctx context.Context, principal types.Principal, skillID string, env map[string]string,
+) error {
+ owned, err := r.userEnvs.ListUserEnvVars(ctx, r.tenantID, principal, r.configID, skillID)
+ if err != nil {
+ return err
+ }
+ for _, value := range owned {
+ if value == nil || value.Value == "" {
+ continue
+ }
+ env[value.Name] = value.Value
+ }
+ return nil
+}
diff --git a/internal/application/service/user_env_resolver_test.go b/internal/application/service/user_env_resolver_test.go
new file mode 100644
index 000000000..585619c60
--- /dev/null
+++ b/internal/application/service/user_env_resolver_test.go
@@ -0,0 +1,305 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+const (
+ testEnvTenantID uint64 = 7
+ testEnvConfigID string = "cfg-1"
+ testEnvOtherConfigID string = "cfg-2"
+)
+
+// fakeUserEnvReader answers per (principal, config, skill) exactly as the
+// repository does: it scopes on tenant, normalised principal, config AND skill,
+// so a resolver that forgot any part of the key gets nothing back rather than
+// somebody else's row.
+type fakeUserEnvReader struct {
+ tenantID uint64
+ rows map[string][]*types.TenantUserEnvVar
+ err error
+
+ calls int
+}
+
+func (f *fakeUserEnvReader) key(p types.Principal, configID, skillID string) string {
+ p = p.Normalize()
+ return p.Type + "\x00" + p.ID + "\x00" + configID + "\x00" + skillID
+}
+
+func (f *fakeUserEnvReader) put(
+ p types.Principal, configID, skillID string, values map[string]string,
+) {
+ if f.rows == nil {
+ f.rows = map[string][]*types.TenantUserEnvVar{}
+ }
+ key := f.key(p, configID, skillID)
+ for name, value := range values {
+ f.rows[key] = append(f.rows[key], &types.TenantUserEnvVar{
+ TenantID: f.tenantID, PrincipalType: p.Type, PrincipalID: p.ID,
+ SandboxConfigID: configID, SkillID: skillID, Name: name, Value: value,
+ })
+ }
+}
+
+func (f *fakeUserEnvReader) ListUserEnvVars(
+ _ context.Context, tenantID uint64, p types.Principal, configID, skillID string,
+) ([]*types.TenantUserEnvVar, error) {
+ f.calls++
+ if f.err != nil {
+ return nil, f.err
+ }
+ if tenantID != f.tenantID {
+ return nil, nil
+ }
+ return f.rows[f.key(p, configID, skillID)], nil
+}
+
+func webPrincipal(id string) types.Principal {
+ return types.Principal{Type: types.PrincipalWebUser, ID: id}
+}
+
+func imPrincipal(id string) types.Principal {
+ return types.Principal{Type: types.PrincipalIMUser, ID: id}
+}
+
+func searchSkillRow() *types.TenantSkillEntity {
+ return &types.TenantSkillEntity{
+ ID: "sk-1", TenantID: testEnvTenantID, SandboxConfigID: testEnvConfigID,
+ Name: "web-search",
+ Envs: types.SkillEnvVars{
+ {Name: "TAVILY_API_KEY", Required: true, Value: "workspace-key"},
+ {Name: "SEARCH_REGION", Value: "workspace-region"},
+ {Name: "OPTIONAL_TOKEN"},
+ },
+ }
+}
+
+func newTestResolver(reader userEnvReader, rows ...*types.TenantSkillEntity) *userEnvResolver {
+ return NewUserEnvResolver(rows, reader, testEnvTenantID, testEnvConfigID)
+}
+
+func TestResolverUserValueOverridesWorkspaceValue(t *testing.T) {
+ reader := &fakeUserEnvReader{tenantID: testEnvTenantID}
+ reader.put(webPrincipal("u1"), testEnvConfigID, "sk-1",
+ map[string]string{"TAVILY_API_KEY": "u1-key"})
+ resolver := newTestResolver(reader, searchSkillRow())
+ ctx := types.WithPrincipal(context.Background(), webPrincipal("u1"))
+
+ env, missing, err := resolver.ResolveEnv(ctx, "web-search")
+
+ require.NoError(t, err)
+ require.Empty(t, missing)
+ require.Equal(t, "u1-key", env["TAVILY_API_KEY"])
+ require.Equal(t, "workspace-region", env["SEARCH_REGION"],
+ "a name the caller did not fill in keeps the workspace value")
+}
+
+// Config-wide variables are the whole point of the second scope: they apply
+// whether or not the execution names a skill.
+func TestResolverInjectsConfigWideValuesWithoutASkill(t *testing.T) {
+ reader := &fakeUserEnvReader{tenantID: testEnvTenantID}
+ reader.put(webPrincipal("u1"), testEnvConfigID, "",
+ map[string]string{"HTTP_PROXY": "http://proxy:8080"})
+ resolver := newTestResolver(reader, searchSkillRow())
+ ctx := types.WithPrincipal(context.Background(), webPrincipal("u1"))
+
+ env, missing, err := resolver.ResolveEnv(ctx, "")
+
+ require.NoError(t, err)
+ require.Empty(t, missing, "no skill was named, so nothing can be missing")
+ require.Equal(t, map[string]string{"HTTP_PROXY": "http://proxy:8080"}, env)
+}
+
+func TestResolverAddsConfigWideValuesToASkillRun(t *testing.T) {
+ reader := &fakeUserEnvReader{tenantID: testEnvTenantID}
+ reader.put(webPrincipal("u1"), testEnvConfigID, "",
+ map[string]string{"HTTP_PROXY": "http://proxy:8080"})
+ reader.put(webPrincipal("u1"), testEnvConfigID, "sk-1",
+ map[string]string{"TAVILY_API_KEY": "u1-key"})
+ resolver := newTestResolver(reader, searchSkillRow())
+ ctx := types.WithPrincipal(context.Background(), webPrincipal("u1"))
+
+ env, _, err := resolver.ResolveEnv(ctx, "web-search")
+
+ require.NoError(t, err)
+ require.Equal(t, "http://proxy:8080", env["HTTP_PROXY"])
+ require.Equal(t, "u1-key", env["TAVILY_API_KEY"])
+}
+
+// Specificity decides a collision between the caller's own two scopes: the
+// value they entered for this skill is the more deliberate statement.
+func TestResolverSkillScopeBeatsConfigWideScope(t *testing.T) {
+ reader := &fakeUserEnvReader{tenantID: testEnvTenantID}
+ reader.put(webPrincipal("u1"), testEnvConfigID, "",
+ map[string]string{"TAVILY_API_KEY": "config-wide"})
+ reader.put(webPrincipal("u1"), testEnvConfigID, "sk-1",
+ map[string]string{"TAVILY_API_KEY": "skill-scoped"})
+ resolver := newTestResolver(reader, searchSkillRow())
+ ctx := types.WithPrincipal(context.Background(), webPrincipal("u1"))
+
+ env, _, err := resolver.ResolveEnv(ctx, "web-search")
+
+ require.NoError(t, err)
+ require.Equal(t, "skill-scoped", env["TAVILY_API_KEY"])
+}
+
+// The caller's own config-wide value still beats the admin's workspace value:
+// mine always win over the workspace's.
+func TestResolverConfigWideValueBeatsWorkspaceValue(t *testing.T) {
+ reader := &fakeUserEnvReader{tenantID: testEnvTenantID}
+ reader.put(webPrincipal("u1"), testEnvConfigID, "",
+ map[string]string{"SEARCH_REGION": "mine"})
+ resolver := newTestResolver(reader, searchSkillRow())
+ ctx := types.WithPrincipal(context.Background(), webPrincipal("u1"))
+
+ env, _, err := resolver.ResolveEnv(ctx, "web-search")
+
+ require.NoError(t, err)
+ require.Equal(t, "mine", env["SEARCH_REGION"])
+}
+
+func TestResolverGivesAnotherPrincipalTheWorkspaceValue(t *testing.T) {
+ reader := &fakeUserEnvReader{tenantID: testEnvTenantID}
+ reader.put(webPrincipal("u1"), testEnvConfigID, "sk-1",
+ map[string]string{"TAVILY_API_KEY": "u1-key"})
+ resolver := newTestResolver(reader, searchSkillRow())
+
+ env, _, err := resolver.ResolveEnv(
+ types.WithPrincipal(context.Background(), webPrincipal("u2")), "web-search")
+
+ require.NoError(t, err)
+ require.Equal(t, "workspace-key", env["TAVILY_API_KEY"])
+}
+
+// The IM path sets a real IM principal AND a synthetic web user id. Keying on
+// the user id instead of the principal would hand the IM caller the web user's
+// key, so both directions are asserted.
+func TestResolverDoesNotCrossIMAndWebPrincipals(t *testing.T) {
+ reader := &fakeUserEnvReader{tenantID: testEnvTenantID}
+ reader.put(webPrincipal("system-7"), testEnvConfigID, "sk-1",
+ map[string]string{"TAVILY_API_KEY": "web-key"})
+ reader.put(imPrincipal("wecom:ch1:alice"), testEnvConfigID, "sk-1",
+ map[string]string{"TAVILY_API_KEY": "im-key"})
+ resolver := newTestResolver(reader, searchSkillRow())
+
+ imCtx := types.WithPrincipal(context.Background(), imPrincipal("wecom:ch1:alice"))
+ imCtx = context.WithValue(imCtx, types.UserIDContextKey, "system-7")
+ imEnv, _, err := resolver.ResolveEnv(imCtx, "web-search")
+ require.NoError(t, err)
+ require.Equal(t, "im-key", imEnv["TAVILY_API_KEY"])
+
+ webCtx := context.WithValue(context.Background(), types.UserIDContextKey, "system-7")
+ webEnv, _, err := resolver.ResolveEnv(webCtx, "web-search")
+ require.NoError(t, err)
+ require.Equal(t, "web-key", webEnv["TAVILY_API_KEY"])
+}
+
+// A value entered on another config must not leak into this run: the resolver
+// is pinned to the config the rows came from.
+func TestResolverIsPinnedToItsOwnConfig(t *testing.T) {
+ reader := &fakeUserEnvReader{tenantID: testEnvTenantID}
+ reader.put(webPrincipal("u1"), testEnvOtherConfigID, "",
+ map[string]string{"HTTP_PROXY": "other-config"})
+ resolver := newTestResolver(reader, searchSkillRow())
+ ctx := types.WithPrincipal(context.Background(), webPrincipal("u1"))
+
+ env, _, err := resolver.ResolveEnv(ctx, "web-search")
+
+ require.NoError(t, err)
+ require.NotContains(t, env, "HTTP_PROXY")
+}
+
+func TestResolverReportsMissingRequiredOnly(t *testing.T) {
+ row := searchSkillRow()
+ row.Envs = types.SkillEnvVars{
+ {Name: "TAVILY_API_KEY", Required: true},
+ {Name: "OPTIONAL_TOKEN"},
+ }
+ resolver := newTestResolver(&fakeUserEnvReader{tenantID: testEnvTenantID}, row)
+ ctx := types.WithPrincipal(context.Background(), webPrincipal("u1"))
+
+ env, missing, err := resolver.ResolveEnv(ctx, "web-search")
+
+ require.NoError(t, err)
+ require.Equal(t, []string{"TAVILY_API_KEY"}, missing)
+ require.Empty(t, env)
+}
+
+// An empty workspace value is not a value: injecting it would make an
+// unconfigured variable indistinguishable from one deliberately set to "".
+func TestResolverTreatsAnEmptyWorkspaceValueAsUnset(t *testing.T) {
+ row := searchSkillRow()
+ row.Envs = types.SkillEnvVars{{Name: "TAVILY_API_KEY", Required: true, Value: ""}}
+ resolver := newTestResolver(&fakeUserEnvReader{tenantID: testEnvTenantID}, row)
+ ctx := types.WithPrincipal(context.Background(), webPrincipal("u1"))
+
+ env, missing, err := resolver.ResolveEnv(ctx, "web-search")
+
+ require.NoError(t, err)
+ require.NotContains(t, env, "TAVILY_API_KEY")
+ require.Equal(t, []string{"TAVILY_API_KEY"}, missing)
+}
+
+// Never degrade to the workspace value on a lookup failure: running a skill
+// with somebody else's key is worse than not running it.
+func TestResolverFailsClosedWhenTheLookupFails(t *testing.T) {
+ reader := &fakeUserEnvReader{tenantID: testEnvTenantID, err: errors.New("db down")}
+ resolver := newTestResolver(reader, searchSkillRow())
+ ctx := types.WithPrincipal(context.Background(), webPrincipal("u1"))
+
+ env, missing, err := resolver.ResolveEnv(ctx, "web-search")
+
+ require.Error(t, err)
+ require.Nil(t, env)
+ require.Nil(t, missing)
+}
+
+// Without a principal there is nobody to look up, and no lookup must be
+// attempted under a fallback identity.
+func TestResolverWithoutAPrincipalUsesWorkspaceValuesOnly(t *testing.T) {
+ reader := &fakeUserEnvReader{tenantID: testEnvTenantID}
+ resolver := newTestResolver(reader, searchSkillRow())
+
+ env, _, err := resolver.ResolveEnv(context.Background(), "web-search")
+
+ require.NoError(t, err)
+ require.Equal(t, "workspace-key", env["TAVILY_API_KEY"])
+ require.Zero(t, reader.calls)
+}
+
+// Preloaded skills reach the resolver too and carry no declaration, so an
+// unknown name is not an error — it just resolves the config-wide scope.
+func TestResolverUnknownSkillStillGetsConfigWideValues(t *testing.T) {
+ reader := &fakeUserEnvReader{tenantID: testEnvTenantID}
+ reader.put(webPrincipal("u1"), testEnvConfigID, "",
+ map[string]string{"HTTP_PROXY": "http://proxy:8080"})
+ resolver := newTestResolver(reader, searchSkillRow())
+ ctx := types.WithPrincipal(context.Background(), webPrincipal("u1"))
+
+ env, missing, err := resolver.ResolveEnv(ctx, "preloaded-thing")
+
+ require.NoError(t, err)
+ require.Empty(t, missing)
+ require.Equal(t, map[string]string{"HTTP_PROXY": "http://proxy:8080"}, env)
+}
+
+// The resolver is built even for a run with no installed skills, so shell_exec
+// still receives the caller's config-wide variables.
+func TestResolverWorksWithNoInstalledSkills(t *testing.T) {
+ reader := &fakeUserEnvReader{tenantID: testEnvTenantID}
+ reader.put(webPrincipal("u1"), testEnvConfigID, "",
+ map[string]string{"HTTP_PROXY": "http://proxy:8080"})
+ resolver := NewUserEnvResolver(nil, reader, testEnvTenantID, testEnvConfigID)
+ ctx := types.WithPrincipal(context.Background(), webPrincipal("u1"))
+
+ env, _, err := resolver.ResolveEnv(ctx, "")
+
+ require.NoError(t, err)
+ require.Equal(t, "http://proxy:8080", env["HTTP_PROXY"])
+}
diff --git a/internal/application/service/user_env_test.go b/internal/application/service/user_env_test.go
new file mode 100644
index 000000000..faee2502e
--- /dev/null
+++ b/internal/application/service/user_env_test.go
@@ -0,0 +1,505 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+const userEnvTenantID = uint64(7)
+
+// userEnvCtx builds the only context these calls trust: the workspace and the
+// identity both come from it, and nothing in a request can influence either.
+func userEnvCtx(tenantID uint64, principalID string) context.Context {
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, tenantID)
+ return types.WithPrincipal(ctx, types.Principal{
+ Type: types.PrincipalWebUser, ID: principalID,
+ })
+}
+
+// userEnvConfigRepo is the sandbox-config slice UserEnvService needs: names for
+// the listing, and a workspace-scoped lookup that refuses a foreign config.
+type userEnvConfigRepo struct {
+ rows []*types.TenantSandboxConfigEntity
+}
+
+func (r *userEnvConfigRepo) Create(context.Context, *types.TenantSandboxConfigEntity) error {
+ panic("Create is outside the user env surface")
+}
+
+func (r *userEnvConfigRepo) GetByID(
+ _ context.Context, tenantID uint64, id string,
+) (*types.TenantSandboxConfigEntity, error) {
+ for _, row := range r.rows {
+ if row.TenantID == tenantID && row.ID == id {
+ return row, nil
+ }
+ }
+ return nil, nil
+}
+
+func (r *userEnvConfigRepo) ListByTenant(
+ _ context.Context, tenantID uint64,
+) ([]*types.TenantSandboxConfigEntity, error) {
+ var out []*types.TenantSandboxConfigEntity
+ for _, row := range r.rows {
+ if row.TenantID == tenantID {
+ out = append(out, row)
+ }
+ }
+ return out, nil
+}
+
+func (r *userEnvConfigRepo) ListAll(context.Context) ([]*types.TenantSandboxConfigEntity, error) {
+ panic("ListAll is outside the user env surface")
+}
+func (r *userEnvConfigRepo) Update(context.Context, *types.TenantSandboxConfigEntity) error {
+ panic("Update is outside the user env surface")
+}
+func (r *userEnvConfigRepo) SoftDelete(context.Context, uint64, string) error {
+ panic("SoftDelete is outside the user env surface")
+}
+func (r *userEnvConfigRepo) SetCordon(context.Context, uint64, string, time.Time) error {
+ panic("SetCordon is outside the user env surface")
+}
+func (r *userEnvConfigRepo) ClearCordon(context.Context, uint64, string) error {
+ panic("ClearCordon is outside the user env surface")
+}
+
+var _ repository.TenantSandboxConfigRepository = (*userEnvConfigRepo)(nil)
+
+// newUserEnvFixture seeds one workspace whose skills cover every case the
+// listing has to decide: the one that is exposed, the disabled one, the one
+// still installing, the one declaring nothing, and one belonging to somebody
+// else's workspace.
+func newUserEnvFixture(t *testing.T) (*UserEnvService, *installSkillRepo) {
+ t.Helper()
+ repo := newInstallSkillRepo()
+ ctx := context.Background()
+ for _, skill := range []*types.TenantSkillEntity{
+ {
+ ID: "sk-ready", TenantID: userEnvTenantID, SandboxConfigID: "cfg-1",
+ Name: "pdf-tools", Enabled: true, Status: types.SkillStatusReady,
+ Envs: types.SkillEnvVars{
+ {Name: "API_TOKEN", Description: "workspace token", Required: true, Value: "admin-secret"},
+ {Name: "USER_TOKEN", Description: "your own token", Required: true},
+ {Name: "OPTIONAL_HINT", Description: "nice to have"},
+ },
+ },
+ {
+ ID: "sk-no-declaration", TenantID: userEnvTenantID, SandboxConfigID: "cfg-1",
+ Name: "plain", Enabled: true, Status: types.SkillStatusReady,
+ },
+ {
+ ID: "sk-disabled", TenantID: userEnvTenantID, SandboxConfigID: "cfg-1",
+ Name: "hidden", Enabled: false, Status: types.SkillStatusReady,
+ Envs: types.SkillEnvVars{{Name: "HIDDEN_TOKEN"}},
+ },
+ {
+ ID: "sk-installing", TenantID: userEnvTenantID, SandboxConfigID: "cfg-2",
+ Name: "half-done", Enabled: true, Status: types.SkillStatusInstalling,
+ Envs: types.SkillEnvVars{{Name: "HALF_TOKEN"}},
+ },
+ {
+ ID: "sk-foreign", TenantID: 8, SandboxConfigID: "cfg-9",
+ Name: "theirs", Enabled: true, Status: types.SkillStatusReady,
+ Envs: types.SkillEnvVars{{Name: "THEIR_TOKEN"}},
+ },
+ } {
+ require.NoError(t, repo.CreateSkill(ctx, skill))
+ }
+ configs := &userEnvConfigRepo{rows: []*types.TenantSandboxConfigEntity{
+ {ID: "cfg-1", TenantID: userEnvTenantID, Name: "Production"},
+ {ID: "cfg-2", TenantID: userEnvTenantID, Name: "Staging"},
+ {ID: "cfg-9", TenantID: 8, Name: "Theirs"},
+ }}
+ return NewUserEnvService(repo, configs), repo
+}
+
+func configByID(t *testing.T, groups []ConfigEnvGroup, configID string) ConfigEnvGroup {
+ t.Helper()
+ for _, g := range groups {
+ if g.SandboxConfigID == configID {
+ return g
+ }
+ }
+ t.Fatalf("no group for config %q (%+v)", configID, groups)
+ return ConfigEnvGroup{}
+}
+
+func skillByID(t *testing.T, group ConfigEnvGroup, skillID string) SkillEnvGroup {
+ t.Helper()
+ for _, s := range group.Skills {
+ if s.SkillID == skillID {
+ return s
+ }
+ }
+ t.Fatalf("no skill %q on config %q (%+v)", skillID, group.SandboxConfigID, group.Skills)
+ return SkillEnvGroup{}
+}
+
+func viewByName(t *testing.T, vars []EnvVarView, name string) EnvVarView {
+ t.Helper()
+ for _, v := range vars {
+ if v.Name == name {
+ return v
+ }
+ }
+ t.Fatalf("no variable %q (%+v)", name, vars)
+ return EnvVarView{}
+}
+
+func TestListMineReportsTheThreeSourceStates(t *testing.T) {
+ svc, _ := newUserEnvFixture(t)
+ ctx := userEnvCtx(userEnvTenantID, "alice")
+ require.NoError(t, svc.SetMineSkill(ctx, "sk-ready", "USER_TOKEN", "alice-secret"))
+
+ groups, err := svc.ListMine(ctx)
+ require.NoError(t, err)
+ skill := skillByID(t, configByID(t, groups, "cfg-1"), "sk-ready")
+ require.Equal(t, "pdf-tools", skill.SkillName)
+
+ workspace := viewByName(t, skill.Vars, "API_TOKEN")
+ require.Equal(t, EnvSourceWorkspace, workspace.Source)
+ require.Equal(t, "workspace token", workspace.Description)
+ require.True(t, workspace.Required)
+
+ own := viewByName(t, skill.Vars, "USER_TOKEN")
+ require.Equal(t, EnvSourceUser, own.Source)
+ require.NotNil(t, own.UpdatedAt)
+
+ require.Equal(t, EnvSourceUnset, viewByName(t, skill.Vars, "OPTIONAL_HINT").Source)
+}
+
+// Every config is listed so the config-wide editor is always reachable, even on
+// a config carrying no skills at all.
+func TestListMineListsEveryConfigWithItsName(t *testing.T) {
+ svc, _ := newUserEnvFixture(t)
+
+ groups, err := svc.ListMine(userEnvCtx(userEnvTenantID, "alice"))
+
+ require.NoError(t, err)
+ require.Len(t, groups, 2)
+ require.Equal(t, "Production", groups[0].SandboxConfigName)
+ require.Equal(t, "Staging", groups[1].SandboxConfigName)
+ require.Empty(t, configByID(t, groups, "cfg-2").Skills)
+}
+
+// Both lists must marshal as [] rather than null: the settings page reads
+// .length off them, and a null blanks the whole page.
+func TestListMineNeverReturnsNullLists(t *testing.T) {
+ svc, _ := newUserEnvFixture(t)
+
+ groups, err := svc.ListMine(userEnvCtx(userEnvTenantID, "alice"))
+
+ require.NoError(t, err)
+ require.NotEmpty(t, groups)
+ for _, group := range groups {
+ require.NotNil(t, group.Vars, "config %s", group.SandboxConfigID)
+ require.NotNil(t, group.Skills, "config %s", group.SandboxConfigID)
+ for _, skill := range group.Skills {
+ require.NotNil(t, skill.Vars, "skill %s", skill.SkillID)
+ }
+ }
+}
+
+// A disabled or half-installed skill is never handed to the agent, and a skill
+// declaring nothing has nothing to ask for.
+func TestListMineOnlyListsReadySkillsThatDeclaredSomething(t *testing.T) {
+ svc, _ := newUserEnvFixture(t)
+
+ groups, err := svc.ListMine(userEnvCtx(userEnvTenantID, "alice"))
+
+ require.NoError(t, err)
+ cfg1 := configByID(t, groups, "cfg-1")
+ require.Len(t, cfg1.Skills, 1)
+ require.Equal(t, "sk-ready", cfg1.Skills[0].SkillID)
+}
+
+func TestListMineReportsMyConfigWideVariables(t *testing.T) {
+ svc, _ := newUserEnvFixture(t)
+ ctx := userEnvCtx(userEnvTenantID, "alice")
+ require.NoError(t, svc.SetMineSandbox(ctx, "cfg-1", "HTTP_PROXY", "http://proxy:8080"))
+
+ groups, err := svc.ListMine(ctx)
+ require.NoError(t, err)
+ cfg1 := configByID(t, groups, "cfg-1")
+
+ require.Len(t, cfg1.Vars, 1)
+ require.Equal(t, "HTTP_PROXY", cfg1.Vars[0].Name)
+ require.Equal(t, EnvSourceUser, cfg1.Vars[0].Source)
+ require.NotNil(t, cfg1.Vars[0].UpdatedAt)
+}
+
+func TestListMineDoesNotLeakAnotherPrincipalsValues(t *testing.T) {
+ svc, _ := newUserEnvFixture(t)
+ alice := userEnvCtx(userEnvTenantID, "alice")
+ require.NoError(t, svc.SetMineSkill(alice, "sk-ready", "USER_TOKEN", "alice-secret"))
+ require.NoError(t, svc.SetMineSandbox(alice, "cfg-1", "HTTP_PROXY", "alice-proxy"))
+
+ groups, err := svc.ListMine(userEnvCtx(userEnvTenantID, "bob"))
+ require.NoError(t, err)
+ cfg1 := configByID(t, groups, "cfg-1")
+
+ require.Empty(t, cfg1.Vars, "bob must not even see that alice added a name")
+ skill := skillByID(t, cfg1, "sk-ready")
+ require.Equal(t, EnvSourceUnset, viewByName(t, skill.Vars, "USER_TOKEN").Source)
+ require.Equal(t, EnvSourceWorkspace, viewByName(t, skill.Vars, "API_TOKEN").Source)
+}
+
+// Free-form names belong to the config-wide scope; a skill credential exists
+// only because the skill declared it.
+func TestSetMineSkillRefusesAnUndeclaredName(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+
+ err := svc.SetMineSkill(
+ userEnvCtx(userEnvTenantID, "alice"), "sk-ready", "INVENTED_TOKEN", "v")
+
+ require.Error(t, err)
+ require.Empty(t, repo.userEnvs)
+}
+
+func TestSetMineRejectsUnusableNames(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+ ctx := userEnvCtx(userEnvTenantID, "alice")
+
+ for _, name := range []string{"PATH", "WEKNORA_ARTIFACT_DIR", "lower_case", "HAS SPACE", ""} {
+ t.Run(name, func(t *testing.T) {
+ require.Error(t, svc.SetMineSandbox(ctx, "cfg-1", name, "whatever"))
+ })
+ }
+ require.Empty(t, repo.userEnvs)
+}
+
+func TestSetMineRejectsAnOversizedValue(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+
+ err := svc.SetMineSandbox(userEnvCtx(userEnvTenantID, "alice"), "cfg-1", "TOKEN",
+ strings.Repeat("x", MaxEnvValueBytes+1))
+
+ require.Error(t, err)
+ require.Empty(t, repo.userEnvs)
+}
+
+// The quota bounds how many names one principal keeps in one scope, so a user
+// already at the limit must still be able to rotate a key they hold.
+func TestSetMineEnforcesTheQuotaButStillAllowsRotation(t *testing.T) {
+ svc, _ := newUserEnvFixture(t)
+ ctx := userEnvCtx(userEnvTenantID, "alice")
+ for i := 0; i < MaxUserEnvVarsPerScope; i++ {
+ require.NoError(t, svc.SetMineSandbox(ctx, "cfg-1", envNameForIndex(i), "v"))
+ }
+
+ require.Error(t, svc.SetMineSandbox(ctx, "cfg-1", "ONE_TOO_MANY", "v"))
+ require.NoError(t, svc.SetMineSandbox(ctx, "cfg-1", envNameForIndex(0), "rotated"))
+}
+
+func envNameForIndex(i int) string {
+ return "VAR_" + string(rune('A'+i/26)) + string(rune('A'+i%26))
+}
+
+// Without this check a member could write rows against another workspace's
+// skill ID, which the resolver would then inject into that workspace's run.
+func TestSetMineRefusesASkillOfAnotherWorkspace(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+
+ err := svc.SetMineSkill(userEnvCtx(userEnvTenantID, "alice"), "sk-foreign", "THEIR_TOKEN", "v")
+
+ require.Error(t, err)
+ require.Empty(t, repo.userEnvs)
+}
+
+func TestSetMineSandboxRefusesAConfigOfAnotherWorkspace(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+
+ err := svc.SetMineSandbox(userEnvCtx(userEnvTenantID, "alice"), "cfg-9", "TOKEN", "v")
+
+ require.Error(t, err)
+ require.Empty(t, repo.userEnvs)
+}
+
+// A missing principal is an error, never a default: falling back would let one
+// identity's values be written under another's key.
+func TestSetMineRequiresAPrincipal(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, userEnvTenantID)
+
+ require.Error(t, svc.SetMineSkill(ctx, "sk-ready", "USER_TOKEN", "v"))
+ require.Error(t, svc.SetMineSandbox(ctx, "cfg-1", "TOKEN", "v"))
+ require.Empty(t, repo.userEnvs)
+
+ _, err := svc.ListMine(ctx)
+ require.Error(t, err)
+ require.Error(t, svc.DeleteMineSkill(ctx, "sk-ready", "USER_TOKEN"))
+ require.Error(t, svc.DeleteMineSandbox(ctx, "cfg-1", "TOKEN"))
+}
+
+func TestDeleteMineReportsNothingToDeleteTheSecondTime(t *testing.T) {
+ svc, _ := newUserEnvFixture(t)
+ ctx := userEnvCtx(userEnvTenantID, "alice")
+ require.NoError(t, svc.SetMineSkill(ctx, "sk-ready", "USER_TOKEN", "alice-secret"))
+ require.NoError(t, svc.SetMineSandbox(ctx, "cfg-1", "HTTP_PROXY", "p"))
+
+ require.NoError(t, svc.DeleteMineSkill(ctx, "sk-ready", "USER_TOKEN"))
+ require.True(t, errors.Is(
+ svc.DeleteMineSkill(ctx, "sk-ready", "USER_TOKEN"), types.ErrEnvVarNotFound))
+
+ require.NoError(t, svc.DeleteMineSandbox(ctx, "cfg-1", "HTTP_PROXY"))
+ require.True(t, errors.Is(
+ svc.DeleteMineSandbox(ctx, "cfg-1", "HTTP_PROXY"), types.ErrEnvVarNotFound))
+}
+
+// Deleting is scoped to the caller's own rows, so one member's revocation
+// cannot touch another's value for the same variable.
+func TestDeleteMineTouchesOnlyTheCallersOwnValue(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+ alice := userEnvCtx(userEnvTenantID, "alice")
+ bob := userEnvCtx(userEnvTenantID, "bob")
+ require.NoError(t, svc.SetMineSkill(alice, "sk-ready", "USER_TOKEN", "alice-secret"))
+ require.NoError(t, svc.SetMineSkill(bob, "sk-ready", "USER_TOKEN", "bob-secret"))
+
+ require.NoError(t, svc.DeleteMineSkill(bob, "sk-ready", "USER_TOKEN"))
+
+ require.Len(t, repo.userEnvs, 1)
+ require.Equal(t, "alice", repo.userEnvs[0].PrincipalID)
+ require.Equal(t, "alice-secret", repo.userEnvs[0].Value)
+}
+
+// Revoking must keep working after an admin disables the skill, which is
+// precisely when somebody is most likely to want the credential gone.
+func TestDeleteMineSkillWorksAfterTheSkillIsDisabled(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+ ctx := userEnvCtx(userEnvTenantID, "alice")
+ require.NoError(t, svc.SetMineSkill(ctx, "sk-ready", "USER_TOKEN", "alice-secret"))
+ skill, err := repo.GetSkill(context.Background(), userEnvTenantID, "cfg-1", "sk-ready")
+ require.NoError(t, err)
+ skill.Enabled = false
+ require.NoError(t, repo.UpdateSkill(context.Background(), skill))
+
+ require.NoError(t, svc.DeleteMineSkill(ctx, "sk-ready", "USER_TOKEN"))
+ require.Empty(t, repo.userEnvs)
+}
+
+// The two scopes are independent rows, so the same name can be held in both.
+func TestSetMineKeepsTheTwoScopesApart(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+ ctx := userEnvCtx(userEnvTenantID, "alice")
+
+ require.NoError(t, svc.SetMineSandbox(ctx, "cfg-1", "API_TOKEN", "config-wide"))
+ require.NoError(t, svc.SetMineSkill(ctx, "sk-ready", "API_TOKEN", "skill-scoped"))
+
+ require.Len(t, repo.userEnvs, 2)
+}
+
+func userEnvByName(t *testing.T, rows []*types.TenantUserEnvVar, name string) *types.TenantUserEnvVar {
+ t.Helper()
+ for _, row := range rows {
+ if row != nil && row.Name == name && row.SkillID == "sk-ready" {
+ return row
+ }
+ }
+ t.Fatalf("no skill-scoped row for %q (%+v)", name, rows)
+ return nil
+}
+
+func TestCaptureSkillEnvWritesDeclaredNamesForTheSpeaker(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+ ctx := userEnvCtx(userEnvTenantID, "alice")
+
+ require.NoError(t, svc.CaptureSkillEnv(ctx, "cfg-1", "pdf-tools", map[string]string{
+ "USER_TOKEN": "alice-from-chat",
+ }))
+
+ require.Len(t, repo.userEnvs, 1)
+ got := repo.userEnvs[0]
+ require.Equal(t, "alice", got.PrincipalID)
+ require.Equal(t, "sk-ready", got.SkillID)
+ require.Equal(t, "cfg-1", got.SandboxConfigID)
+ require.Equal(t, "USER_TOKEN", got.Name)
+ require.Equal(t, "alice-from-chat", got.Value)
+}
+
+func TestCaptureSkillEnvSkipsUndeclaredAndReservedNames(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+
+ require.NoError(t, svc.CaptureSkillEnv(
+ userEnvCtx(userEnvTenantID, "alice"), "cfg-1", "pdf-tools", map[string]string{
+ "USER_TOKEN": "keep-me",
+ "INVENTED": "no",
+ "PATH": "/bin",
+ "WEKNORA_HOME": "no",
+ }))
+
+ require.Len(t, repo.userEnvs, 1)
+ require.Equal(t, "USER_TOKEN", repo.userEnvs[0].Name)
+ require.Equal(t, "keep-me", repo.userEnvs[0].Value)
+}
+
+func TestCaptureSkillEnvDoesNotCopyAdminValueIntoUserSlot(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+
+ require.NoError(t, svc.CaptureSkillEnv(
+ userEnvCtx(userEnvTenantID, "alice"), "cfg-1", "pdf-tools", map[string]string{
+ "API_TOKEN": "admin-secret",
+ }))
+
+ require.Empty(t, repo.userEnvs)
+}
+
+func TestCaptureSkillEnvWritesUserOverrideOfAdminValue(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+
+ require.NoError(t, svc.CaptureSkillEnv(
+ userEnvCtx(userEnvTenantID, "alice"), "cfg-1", "pdf-tools", map[string]string{
+ "API_TOKEN": "alice-override",
+ }))
+
+ require.Equal(t, "alice-override", userEnvByName(t, repo.userEnvs, "API_TOKEN").Value)
+}
+
+func TestCaptureSkillEnvSkipsWhenUserValueAlreadyMatches(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+ ctx := userEnvCtx(userEnvTenantID, "alice")
+ require.NoError(t, svc.SetMineSkill(ctx, "sk-ready", "USER_TOKEN", "already-mine"))
+ require.Len(t, repo.userEnvs, 1)
+
+ require.NoError(t, svc.CaptureSkillEnv(ctx, "cfg-1", "pdf-tools", map[string]string{
+ "USER_TOKEN": "already-mine",
+ }))
+
+ require.Len(t, repo.userEnvs, 1)
+ require.Equal(t, "already-mine", repo.userEnvs[0].Value)
+}
+
+func TestCaptureSkillEnvRotatesADifferentUserValue(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+ ctx := userEnvCtx(userEnvTenantID, "alice")
+ require.NoError(t, svc.SetMineSkill(ctx, "sk-ready", "USER_TOKEN", "old-key"))
+
+ require.NoError(t, svc.CaptureSkillEnv(ctx, "cfg-1", "pdf-tools", map[string]string{
+ "USER_TOKEN": "new-key",
+ }))
+
+ require.Len(t, repo.userEnvs, 1)
+ require.Equal(t, "new-key", repo.userEnvs[0].Value)
+}
+
+func TestCaptureSkillEnvIgnoresUnknownOrUnusableSkills(t *testing.T) {
+ svc, repo := newUserEnvFixture(t)
+ ctx := userEnvCtx(userEnvTenantID, "alice")
+
+ require.NoError(t, svc.CaptureSkillEnv(ctx, "cfg-1", "", map[string]string{"USER_TOKEN": "v"}))
+ require.NoError(t, svc.CaptureSkillEnv(ctx, "cfg-1", "no-such-skill", map[string]string{"USER_TOKEN": "v"}))
+ require.NoError(t, svc.CaptureSkillEnv(ctx, "cfg-1", "plain", map[string]string{"USER_TOKEN": "v"}))
+ require.NoError(t, svc.CaptureSkillEnv(ctx, "cfg-1", "hidden", map[string]string{"HIDDEN_TOKEN": "v"}))
+ require.NoError(t, svc.CaptureSkillEnv(ctx, "cfg-2", "half-done", map[string]string{"HALF_TOKEN": "v"}))
+
+ require.Empty(t, repo.userEnvs)
+}
diff --git a/internal/container/container.go b/internal/container/container.go
index d8485ff76..b22b07054 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -299,6 +299,10 @@ func BuildContainer(container *dig.Container) *dig.Container {
logger.Debugf(ctx, "[Container] Registering session service...")
must(container.Provide(service.NewSessionService))
must(container.Provide(service.NewTenantSkillService))
+ // The member-facing half of env vars is its own service because its
+ // authority is different in kind: it derives the identity from the context
+ // and touches only that identity's rows.
+ must(container.Provide(service.NewUserEnvService))
// ArtifactCollector drains skill-generated files from the sandbox on
// each agent turn (see spec at
@@ -406,6 +410,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
) *handler.SandboxSkillHandler {
return handler.NewSandboxSkillHandler(s, streams)
}))
+ must(container.Provide(handler.NewMeEnvVarHandler))
must(container.Provide(handler.NewEvaluationHandler))
must(container.Provide(handler.NewInitializationHandler))
must(container.Provide(handler.NewAuthHandler))
diff --git a/internal/handler/me_env_var.go b/internal/handler/me_env_var.go
new file mode 100644
index 000000000..b2a36ae5f
--- /dev/null
+++ b/internal/handler/me_env_var.go
@@ -0,0 +1,197 @@
+package handler
+
+import (
+ "context"
+ stderrors "errors"
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/Tencent/WeKnora/internal/application/service"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// meEnvVarService is the member-facing slice of the env var surface. Not one
+// method takes an identity: the service derives it from the context, which is
+// what makes it impossible for a request to select whose values are touched.
+type meEnvVarService interface {
+ ListMine(ctx context.Context) ([]service.ConfigEnvGroup, error)
+ SetMineSkill(ctx context.Context, skillID, name, value string) error
+ DeleteMineSkill(ctx context.Context, skillID, name string) error
+ SetMineSandbox(ctx context.Context, configID, name, value string) error
+ DeleteMineSandbox(ctx context.Context, configID, name string) error
+}
+
+// MeEnvVarHandler serves the /me/env-vars endpoints.
+//
+// These exist instead of relaxing /sandbox-configs/:id/skills*, which is Admin+
+// even for reads on purpose: an upload there drives a root shell whose output is
+// baked into the image every session of that config boots, and the listing names
+// what that image carries. This handler returns declarations and set/unset
+// status only — never a value.
+type MeEnvVarHandler struct {
+ service meEnvVarService
+}
+
+func NewMeEnvVarHandler(s *service.UserEnvService) *MeEnvVarHandler {
+ return &MeEnvVarHandler{service: s}
+}
+
+// meEnvVarRequest is the body of every write endpoint. It has no principal
+// field, deliberately: not an ignored one, an absent one. A field that could
+// name an identity is one refactor away from being honoured, and honouring it
+// would let any logged-in member write another member's values.
+type meEnvVarRequest struct {
+ SkillID string `json:"skill_id"`
+ SandboxConfigID string `json:"sandbox_config_id"`
+ Name string `json:"name"`
+ // Value is unused by the delete endpoints. Clearing a value is a delete
+ // rather than a write of "", so a member always has one unambiguous way to
+ // revoke.
+ Value string `json:"value"`
+}
+
+// respondEnvVarError renders a refusal. Nothing to delete is a 404; a rejected
+// input is a 400; anything else is the service failing and stays a 500 so an
+// internal message never reaches a member.
+func respondEnvVarError(c *gin.Context, err error) {
+ switch {
+ case stderrors.Is(err, types.ErrEnvVarNotFound):
+ c.Error(apperrors.NewNotFoundError("this environment variable is not set"))
+ default:
+ c.Error(err)
+ }
+}
+
+// List godoc
+// @Summary List my environment variables
+// @Description List every sandbox config of this workspace with the caller's own config-wide variables and the credentials its skills declared, each reporting whether it is unset, filled in workspace-wide, or filled in by the caller. Values are never returned.
+// @Tags Me
+// @Produce json
+// @Success 200 {object} map[string]interface{} "One group per sandbox config"
+// @Failure 401 {object} map[string]interface{} "Unauthorized"
+// @Security Bearer
+// @Router /me/env-vars [get]
+func (h *MeEnvVarHandler) List(c *gin.Context) {
+ groups, err := h.service.ListMine(c.Request.Context())
+ if err != nil {
+ c.Error(err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": groups})
+}
+
+// SetSkill godoc
+// @Summary Set one of my skill credentials
+// @Description Store the caller's own value for one variable the skill declared. It overrides the workspace-wide value for this caller only, and is injected only into executions that name this skill.
+// @Tags Me
+// @Accept json
+// @Produce json
+// @Param request body meEnvVarRequest true "Skill, variable name and value"
+// @Success 200 {object} map[string]interface{} "Stored"
+// @Failure 400 {object} apperrors.AppError "Invalid request"
+// @Security Bearer
+// @Router /me/env-vars/skill [put]
+func (h *MeEnvVarHandler) SetSkill(c *gin.Context) {
+ req, ok := bindEnvVarRequest(c, "skill_id", func(r meEnvVarRequest) string { return r.SkillID })
+ if !ok {
+ return
+ }
+ if err := h.service.SetMineSkill(c.Request.Context(), req.SkillID, req.Name, req.Value); err != nil {
+ respondEnvVarError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
+
+// DeleteSkill godoc
+// @Summary Delete one of my skill credentials
+// @Description Remove the caller's own value. The workspace-wide value, if there is one, applies again afterwards.
+// @Tags Me
+// @Accept json
+// @Produce json
+// @Param request body meEnvVarRequest true "Skill and variable name"
+// @Success 200 {object} map[string]interface{} "Deleted"
+// @Failure 404 {object} apperrors.AppError "Not set"
+// @Security Bearer
+// @Router /me/env-vars/skill [delete]
+func (h *MeEnvVarHandler) DeleteSkill(c *gin.Context) {
+ req, ok := bindEnvVarRequest(c, "skill_id", func(r meEnvVarRequest) string { return r.SkillID })
+ if !ok {
+ return
+ }
+ if err := h.service.DeleteMineSkill(c.Request.Context(), req.SkillID, req.Name); err != nil {
+ respondEnvVarError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
+
+// SetSandbox godoc
+// @Summary Set one of my sandbox environment variables
+// @Description Store the caller's own value for one variable on a sandbox config. It is injected into every skill script and shell command this caller's turns run on that config.
+// @Tags Me
+// @Accept json
+// @Produce json
+// @Param request body meEnvVarRequest true "Sandbox config, variable name and value"
+// @Success 200 {object} map[string]interface{} "Stored"
+// @Failure 400 {object} apperrors.AppError "Invalid request"
+// @Security Bearer
+// @Router /me/env-vars/sandbox [put]
+func (h *MeEnvVarHandler) SetSandbox(c *gin.Context) {
+ req, ok := bindEnvVarRequest(c, "sandbox_config_id",
+ func(r meEnvVarRequest) string { return r.SandboxConfigID })
+ if !ok {
+ return
+ }
+ err := h.service.SetMineSandbox(c.Request.Context(), req.SandboxConfigID, req.Name, req.Value)
+ if err != nil {
+ respondEnvVarError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
+
+// DeleteSandbox godoc
+// @Summary Delete one of my sandbox environment variables
+// @Description Remove the caller's own value for one variable on a sandbox config.
+// @Tags Me
+// @Accept json
+// @Produce json
+// @Param request body meEnvVarRequest true "Sandbox config and variable name"
+// @Success 200 {object} map[string]interface{} "Deleted"
+// @Failure 404 {object} apperrors.AppError "Not set"
+// @Security Bearer
+// @Router /me/env-vars/sandbox [delete]
+func (h *MeEnvVarHandler) DeleteSandbox(c *gin.Context) {
+ req, ok := bindEnvVarRequest(c, "sandbox_config_id",
+ func(r meEnvVarRequest) string { return r.SandboxConfigID })
+ if !ok {
+ return
+ }
+ err := h.service.DeleteMineSandbox(c.Request.Context(), req.SandboxConfigID, req.Name)
+ if err != nil {
+ respondEnvVarError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
+
+// bindEnvVarRequest decodes a write body and refuses one missing its scope key
+// or its name, so every endpoint reports the same two required fields the same
+// way.
+func bindEnvVarRequest(
+ c *gin.Context, scopeField string, scope func(meEnvVarRequest) string,
+) (meEnvVarRequest, bool) {
+ var req meEnvVarRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.Error(apperrors.NewBadRequestError(err.Error()))
+ return req, false
+ }
+ if scope(req) == "" || req.Name == "" {
+ c.Error(apperrors.NewBadRequestError(scopeField + " and name are required"))
+ return req, false
+ }
+ return req, true
+}
diff --git a/internal/handler/me_env_var_test.go b/internal/handler/me_env_var_test.go
new file mode 100644
index 000000000..68259bcc2
--- /dev/null
+++ b/internal/handler/me_env_var_test.go
@@ -0,0 +1,227 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/application/service"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/middleware"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+type fakeMeEnvVarService struct {
+ groups []service.ConfigEnvGroup
+ listErr error
+ setErr error
+ delErr error
+
+ setScope, setName, setValue string
+ delScope, delName string
+}
+
+func (f *fakeMeEnvVarService) ListMine(context.Context) ([]service.ConfigEnvGroup, error) {
+ return f.groups, f.listErr
+}
+
+func (f *fakeMeEnvVarService) SetMineSkill(_ context.Context, skillID, name, value string) error {
+ f.setScope, f.setName, f.setValue = skillID, name, value
+ return f.setErr
+}
+
+func (f *fakeMeEnvVarService) DeleteMineSkill(_ context.Context, skillID, name string) error {
+ f.delScope, f.delName = skillID, name
+ return f.delErr
+}
+
+func (f *fakeMeEnvVarService) SetMineSandbox(_ context.Context, configID, name, value string) error {
+ f.setScope, f.setName, f.setValue = configID, name, value
+ return f.setErr
+}
+
+func (f *fakeMeEnvVarService) DeleteMineSandbox(_ context.Context, configID, name string) error {
+ f.delScope, f.delName = configID, name
+ return f.delErr
+}
+
+func newMeEnvVarRouter(svc meEnvVarService) *gin.Engine {
+ gin.SetMode(gin.TestMode)
+ r := gin.New()
+ r.Use(middleware.ErrorHandler())
+ h := &MeEnvVarHandler{service: svc}
+ r.GET("/me/env-vars", h.List)
+ r.PUT("/me/env-vars/skill", h.SetSkill)
+ r.DELETE("/me/env-vars/skill", h.DeleteSkill)
+ r.PUT("/me/env-vars/sandbox", h.SetSandbox)
+ r.DELETE("/me/env-vars/sandbox", h.DeleteSandbox)
+ return r
+}
+
+func envVarRequest(method, path, body string) *http.Request {
+ req := httptest.NewRequest(method, path, strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ return req
+}
+
+// The principal is derived from the context, so the request type must have no
+// field that could name one — absent rather than ignored, because an ignored
+// field is one refactor away from being honoured.
+func TestMeEnvVarRequestCannotCarryAPrincipal(t *testing.T) {
+ rt := reflect.TypeOf(meEnvVarRequest{})
+ for i := 0; i < rt.NumField(); i++ {
+ field := rt.Field(i)
+ lower := strings.ToLower(field.Name + " " + field.Tag.Get("json"))
+ for _, forbidden := range []string{"principal", "user"} {
+ require.NotContains(t, lower, forbidden,
+ "field %s would let a request choose whose values are touched", field.Name)
+ }
+ }
+
+ raw, err := json.Marshal(meEnvVarRequest{})
+ require.NoError(t, err)
+ require.NotContains(t, strings.ToLower(string(raw)), "principal")
+}
+
+// A body that tries to name somebody else must simply not bind: the extra keys
+// are dropped and the handler still passes only what the type carries.
+func TestMeEnvVarSetIgnoresPrincipalFieldsInTheBody(t *testing.T) {
+ svc := &fakeMeEnvVarService{}
+ router := newMeEnvVarRouter(svc)
+
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, envVarRequest(http.MethodPut, "/me/env-vars/skill",
+ `{"skill_id":"sk-1","name":"API_TOKEN","value":"mine",`+
+ `"principal_id":"bob","principal_type":"web_user","user_id":"bob"}`))
+
+ require.Equal(t, http.StatusOK, w.Code)
+ require.Equal(t, "sk-1", svc.setScope)
+ require.Equal(t, "API_TOKEN", svc.setName)
+ require.Equal(t, "mine", svc.setValue)
+}
+
+func TestEnvVarGroupJSONCarriesNoSecrets(t *testing.T) {
+ updated := time.Date(2026, 8, 24, 9, 0, 0, 0, time.UTC)
+ svc := &fakeMeEnvVarService{groups: []service.ConfigEnvGroup{{
+ SandboxConfigID: "cfg-a",
+ SandboxConfigName: "Production",
+ Vars: []service.EnvVarView{
+ {Name: "HTTP_PROXY", Source: service.EnvSourceUser, UpdatedAt: &updated},
+ },
+ Skills: []service.SkillEnvGroup{{
+ SkillID: "sk-1",
+ SkillName: "pdf-tools",
+ Vars: []service.EnvVarView{
+ {Name: "API_TOKEN", Description: "the workspace token", Required: true,
+ Source: service.EnvSourceWorkspace},
+ {Name: "USER_TOKEN", Source: service.EnvSourceUser, UpdatedAt: &updated},
+ {Name: "REGION", Source: service.EnvSourceUnset},
+ },
+ }},
+ }}}
+ router := newMeEnvVarRouter(svc)
+
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/me/env-vars", nil))
+
+ require.Equal(t, http.StatusOK, w.Code)
+ body := w.Body.String()
+ for _, forbidden := range []string{
+ `"value"`, "instructions", "bundle_ref", "installed_snapshot_id",
+ `"status"`, `"error"`,
+ } {
+ require.NotContains(t, body, forbidden)
+ }
+ require.Contains(t, body, `"sandbox_config_name":"Production"`)
+ require.Contains(t, body, `"skill_name":"pdf-tools"`)
+ require.Contains(t, body, `"source":"workspace"`)
+ require.Contains(t, body, `"source":"user"`)
+ require.Contains(t, body, `"source":"unset"`)
+}
+
+func TestMeEnvVarWritesRejectAnIncompleteBody(t *testing.T) {
+ cases := []struct{ path, body string }{
+ {"/me/env-vars/skill", `{}`},
+ {"/me/env-vars/skill", `{"skill_id":"sk-1"}`},
+ {"/me/env-vars/skill", `{"name":"API_TOKEN"}`},
+ // A skill id on the sandbox route names no config.
+ {"/me/env-vars/sandbox", `{"skill_id":"sk-1","name":"API_TOKEN"}`},
+ {"/me/env-vars/sandbox", `{"sandbox_config_id":"cfg-a"}`},
+ }
+ for _, tc := range cases {
+ t.Run(tc.path+tc.body, func(t *testing.T) {
+ svc := &fakeMeEnvVarService{}
+ w := httptest.NewRecorder()
+ newMeEnvVarRouter(svc).ServeHTTP(w, envVarRequest(http.MethodPut, tc.path, tc.body))
+
+ require.Equal(t, http.StatusBadRequest, w.Code)
+ require.Empty(t, svc.setScope)
+ })
+ }
+}
+
+// A refused name is the caller's mistake, and the service says so with an
+// AppError; the handler must not turn that into a 500.
+func TestMeEnvVarSetMapsAServiceRefusalTo400(t *testing.T) {
+ svc := &fakeMeEnvVarService{
+ setErr: apperrors.NewBadRequestError(`environment variable name "PATH" is reserved`),
+ }
+ w := httptest.NewRecorder()
+ newMeEnvVarRouter(svc).ServeHTTP(w, envVarRequest(http.MethodPut, "/me/env-vars/sandbox",
+ `{"sandbox_config_id":"cfg-a","name":"PATH","value":"x"}`))
+
+ require.Equal(t, http.StatusBadRequest, w.Code)
+}
+
+// A repository failure is not the caller's mistake. Reporting it as 400 would
+// both mislead and hand an internal message to any logged-in member.
+func TestMeEnvVarSetDoesNotReportAServerFailureAs400(t *testing.T) {
+ svc := &fakeMeEnvVarService{setErr: errors.New("dial tcp 10.0.0.5:5432: connect: refused")}
+ w := httptest.NewRecorder()
+ newMeEnvVarRouter(svc).ServeHTTP(w, envVarRequest(http.MethodPut, "/me/env-vars/sandbox",
+ `{"sandbox_config_id":"cfg-a","name":"HTTP_PROXY","value":"x"}`))
+
+ require.Equal(t, http.StatusInternalServerError, w.Code)
+ require.NotContains(t, w.Body.String(), "10.0.0.5")
+}
+
+func TestMeEnvVarDeleteMapsNothingToDeleteTo404(t *testing.T) {
+ for _, path := range []string{"/me/env-vars/skill", "/me/env-vars/sandbox"} {
+ t.Run(path, func(t *testing.T) {
+ svc := &fakeMeEnvVarService{delErr: types.ErrEnvVarNotFound}
+ body := `{"skill_id":"sk-1","sandbox_config_id":"cfg-a","name":"API_TOKEN"}`
+ w := httptest.NewRecorder()
+ newMeEnvVarRouter(svc).ServeHTTP(w, envVarRequest(http.MethodDelete, path, body))
+
+ require.Equal(t, http.StatusNotFound, w.Code)
+ require.Equal(t, "API_TOKEN", svc.delName)
+ })
+ }
+}
+
+func TestMeEnvVarDeleteRoutesToTheRequestedScope(t *testing.T) {
+ body := `{"skill_id":"sk-1","sandbox_config_id":"cfg-a","name":"API_TOKEN"}`
+
+ skillSvc := &fakeMeEnvVarService{}
+ w := httptest.NewRecorder()
+ newMeEnvVarRouter(skillSvc).ServeHTTP(w,
+ envVarRequest(http.MethodDelete, "/me/env-vars/skill", body))
+ require.Equal(t, http.StatusOK, w.Code)
+ require.Equal(t, "sk-1", skillSvc.delScope)
+
+ sandboxSvc := &fakeMeEnvVarService{}
+ w = httptest.NewRecorder()
+ newMeEnvVarRouter(sandboxSvc).ServeHTTP(w,
+ envVarRequest(http.MethodDelete, "/me/env-vars/sandbox", body))
+ require.Equal(t, http.StatusOK, w.Code)
+ require.Equal(t, "cfg-a", sandboxSvc.delScope)
+}
diff --git a/internal/handler/sandbox_skill.go b/internal/handler/sandbox_skill.go
index 9d032d651..d00b6bd08 100644
--- a/internal/handler/sandbox_skill.go
+++ b/internal/handler/sandbox_skill.go
@@ -50,8 +50,9 @@ type sandboxSkillService interface {
ReadSkillFile(
ctx context.Context, tenantID uint64, configID, skillID, relativePath string,
) (*service.SkillFileContent, error)
- SetSkillEnabled(
- ctx context.Context, tenantID uint64, configID, skillID string, enabled bool,
+ UpdateSkillAdmin(
+ ctx context.Context, tenantID uint64, configID, skillID string,
+ update service.SkillAdminUpdate,
) (*types.TenantSkillEntity, error)
InstallSkill(ctx context.Context, tenantID uint64, configID string, archive []byte) (string, error)
InstallSkillFromSource(
@@ -111,6 +112,34 @@ type skillResponse struct {
InstallMessageID string `json:"install_message_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
+
+ Envs []skillEnvResponse `json:"envs,omitempty"`
+}
+
+// skillEnvResponse is one declared environment variable. It reports whether a
+// workspace value exists and never what it is: a stored credential is written
+// once and read only by the sandbox that needs it.
+type skillEnvResponse struct {
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ Required bool `json:"required,omitempty"`
+ IsSet bool `json:"is_set"`
+}
+
+func toSkillEnvResponses(envs types.SkillEnvVars) []skillEnvResponse {
+ if len(envs) == 0 {
+ return nil
+ }
+ out := make([]skillEnvResponse, 0, len(envs))
+ for _, entry := range envs {
+ out = append(out, skillEnvResponse{
+ Name: entry.Name,
+ Description: entry.Description,
+ Required: entry.Required,
+ IsSet: entry.Value != "",
+ })
+ }
+ return out
}
func toSkillResponse(e *types.TenantSkillEntity) skillResponse {
@@ -131,6 +160,7 @@ func toSkillResponse(e *types.TenantSkillEntity) skillResponse {
InstallMessageID: e.InstallMessageID,
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
+ Envs: toSkillEnvResponses(e.Envs),
}
}
@@ -383,14 +413,18 @@ func skillTooLargeError() error {
}
type skillPatchRequest struct {
- // Enabled is a pointer because its absence is a bad request rather than a
- // request to disable the skill.
+ // Enabled is a pointer because its absence is not a request to disable the
+ // skill; a body may carry envs instead.
Enabled *bool `json:"enabled"`
+ // Envs is a pointer to a map because "sent an empty object" and "did not
+ // mention envs" are different requests: the first clears what it names,
+ // the second must leave every stored value alone.
+ Envs *map[string]string `json:"envs"`
}
// Patch godoc
// @Summary Update an installed skill
-// @Description Show or hide an installed skill. The files stay in the image either way; removal is a separate flow.
+// @Description Show or hide an installed skill and set the workspace-wide values of the environment variables it declared. Either field may be sent, or both. The files stay in the image either way; removal is a separate flow.
// @Tags SandboxConfig
// @Accept json
// @Produce json
@@ -410,12 +444,23 @@ func (h *SandboxSkillHandler) Patch(c *gin.Context) {
_ = c.Error(apperrors.NewBadRequestError(err.Error()))
return
}
- if req.Enabled == nil {
- _ = c.Error(apperrors.NewBadRequestError("enabled is required"))
+ if req.Enabled == nil && req.Envs == nil {
+ _ = c.Error(apperrors.NewBadRequestError("enabled or envs is required"))
return
}
- updated, err := h.service.SetSkillEnabled(c.Request.Context(), sandboxConfigTenantID(c),
- c.Param("id"), c.Param("skillId"), *req.Enabled)
+
+ ctx := c.Request.Context()
+ tenantID := sandboxConfigTenantID(c)
+ configID, skillID := c.Param("id"), c.Param("skillId")
+
+ // Both fields go down in one call so the request is all-or-nothing: two
+ // service calls could persist the toggle and then fail the values, which
+ // is exactly what a half-applied credential rotation looks like.
+ update := service.SkillAdminUpdate{Enabled: req.Enabled}
+ if req.Envs != nil {
+ update.EnvValues = *req.Envs
+ }
+ updated, err := h.service.UpdateSkillAdmin(ctx, tenantID, configID, skillID, update)
if err != nil {
_ = c.Error(err)
return
diff --git a/internal/handler/sandbox_skill_env_test.go b/internal/handler/sandbox_skill_env_test.go
new file mode 100644
index 000000000..644eed7bc
--- /dev/null
+++ b/internal/handler/sandbox_skill_env_test.go
@@ -0,0 +1,124 @@
+package handler
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// skillWithEnvDeclaration is a row carrying everything the projection has to
+// keep out of a response: the stored credential, the SKILL.md body and the
+// pointer to the uploaded archive.
+func skillWithEnvDeclaration() *types.TenantSkillEntity {
+ return &types.TenantSkillEntity{
+ ID: "skill-1", TenantID: testSkillTenantID, SandboxConfigID: "cfg-a",
+ Name: "pdf", Status: types.SkillStatusReady, Enabled: true,
+ Instructions: "run scripts/extract.py to read a pdf",
+ BundleRef: "tenant/42/skills/pdf.zip",
+ Envs: types.SkillEnvVars{
+ {Name: "API_TOKEN", Description: "the workspace token", Required: true, Value: "admin-secret"},
+ {Name: "REGION", Description: "which region"},
+ },
+ }
+}
+
+// The response says whether a value exists and never what it is. Instructions
+// and the bundle pointer are level-2 disclosure for the agent, not for a
+// listing.
+func TestSkillResponseReportsIsSetWithoutTheValue(t *testing.T) {
+ raw, err := json.Marshal(toSkillResponse(skillWithEnvDeclaration()))
+ require.NoError(t, err)
+ body := string(raw)
+
+ require.NotContains(t, body, "admin-secret")
+ require.NotContains(t, body, "scripts/extract.py")
+ require.NotContains(t, body, "pdf.zip")
+ require.NotContains(t, body, `"value"`)
+
+ require.Contains(t, body, `"API_TOKEN"`)
+ require.Contains(t, body, "the workspace token")
+ require.Contains(t, body, `"is_set":true`)
+ require.Contains(t, body, `"required":true`)
+ require.Contains(t, body, `"is_set":false`)
+}
+
+func TestSkillResponsePatchWritesEnvValues(t *testing.T) {
+ skill := skillWithEnvDeclaration()
+ svc := &fakeSandboxSkillService{skills: map[string]*types.TenantSkillEntity{"skill-1": skill}}
+ router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
+
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPatch, "/sandbox-configs/cfg-a/skills/skill-1",
+ strings.NewReader(`{"envs":{"API_TOKEN":"rotated"}}`))
+ req.Header.Set("Content-Type", "application/json")
+ router.ServeHTTP(w, req)
+
+ require.Equal(t, http.StatusOK, w.Code)
+ require.Equal(t, map[string]string{"API_TOKEN": "rotated"}, svc.patchEnvs)
+ require.NotContains(t, w.Body.String(), "rotated")
+ require.True(t, svc.skills["skill-1"].Enabled, "envs-only patch must not touch visibility")
+}
+
+// An empty object is a real request — "clear everything you sent me" — and is
+// distinguishable from a body that never mentioned envs at all.
+func TestSkillResponsePatchAcceptsAnEmptyEnvsObject(t *testing.T) {
+ svc := &fakeSandboxSkillService{skills: map[string]*types.TenantSkillEntity{
+ "skill-1": skillWithEnvDeclaration(),
+ }}
+ router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
+
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPatch, "/sandbox-configs/cfg-a/skills/skill-1",
+ strings.NewReader(`{"envs":{}}`))
+ req.Header.Set("Content-Type", "application/json")
+ router.ServeHTTP(w, req)
+
+ require.Equal(t, http.StatusOK, w.Code)
+ require.NotNil(t, svc.patchEnvs)
+ require.Empty(t, svc.patchEnvs)
+}
+
+// The existing contract must survive: an enabled-only body is still a valid
+// request and must not start requiring envs.
+func TestSkillResponsePatchStillAcceptsEnabledAlone(t *testing.T) {
+ svc := &fakeSandboxSkillService{skills: map[string]*types.TenantSkillEntity{
+ "skill-1": skillWithEnvDeclaration(),
+ }}
+ router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
+
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPatch, "/sandbox-configs/cfg-a/skills/skill-1",
+ strings.NewReader(`{"enabled":false}`))
+ req.Header.Set("Content-Type", "application/json")
+ router.ServeHTTP(w, req)
+
+ require.Equal(t, http.StatusOK, w.Code)
+ require.False(t, svc.patchEnabled)
+ require.Nil(t, svc.patchEnvs, "an enabled-only body must not be read as clearing values")
+}
+
+func TestSkillResponsePatchAcceptsEnabledAndEnvsTogether(t *testing.T) {
+ svc := &fakeSandboxSkillService{skills: map[string]*types.TenantSkillEntity{
+ "skill-1": skillWithEnvDeclaration(),
+ }}
+ router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
+
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPatch, "/sandbox-configs/cfg-a/skills/skill-1",
+ strings.NewReader(`{"enabled":false,"envs":{"REGION":"eu"}}`))
+ req.Header.Set("Content-Type", "application/json")
+ router.ServeHTTP(w, req)
+
+ require.Equal(t, http.StatusOK, w.Code)
+ require.False(t, svc.patchEnabled)
+ require.Equal(t, map[string]string{"REGION": "eu"}, svc.patchEnvs)
+ require.Equal(t, 1, svc.patchCalls,
+ "both fields must reach the service in one call, or a failed second write "+
+ "leaves the first already persisted")
+}
diff --git a/internal/handler/sandbox_skill_test.go b/internal/handler/sandbox_skill_test.go
index 1ad699279..34b8b8f1b 100644
--- a/internal/handler/sandbox_skill_test.go
+++ b/internal/handler/sandbox_skill_test.go
@@ -71,7 +71,13 @@ type fakeSandboxSkillService struct {
removeConfig string
removeSkill string
patchEnabled bool
- closed bool
+ // patchEnvs is nil until a request actually carried the field, so a test
+ // can tell "did not mention envs" from "sent an empty object".
+ patchEnvs map[string]string
+ // patchCalls counts service calls per request, so a handler that split
+ // one PATCH back into two read-modify-write cycles fails the test.
+ patchCalls int
+ closed bool
// onGet runs on every read, so a test can model a row that disappears
// while the client is streaming.
onGet func(calls int)
@@ -113,18 +119,36 @@ func (f *fakeSandboxSkillService) GetSkill(
return skill, nil
}
-func (f *fakeSandboxSkillService) SetSkillEnabled(
- _ context.Context, tenantID uint64, configID, skillID string, enabled bool,
+// UpdateSkillAdmin mirrors the real service: only declared names are written,
+// and an unreachable skill is reported as nil rather than as an error. A fake
+// that accepted any name would let the handler stop being the layer that keeps
+// the declaration meaningful.
+func (f *fakeSandboxSkillService) UpdateSkillAdmin(
+ _ context.Context, tenantID uint64, configID, skillID string,
+ update service.SkillAdminUpdate,
) (*types.TenantSkillEntity, error) {
+ f.patchCalls++
if f.patchErr != nil {
return nil, f.patchErr
}
- f.patchEnabled = enabled
+ if update.Enabled != nil {
+ f.patchEnabled = *update.Enabled
+ }
+ if update.EnvValues != nil {
+ f.patchEnvs = update.EnvValues
+ }
skill := f.skills[skillID]
if skill == nil || tenantID != testSkillTenantID || skill.SandboxConfigID != configID {
return nil, nil
}
- skill.Enabled = enabled
+ if update.Enabled != nil {
+ skill.Enabled = *update.Enabled
+ }
+ for i := range skill.Envs {
+ if value, sent := update.EnvValues[skill.Envs[i].Name]; sent {
+ skill.Envs[i].Value = value
+ }
+ }
return skill, nil
}
diff --git a/internal/router/router.go b/internal/router/router.go
index c164734e7..1e587b567 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -58,6 +58,7 @@ type RouterParams struct {
ModelCredentialsHandler *handler.ModelCredentialsHandler
SandboxConfigHandler *handler.SandboxConfigHandler
SandboxSkillHandler *handler.SandboxSkillHandler
+ MeEnvVarHandler *handler.MeEnvVarHandler
EvaluationHandler *handler.EvaluationHandler
AuthHandler *handler.AuthHandler
InitializationHandler *handler.InitializationHandler
@@ -266,6 +267,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterMessageRoutes(v1, params.MessageHandler, rbacGuards)
RegisterModelRoutes(v1, params.ModelHandler, params.ModelCredentialsHandler, rbacGuards)
RegisterSandboxConfigRoutes(v1, params.SandboxConfigHandler, params.SandboxSkillHandler, rbacGuards)
+ RegisterMyEnvVarRoutes(v1, params.MeEnvVarHandler)
RegisterEvaluationRoutes(v1, params.EvaluationHandler, rbacGuards)
RegisterInitializationRoutes(v1, params.InitializationHandler, rbacGuards)
params.SystemHandler.BindDeploymentCapabilities(deploymentCapabilitiesFromRouter(params))
diff --git a/internal/router/routes_auth_tenant.go b/internal/router/routes_auth_tenant.go
index 38d36bfc4..d495723d8 100644
--- a/internal/router/routes_auth_tenant.go
+++ b/internal/router/routes_auth_tenant.go
@@ -176,6 +176,32 @@ func RegisterMyInvitationRoutes(r *gin.RouterGroup, invitationHandler *handler.T
}
}
+// RegisterMyEnvVarRoutes wires the caller's own environment variables under
+// /me/env-vars. The v1 group already applies middleware.Auth, and no role gate
+// is added on purpose: these are the caller's own values, and the service
+// derives whose they are from the context rather than the request.
+//
+// This deliberately does not reuse /sandbox-configs/:id/skills*, which is
+// Admin+ even for reads (see routes_infra.go): an upload there drives a root
+// shell whose output is baked into the image, and the listing names what that
+// image carries. This endpoint returns declarations and set/unset status only.
+//
+// h may be nil in environments built without the dependency wired; a no-op
+// registration is preferable to a startup crash, as with the invitation inbox.
+func RegisterMyEnvVarRoutes(r *gin.RouterGroup, h *handler.MeEnvVarHandler) {
+ if h == nil {
+ return
+ }
+ me := r.Group("/me/env-vars")
+ {
+ me.GET("", h.List)
+ me.PUT("/skill", h.SetSkill)
+ me.DELETE("/skill", h.DeleteSkill)
+ me.PUT("/sandbox", h.SetSandbox)
+ me.DELETE("/sandbox", h.DeleteSandbox)
+ }
+}
+
// RegisterAuthRoutes registers authentication routes
func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler, g *rbacGuards) {
r.POST("/auth/register", handler.Register)
diff --git a/internal/sandbox/skill_paths.go b/internal/sandbox/skill_paths.go
index eeec273ab..837a6ebf4 100644
--- a/internal/sandbox/skill_paths.go
+++ b/internal/sandbox/skill_paths.go
@@ -49,6 +49,23 @@ func SkillDirFor(skillName string) (string, error) {
return path.Join(SkillsImageRoot, skillName), nil
}
+// SkillRequirementsPath is where the installer agent writes what the skill
+// needs at run time. It lives inside the skill's own directory so it travels
+// with the skill into the snapshot, and it is a file rather than a tool call
+// on purpose: the agent reads a third-party SKILL.md, so nothing it produces
+// may reach the database except as bytes the server parses and validates.
+//
+// An invalid skill name yields an empty path, which every caller treats as
+// "no declaration": the name is already validated before an install starts,
+// and a best-effort read is not a place to fail an install.
+func SkillRequirementsPath(skillName string) string {
+ dir, err := SkillDirFor(skillName)
+ if err != nil {
+ return ""
+ }
+ return path.Join(dir, ".weknora", "requirements.json")
+}
+
// SkillDirForImageScript returns the owning skill directory for an image script.
// It anchors on SkillsImageRoot so nested script layouts still use the venv that
// was installed beside the skill, not a shallower scripts directory.
diff --git a/internal/types/tenant_env_vars.go b/internal/types/tenant_env_vars.go
new file mode 100644
index 000000000..b9883a0e1
--- /dev/null
+++ b/internal/types/tenant_env_vars.go
@@ -0,0 +1,196 @@
+package types
+
+import (
+ "database/sql/driver"
+ "encoding/json"
+ "errors"
+ "log"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/utils"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+// ErrEnvVarNotFound reports that a principal has no own value stored for the
+// requested variable. Callers turn it into a 404 rather than a failure.
+var ErrEnvVarNotFound = errors.New("env var not found")
+
+// SkillEnvVar is one environment variable a skill needs, as declared by the
+// installer agent, optionally carrying the workspace-wide value an admin
+// supplied. Everything except Value stays plaintext in the column so the UI can
+// render the declaration even when SYSTEM_AES_KEY is unavailable.
+type SkillEnvVar struct {
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ Required bool `json:"required,omitempty"`
+ // Value is the workspace-wide admin value. It is AES-GCM encrypted at rest
+ // by SkillEnvVars.Value and decrypted by SkillEnvVars.Scan. json:"-" makes
+ // it unserialisable by construction: the column round-trip goes through
+ // skillEnvVarRow, so no response body can carry it by forgetting to strip
+ // it in a DTO.
+ Value string `json:"-"`
+}
+
+// skillEnvVarRow is the on-column shape of one declaration. It exists only so
+// SkillEnvVars.Value and SkillEnvVars.Scan can persist the encrypted value
+// while SkillEnvVar itself stays unserialisable.
+type skillEnvVarRow struct {
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ Required bool `json:"required,omitempty"`
+ Value string `json:"value,omitempty"`
+}
+
+// SkillEnvVars is the whole declaration list, stored as one JSON column.
+// It follows TenantSandboxConfig's driver.Valuer/sql.Scanner pattern rather
+// than GORM hooks because the encrypted field lives inside a JSON document.
+type SkillEnvVars []SkillEnvVar
+
+// Get returns the declaration for name, if the skill declares it.
+func (v SkillEnvVars) Get(name string) (SkillEnvVar, bool) {
+ for _, e := range v {
+ if e.Name == name {
+ return e, true
+ }
+ }
+ return SkillEnvVar{}, false
+}
+
+// Value implements driver.Valuer. The receiver is never mutated: the caller
+// holds plaintext, so encryption happens on a copy of the slice.
+func (v SkillEnvVars) Value() (driver.Value, error) {
+ if v == nil {
+ return nil, nil
+ }
+ rows := make([]skillEnvVarRow, len(v))
+ for i, entry := range v {
+ rows[i] = skillEnvVarRow{
+ Name: entry.Name,
+ Description: entry.Description,
+ Required: entry.Required,
+ Value: encryptEnvValue(entry.Value),
+ }
+ }
+ return json.Marshal(rows)
+}
+
+// Scan implements sql.Scanner. A value that cannot be decrypted (missing or
+// rotated SYSTEM_AES_KEY) is reported as unset rather than failing the load,
+// matching TenantSandboxConfig.Scan: the skill must stay listable and editable
+// even when its stored credential became unreadable.
+func (v *SkillEnvVars) Scan(value interface{}) error {
+ if value == nil {
+ return nil
+ }
+ var b []byte
+ switch raw := value.(type) {
+ case []byte:
+ b = raw
+ case string:
+ b = []byte(raw)
+ default:
+ return nil
+ }
+ if len(b) == 0 {
+ return nil
+ }
+ var rows []skillEnvVarRow
+ if err := json.Unmarshal(b, &rows); err != nil {
+ return err
+ }
+ if rows == nil {
+ *v = nil
+ return nil
+ }
+ out := make(SkillEnvVars, len(rows))
+ for i, row := range rows {
+ out[i] = SkillEnvVar{
+ Name: row.Name,
+ Description: row.Description,
+ Required: row.Required,
+ Value: decryptEnvValue("skill_env_vars", row.Name, row.Value),
+ }
+ }
+ *v = out
+ return nil
+}
+
+// TenantUserEnvVar is one principal's own environment variable.
+//
+// An empty SkillID means the variable belongs to the whole sandbox config and
+// is injected into every execution on it. A non-empty SkillID scopes it to that
+// skill's declaration, injected only when a tool names the skill. The storage is
+// the same either way; only the load timing differs.
+//
+// It is keyed by principal rather than user id because the IM path puts a
+// synthetic "system-<tenantID>" account in the user id, which would make every
+// IM user of a workspace share a single credential.
+type TenantUserEnvVar struct {
+ ID string `gorm:"type:varchar(36);primaryKey"`
+ TenantID uint64 `gorm:"uniqueIndex:uq_user_env_var,priority:1;index:idx_user_env_var_skill,priority:1;index:idx_user_env_var_config,priority:1"`
+
+ PrincipalType string `gorm:"type:varchar(32);not null;uniqueIndex:uq_user_env_var,priority:2"`
+ PrincipalID string `gorm:"type:varchar(512);not null;uniqueIndex:uq_user_env_var,priority:3"`
+
+ SandboxConfigID string `gorm:"type:varchar(36);not null;uniqueIndex:uq_user_env_var,priority:4;index:idx_user_env_var_config,priority:2"`
+ SkillID string `gorm:"type:varchar(36);not null;uniqueIndex:uq_user_env_var,priority:5;index:idx_user_env_var_skill,priority:2"`
+ Name string `gorm:"type:varchar(255);not null;uniqueIndex:uq_user_env_var,priority:6"`
+
+ // Value is AES-GCM encrypted at rest by BeforeSave and decrypted by
+ // AfterFind. json:"-" makes it unserialisable by construction, so no
+ // endpoint can leak it by forgetting to strip it.
+ Value string `json:"-" gorm:"type:text"`
+
+ CreatedAt time.Time
+ UpdatedAt time.Time
+}
+
+// TableName pins the table so GORM's pluralizer cannot drift.
+func (TenantUserEnvVar) TableName() string { return "tenant_user_env_vars" }
+
+func (e *TenantUserEnvVar) BeforeCreate(tx *gorm.DB) error {
+ if e.ID == "" {
+ e.ID = uuid.New().String()
+ }
+ e.Value = encryptEnvValue(e.Value)
+ return nil
+}
+
+func (e *TenantUserEnvVar) BeforeSave(tx *gorm.DB) error {
+ e.Value = encryptEnvValue(e.Value)
+ return nil
+}
+
+func (e *TenantUserEnvVar) AfterFind(tx *gorm.DB) error {
+ e.Value = decryptEnvValue("tenant_user_env_vars", e.Name, e.Value)
+ return nil
+}
+
+// encryptEnvValue returns the ciphertext, or the input unchanged when there is
+// no key to encrypt with.
+func encryptEnvValue(value string) string {
+ key := utils.GetAESKey()
+ if key == nil || value == "" {
+ return value
+ }
+ if encrypted, err := utils.EncryptAESGCM(value, key); err == nil {
+ return encrypted
+ }
+ return value
+}
+
+// decryptEnvValue reports an unreadable secret as unset rather than failing the
+// load, so a row whose key was rotated away stays listable and the member can
+// see they have to enter it again.
+func decryptEnvValue(table, name, stored string) string {
+ if stored == "" {
+ return ""
+ }
+ if plain, ok := utils.DecryptStoredSecretLenient(stored); ok {
+ return plain
+ }
+ log.Printf("[crypto] %s.%s: decrypt failed "+
+ "(SYSTEM_AES_KEY missing/rotated?), treating as unset", table, name)
+ return ""
+}
diff --git a/internal/types/tenant_env_vars_test.go b/internal/types/tenant_env_vars_test.go
new file mode 100644
index 000000000..f3329634d
--- /dev/null
+++ b/internal/types/tenant_env_vars_test.go
@@ -0,0 +1,161 @@
+package types
+
+import (
+ "bytes"
+ "encoding/json"
+ "log"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/utils"
+ "github.com/stretchr/testify/require"
+)
+
+// skillEnvAESKey is exactly 32 bytes, the only length GetAESKey accepts.
+const skillEnvAESKey = "0123456789abcdef0123456789abcdef"
+
+func TestSkillEnvVarsValueEncryptsOnlyTheValue(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", skillEnvAESKey)
+
+ vars := SkillEnvVars{{
+ Name: "TAVILY_API_KEY",
+ Description: "Tavily search key",
+ Required: true,
+ Value: "tvly-super-secret",
+ }}
+
+ stored, err := vars.Value()
+ require.NoError(t, err)
+ raw, ok := stored.([]byte)
+ require.True(t, ok, "Value must marshal to JSON bytes for a jsonb column")
+
+ require.NotContains(t, string(raw), "tvly-super-secret",
+ "the plaintext secret must never reach the column")
+
+ var decoded []map[string]any
+ require.NoError(t, json.Unmarshal(raw, &decoded))
+ require.Len(t, decoded, 1)
+ require.Equal(t, "TAVILY_API_KEY", decoded[0]["name"],
+ "the name stays plaintext so the UI can render it without a key")
+ require.Equal(t, "Tavily search key", decoded[0]["description"])
+ require.Equal(t, true, decoded[0]["required"])
+ require.True(t, strings.HasPrefix(decoded[0]["value"].(string), utils.EncPrefix),
+ "only the value is encrypted")
+
+ require.Equal(t, "tvly-super-secret", vars[0].Value,
+ "the receiver holds the caller's plaintext; encryption must happen on a copy")
+}
+
+func TestSkillEnvVarsValueScanRoundTrip(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", skillEnvAESKey)
+
+ vars := SkillEnvVars{
+ {Name: "WITH_VALUE", Description: "has an admin value", Required: true, Value: "secret-1"},
+ {Name: "UNSET", Description: "user supplies it"},
+ }
+
+ stored, err := vars.Value()
+ require.NoError(t, err)
+
+ var got SkillEnvVars
+ require.NoError(t, got.Scan(stored))
+ require.Len(t, got, 2)
+ require.Equal(t, "WITH_VALUE", got[0].Name)
+ require.True(t, got[0].Required)
+ require.Equal(t, "secret-1", got[0].Value, "a stored value reads back as plaintext")
+ require.Equal(t, "UNSET", got[1].Name)
+ require.Empty(t, got[1].Value, "an empty value stays empty rather than becoming ciphertext")
+}
+
+func TestSkillEnvVarsScanKeepsDeclarationWhenValueUndecryptable(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", skillEnvAESKey)
+ var logs bytes.Buffer
+ previousLogOutput := log.Writer()
+ log.SetOutput(&logs)
+ t.Cleanup(func() { log.SetOutput(previousLogOutput) })
+
+ // Ciphertext that cannot be opened, as after a key rotation.
+ stored := []byte(`[{"name":"TAVILY_API_KEY","description":"key","required":true,` +
+ `"value":"` + utils.EncPrefix + `not-real-ciphertext"}]`)
+
+ var got SkillEnvVars
+ require.NoError(t, got.Scan(stored),
+ "an unreadable secret must not fail the whole row load")
+ require.Len(t, got, 1)
+ require.Equal(t, "TAVILY_API_KEY", got[0].Name, "the declaration survives")
+ require.True(t, got[0].Required)
+ require.Empty(t, got[0].Value, "an unreadable value reports as unset, never as ciphertext")
+ require.Contains(t, logs.String(), "[crypto] skill_env_vars.TAVILY_API_KEY: decrypt failed",
+ "the unreadable value must be visible to operators")
+}
+
+func TestSkillEnvVarsScanAcceptsNilAndEmpty(t *testing.T) {
+ var fromNil SkillEnvVars
+ require.NoError(t, fromNil.Scan(nil))
+ require.Empty(t, fromNil)
+
+ var fromEmpty SkillEnvVars
+ require.NoError(t, fromEmpty.Scan([]byte("")))
+ require.Empty(t, fromEmpty)
+}
+
+func TestSkillEnvVarsGet(t *testing.T) {
+ vars := SkillEnvVars{
+ {Name: "A", Value: "a"},
+ {Name: "B", Required: true},
+ }
+
+ got, ok := vars.Get("B")
+ require.True(t, ok)
+ require.True(t, got.Required)
+
+ _, ok = vars.Get("MISSING")
+ require.False(t, ok)
+}
+
+// The declaration type must be unserialisable in its own right: today every
+// handler projects through a DTO that reports only is_set, and this is what
+// makes a future forgotten DTO drop the credential instead of leaking it.
+func TestSkillEnvVarsNeverSerialiseTheirValues(t *testing.T) {
+ vars := SkillEnvVars{{Name: "TAVILY_API_KEY", Required: true, Value: "tvly-super-secret"}}
+
+ raw, err := json.Marshal(vars)
+ require.NoError(t, err)
+ require.NotContains(t, string(raw), "tvly-super-secret",
+ "marshalling a declaration must never emit the admin value")
+ require.Contains(t, string(raw), "TAVILY_API_KEY")
+
+ entity, err := json.Marshal(&TenantSkillEntity{ID: "skill-1", Name: "web-search", Envs: vars})
+ require.NoError(t, err)
+ require.NotContains(t, string(entity), "tvly-super-secret",
+ "marshalling the skill row must never emit the admin value either")
+ require.Contains(t, string(entity), "TAVILY_API_KEY")
+}
+
+func TestTenantUserEnvVarNeverSerialisesItsValue(t *testing.T) {
+ raw, err := json.Marshal(&TenantUserEnvVar{
+ ID: "env-1", TenantID: 7, Name: "TAVILY_API_KEY", Value: "secret",
+ })
+ require.NoError(t, err)
+ require.NotContains(t, string(raw), "secret",
+ "the type itself must be unserialisable, so no handler has to remember to strip it")
+ require.Contains(t, string(raw), "TAVILY_API_KEY")
+}
+
+func TestTenantUserEnvVarAfterFindTreatsUndecryptableValueAsUnset(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", skillEnvAESKey)
+ var logs bytes.Buffer
+ previousLogOutput := log.Writer()
+ log.SetOutput(&logs)
+ t.Cleanup(func() { log.SetOutput(previousLogOutput) })
+ row := &TenantUserEnvVar{
+ Name: "TAVILY_API_KEY",
+ Value: utils.EncPrefix + "not-real-ciphertext",
+ }
+
+ require.NoError(t, row.AfterFind(nil),
+ "an unreadable secret must not fail the whole row load")
+ require.Empty(t, row.Value, "an unreadable value reports as unset, never as ciphertext")
+ require.Contains(t, logs.String(), "[crypto] tenant_user_env_vars.TAVILY_API_KEY: decrypt failed",
+ "the unreadable value must be visible to operators")
+}
diff --git a/internal/types/tenant_skill.go b/internal/types/tenant_skill.go
index 6eebf27f6..d308e9ba7 100644
--- a/internal/types/tenant_skill.go
+++ b/internal/types/tenant_skill.go
@@ -79,6 +79,10 @@ type TenantSkillEntity struct {
InstallSessionID string `gorm:"type:varchar(36)"`
InstallMessageID string `gorm:"type:varchar(36)"`
+ // Envs is the installer agent's declaration of the environment variables
+ // this skill needs, each optionally carrying a workspace-wide admin value.
+ Envs SkillEnvVars `json:"envs,omitempty" gorm:"type:jsonb"`
+
Status string `gorm:"type:varchar(32);not null"`
Error string `gorm:"type:text"`
// InstallingSince drives the stuck-run reaper for both install and remove.
diff --git a/migrations/versioned/000089_env_vars.down.sql b/migrations/versioned/000089_env_vars.down.sql
new file mode 100644
index 000000000..3b152089f
--- /dev/null
+++ b/migrations/versioned/000089_env_vars.down.sql
@@ -0,0 +1,4 @@
+DO $$ BEGIN RAISE NOTICE '[Migration 000088 down] Dropping env vars'; END $$;
+
+DROP TABLE IF EXISTS tenant_user_env_vars;
+ALTER TABLE tenant_skills DROP COLUMN IF EXISTS envs;
diff --git a/migrations/versioned/000089_env_vars.up.sql b/migrations/versioned/000089_env_vars.up.sql
new file mode 100644
index 000000000..2213f0e9b
--- /dev/null
+++ b/migrations/versioned/000089_env_vars.up.sql
@@ -0,0 +1,49 @@
+-- Description: Environment variables for skill execution. Two things live here:
+-- the per-skill declaration an installer agent produces (with the optional
+-- workspace-wide value an admin supplies), and the values individual members
+-- keep for themselves.
+--
+-- A member value with an empty skill_id belongs to the whole sandbox config and
+-- is injected into every execution on it; one with a skill_id is that skill's
+-- declared credential, injected only when a tool names the skill. The storage is
+-- shared because it is the same kind of thing — only the load timing differs.
+DO $$ BEGIN RAISE NOTICE '[Migration 000088] Adding tenant_skills.envs'; END $$;
+
+ALTER TABLE tenant_skills ADD COLUMN IF NOT EXISTS envs JSONB;
+
+COMMENT ON COLUMN tenant_skills.envs IS
+ 'Installer-agent declaration [{name,description,required,value}]. value is the workspace-wide admin value and is AES-GCM encrypted; the rest is plaintext so the UI can render it without a key.';
+
+DO $$ BEGIN RAISE NOTICE '[Migration 000088] Creating tenant_user_env_vars'; END $$;
+
+CREATE TABLE IF NOT EXISTS tenant_user_env_vars (
+ id VARCHAR(36) PRIMARY KEY,
+ tenant_id BIGINT NOT NULL,
+ principal_type VARCHAR(32) NOT NULL,
+ principal_id VARCHAR(512) NOT NULL,
+ sandbox_config_id VARCHAR(36) NOT NULL,
+ skill_id VARCHAR(36) NOT NULL DEFAULT '',
+ name VARCHAR(255) NOT NULL,
+ value TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+COMMENT ON TABLE tenant_user_env_vars IS
+ 'One principal''s own environment variable. An empty skill_id applies to every execution on the sandbox config; a skill_id scopes it to that skill''s declaration. Keyed by principal, not user_id: the IM path stores a synthetic tenant account in the user ID, which would make every IM user of a workspace share one value.';
+COMMENT ON COLUMN tenant_user_env_vars.value IS 'AES-GCM encrypted. Never returned by any endpoint.';
+
+-- Also the read index for resolution: its leftmost prefix is the exact tuple
+-- looked up on every execution. sandbox_config_id is part of the key because
+-- without it two configs could not each hold a config-wide variable of the
+-- same name (their skill_id is empty in both).
+CREATE UNIQUE INDEX IF NOT EXISTS uq_user_env_var
+ ON tenant_user_env_vars (tenant_id, principal_type, principal_id, sandbox_config_id, skill_id, name);
+
+-- Cleanup indexes. Skills and sandbox configs are soft-deleted, so a foreign
+-- key with ON DELETE CASCADE would never fire; deletion is explicit in the
+-- repository and needs these to stay cheap.
+CREATE INDEX IF NOT EXISTS idx_user_env_var_skill
+ ON tenant_user_env_vars (tenant_id, skill_id);
+CREATE INDEX IF NOT EXISTS idx_user_env_var_config
+ ON tenant_user_env_vars (tenant_id, sandbox_config_id);