Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,49 @@ jobs:
fi
exit 1

- name: 🧪 Execute smoke check (production)
shell: bash
env:
DEPLOY_URL: ${{ steps.deploy.outputs.url }}
CAPABILITY_REINDEX_SECRET: ${{ secrets.CAPABILITY_REINDEX_SECRET }}
run: |
set -euo pipefail
if [ -z "${CAPABILITY_REINDEX_SECRET:-}" ]; then
echo "Skipping execute smoke check (CAPABILITY_REINDEX_SECRET not set)."
exit 0
fi
if [ -z "${DEPLOY_URL:-}" ]; then
echo "Missing deploy URL output; cannot run execute smoke check." >&2
exit 1
fi

base="${DEPLOY_URL%/}"
smoke_url="${base}/__maintenance/execute-smoke"
echo "POST ${smoke_url}"

attempts=10
delay_seconds=3
for i in $(seq 1 "$attempts"); do
echo "Attempt $i/$attempts"
status="$(curl --silent --show-error --location --max-time 30 \
-X POST \
-H "Authorization: Bearer ${CAPABILITY_REINDEX_SECRET}" \
-H "Accept: application/json" \
--output execute-smoke.json \
--write-out "%{http_code}" \
"${smoke_url}")"
cat execute-smoke.json
echo
if [ "$status" -ge 200 ] && [ "$status" -lt 300 ] && \
node -e "const fs = require('node:fs'); const json = JSON.parse(fs.readFileSync('execute-smoke.json','utf8')); if (json?.ok !== true || json?.result !== 42) { console.error('execute-smoke-unexpected-response', json); process.exit(1); } console.log('execute-smoke-ok', json);"; then
exit 0
fi
sleep "$delay_seconds"
done
Comment on lines +274 to +292

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the workflow and inspect the surrounding lines.
git ls-files .github/workflows/deploy.yml
wc -l .github/workflows/deploy.yml
sed -n '240,310p' .github/workflows/deploy.yml

# Probe shell semantics relevant to: status="$(cmd)" under set -e.
python3 - <<'PY'
import subprocess, textwrap, tempfile, os, json, pathlib

cases = {
    "bare_assignment_success": r'''
set -e
status="$(python3 - <<'PY2'
import sys
print("ok")
sys.exit(0)
PY2
)"
echo "reached:$status"
''',
    "bare_assignment_failure": r'''
set -e
status="$(python3 - <<'PY2'
import sys
print("partial", end="")
sys.exit(1)
PY2
)"
echo "reached:$status"
''',
    "if_assignment_failure": r'''
set -e
if status="$(python3 - <<'PY2'
import sys
print("partial", end="")
sys.exit(1)
PY2
)"; then
  echo ok
fi
echo "reached:$status"
''',
}

for name, script in cases.items():
    p = subprocess.run(["bash", "-lc", script], capture_output=True, text=True)
    print(f"## {name}")
    print("exit", p.returncode)
    print("stdout:", repr(p.stdout))
    print("stderr:", repr(p.stderr))
PY

Repository: kentcdodds/kody

Length of output: 3921


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Read the specific workflow step for exact context.
nl -ba .github/workflows/deploy.yml | sed -n '268,294p'

# Check shell behavior in a way that mirrors the workflow structure.
python3 - <<'PY'
import subprocess, textwrap

scripts = {
    "bare_assignment_success": r'''set -e
status="$(python3 - <<'PY2'
print("ok")
PY2
)"
echo "reached:$status"
''',
    "bare_assignment_failure": r'''set -e
status="$(python3 - <<'PY2'
import sys
print("partial", end="")
sys.exit(1)
PY2
)"
echo "reached:$status"
''',
    "conditional_assignment_failure": r'''set -e
if status="$(python3 - <<'PY2'
import sys
print("partial", end="")
sys.exit(1)
PY2
)"; then
  echo ok
fi
echo "reached:$status"
''',
}

for name, script in scripts.items():
    p = subprocess.run(["bash", "-lc", script], capture_output=True, text=True)
    print(f"## {name}")
    print("exit", p.returncode)
    print("stdout:", repr(p.stdout))
    print("stderr:", repr(p.stderr))
PY

Repository: kentcdodds/kody

Length of output: 193


Retry loop can exit on the first curl failure. status="$(curl ...)" runs under set -euo pipefail, so a transient connection/timeout error aborts the step before any retry happens. Wrap it so curl failures become a retryable status instead of ending the step immediately.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/deploy.yml around lines 274 - 292, The retry loop in the
smoke test step can terminate immediately because the curl invocation inside the
status assignment is still subject to set -euo pipefail. Update the retry logic
around the curl call in the deploy workflow so a curl error/timeout is captured
as a nonzero status and the loop continues retrying, while preserving the
existing response validation with the node check and the execute-smoke.json
output handling.


echo "Execute smoke check failed after ${attempts} attempts: ${smoke_url}" >&2
exit 1

- name: 🧭 Reindex capability vectors (Vectorize)
shell: bash
env:
Expand Down
80 changes: 80 additions & 0 deletions packages/worker/src/execute-maintenance.node.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { expect, test, vi } from 'vitest'

const createExecuteExecutorMock = vi.hoisted(() => vi.fn())

vi.mock('cloudflare:workers', () => ({
exports: {
KodyFetchGateway: () => ({}),
},
}))

vi.mock('#mcp/executor.ts', () => ({
createExecuteExecutor: (...args: Array<unknown>) =>
createExecuteExecutorMock(...args),
}))

const { handleExecuteSmokeRequest, runExecuteSmokeCheck } =
await import('./execute-maintenance.ts')

test('runExecuteSmokeCheck executes trivial code through the dynamic worker path', async () => {
const execute = vi.fn(async () => ({ result: 42, logs: [] }))
createExecuteExecutorMock.mockReturnValue({ execute })

const env = {
APP_BASE_URL: 'https://example.com',
LOADER: {},
} as Env

await expect(runExecuteSmokeCheck(env)).resolves.toEqual({ result: 42 })
expect(createExecuteExecutorMock).toHaveBeenCalledWith(
expect.objectContaining({
timeoutMs: 10_000,
gatewayProps: {
baseUrl: 'https://example.com',
userId: null,
storageContext: null,
},
}),
)
expect(execute).toHaveBeenCalledWith('async () => 42', [
{
name: 'kody',
fns: {},
kodyRemoteConnectors: [],
},
])
})

test('handleExecuteSmokeRequest enforces auth and reports smoke results', async () => {
const execute = vi.fn(async () => ({ result: 42, logs: [] }))
createExecuteExecutorMock.mockReturnValue({ execute })

const env = {
CAPABILITY_REINDEX_SECRET: 'secret',
APP_BASE_URL: 'https://example.com',
LOADER: {},
} as Env

const unauthorized = await handleExecuteSmokeRequest(
new Request('https://example.com/__maintenance/execute-smoke', {
method: 'POST',
}),
env,
)
expect(unauthorized.status).toBe(401)

const success = await handleExecuteSmokeRequest(
new Request('https://example.com/__maintenance/execute-smoke', {
method: 'POST',
headers: {
Authorization: 'Bearer secret',
},
}),
env,
)
expect(success.status).toBe(200)
await expect(success.json()).resolves.toEqual({
ok: true,
result: 42,
})
})
60 changes: 60 additions & 0 deletions packages/worker/src/execute-maintenance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { exports as workerExports } from 'cloudflare:workers'
import { createExecuteExecutor } from '#mcp/executor.ts'
import { handleSecretMaintenanceRequest } from './maintenance-handler.ts'
import { getErrorMessage } from '#mcp/capabilities/error-message.ts'

const executeSmokeCode = 'async () => 42'
const executeSmokeProviders = [
{
name: 'kody',
fns: {},
kodyRemoteConnectors: [],
},
] as const
Comment on lines +6 to +13

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n "ResolvedProvider" packages/worker/src/mcp/executor.ts -B2 -A8
rg -n "KodyRemoteConnectorMetadata" packages/worker/src/mcp/executor.ts -B2 -A8

Repository: kentcdodds/kody

Length of output: 4898


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== execute-maintenance.ts =="
wc -l packages/worker/src/execute-maintenance.ts
cat -n packages/worker/src/execute-maintenance.ts | sed -n '1,220p'

echo
echo "== kody-remote-types.ts =="
wc -l packages/worker/src/mcp/kody-remote-types.ts
cat -n packages/worker/src/mcp/kody-remote-types.ts | sed -n '1,220p'

echo
echo "== executor.ts relevant section =="
cat -n packages/worker/src/mcp/executor.ts | sed -n '390,460p'

Repository: kentcdodds/kody

Length of output: 6943


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
p = Path('packages/worker/src/execute-maintenance.ts')
text = p.read_text()
for i, line in enumerate(text.splitlines(), 1):
    if 'executeSmoke' in line or 'getErrorMessage' in line or 'createKodyProviderProxySource' in line or 'providers:' in line or 'result.result' in line:
        start = max(1, i-8)
        end = min(len(text.splitlines()), i+16)
        print(f"\n--- around line {i} ---")
        for j in range(start, end+1):
            print(f"{j}:{text.splitlines()[j-1]}")
PY

Repository: kentcdodds/kody

Length of output: 5995


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
for path in [
    Path('packages/worker/src/execute-maintenance.ts'),
    Path('packages/worker/src/mcp/kody-remote-types.ts'),
    Path('packages/worker/src/mcp/executor.ts'),
]:
    print(f"\n## {path} ##")
    lines = path.read_text().splitlines()
    for i, line in enumerate(lines, 1):
        if 'executeSmoke' in line or 'getErrorMessage' in line or 'createKodyProviderProxySource' in line or 'KodyResolvedProvider' in line or 'kodyRemoteConnectors' in line or 'ResolvedProvider' in line:
            start = max(1, i-6)
            end = min(len(lines), i+14)
            print(f"\n-- around line {i} --")
            for j in range(start, end+1):
                print(f"{j}:{lines[j-1]}")
PY

Repository: kentcdodds/kody

Length of output: 19496


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path

files = [
    'packages/worker/src/execute-maintenance.ts',
    'packages/worker/src/mcp/kody-remote-types.ts',
    'packages/worker/src/mcp/executor.ts',
]
for file in files:
    print(f"\n## {file}")
    lines = Path(file).read_text().splitlines()
    for idx, line in enumerate(lines, 1):
        if any(tok in line for tok in ['executeSmoke', 'getErrorMessage', 'createKodyProviderProxySource', 'KodyResolvedProvider', 'kodyRemoteConnectors', 'ResolvedProvider']):
            start = max(1, idx - 6)
            end = min(len(lines), idx + 14)
            print(f"\n-- around line {idx} --")
            for j in range(start, end + 1):
                print(f"{j}:{lines[j-1]}")
PY

Repository: kentcdodds/kody

Length of output: 19487


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== execute-maintenance.ts =="
cat -n packages/worker/src/execute-maintenance.ts | sed -n '1,220p'

Repository: kentcdodds/kody

Length of output: 2229


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== getErrorMessage helper =="
fd -a "error-message.ts" packages/worker/src
if [ -f packages/worker/src/mcp/capabilities/error-message.ts ]; then
  wc -l packages/worker/src/mcp/capabilities/error-message.ts
  cat -n packages/worker/src/mcp/capabilities/error-message.ts | sed -n '1,200p'
fi

echo
echo "== TypeScript tool availability =="
command -v tsc || true
node -e "try { const ts = require('typescript'); console.log('typescript module:', ts.version); } catch (e) { console.log('typescript module unavailable') }"

echo
echo "== assignability probe =="
tmpdir="$(mktemp -d)"
cat > "$tmpdir/probe.ts" <<'TS'
type KodyRemoteConnectorMetadata = {
  name: string
}
type ResolvedProvider = {
  name: string
  fns: Record<string, unknown>
  kodyRemoteConnectors?: Array<KodyRemoteConnectorMetadata>
}

const providers = [
  {
    name: 'kody',
    fns: {},
    kodyRemoteConnectors: [],
  },
] as const

const x: Array<ResolvedProvider> = [...providers]
TS

if command -v tsc >/dev/null 2>&1; then
  tsc --noEmit --strict "$tmpdir/probe.ts" 2>&1 || true
else
  echo "tsc not available"
fi
rm -rf "$tmpdir"

Repository: kentcdodds/kody

Length of output: 1732


🏁 Script executed:

#!/bin/bash
set -euo pipefail

tmpdir="$(mktemp -d)"
cat > "$tmpdir/probe.ts" <<'TS'
type KodyRemoteConnectorMetadata = {
  name: string
}
type ResolvedProvider = {
  name: string
  fns: Record<string, unknown>
  kodyRemoteConnectors?: Array<KodyRemoteConnectorMetadata>
}

const executeSmokeProviders = [
  {
    name: 'kody',
    fns: {},
    kodyRemoteConnectors: [],
  },
] as const

const providersA: Array<ResolvedProvider> = [...executeSmokeProviders]
const providersB: Array<ResolvedProvider> = executeSmokeProviders

declare const p: ResolvedProvider
const connectorsA: Array<KodyRemoteConnectorMetadata> = p.kodyRemoteConnectors!
const connectorsB: Array<KodyRemoteConnectorMetadata> = executeSmokeProviders[0].kodyRemoteConnectors
TS

tsc --noEmit --strict --ignoreConfig "$tmpdir/probe.ts" 2>&1 || true
rm -rf "$tmpdir"

Repository: kentcdodds/kody

Length of output: 951


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== assignability probe =="
tmpdir="$(mktemp -d)"
cat > "$tmpdir/probe.ts" <<'TS'
type KodyRemoteConnectorMetadata = {
  name: string
}
type ResolvedProvider = {
  name: string
  fns: Record<string, unknown>
  kodyRemoteConnectors?: Array<KodyRemoteConnectorMetadata>
}

const executeSmokeProviders = [
  {
    name: 'kody',
    fns: {},
    kodyRemoteConnectors: [],
  },
] as const

const providersA: Array<ResolvedProvider> = [...executeSmokeProviders]
const providersB: Array<ResolvedProvider> = executeSmokeProviders

declare const p: ResolvedProvider
const connectorsA: Array<KodyRemoteConnectorMetadata> = p.kodyRemoteConnectors!
const connectorsB: Array<KodyRemoteConnectorMetadata> = executeSmokeProviders[0].kodyRemoteConnectors
TS

tsc --noEmit --strict --ignoreConfig "$tmpdir/probe.ts" 2>&1 || true
rm -rf "$tmpdir"

echo
echo "== ExecuteResult / getErrorMessage context =="
rg -n "type ExecuteResult|interface ExecuteResult|getErrorMessage\\(" packages/worker/src -B2 -A6

Repository: kentcdodds/kody

Length of output: 24337


Drop as const from this fixture packages/worker/src/execute-maintenance.ts:7-13 — kodyRemoteConnectors is inferred as readonly [], which isn’t assignable to ResolvedProvider.kodyRemoteConnectors: Array<KodyRemoteConnectorMetadata>. The outer spread doesn’t remove the nested readonly type; use a mutable fixture instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/worker/src/execute-maintenance.ts` around lines 6 - 13, The
executeSmokeProviders fixture uses as const, which makes kodyRemoteConnectors
infer as a readonly empty array and breaks assignment to
ResolvedProvider.kodyRemoteConnectors. Remove the as const from
executeSmokeProviders in execute-maintenance.ts and keep the fixture mutable so
the nested kodyRemoteConnectors field is inferred as a normal
Array<KodyRemoteConnectorMetadata>.


export async function runExecuteSmokeCheck(env: Env) {
if (!env.LOADER) {
throw new Error('Execute smoke check requires the LOADER binding.')
}
if (!workerExports?.KodyFetchGateway) {
throw new Error(
'Execute smoke check requires the KodyFetchGateway worker export.',
)
}

const origin = env.APP_BASE_URL?.trim() || 'https://heykody.dev'
const executor = createExecuteExecutor({
env,
exports: workerExports,
gatewayProps: {
baseUrl: origin,
userId: null,
storageContext: null,
},
timeoutMs: 10_000,
})
const result = await executor.execute(executeSmokeCode, [
...executeSmokeProviders,
])
if (result.error) {
throw new Error(`Execute smoke check failed: ${result.error}`)
}
if (result.result !== 42) {
throw new Error(
`Execute smoke check returned unexpected result: ${getErrorMessage(result.result)}`,
)
}
return { result: result.result }
}

export async function handleExecuteSmokeRequest(
request: Request,
env: Env,
): Promise<Response> {
return handleSecretMaintenanceRequest({
request,
secret: env.CAPABILITY_REINDEX_SECRET,
notConfiguredMessage: 'Execute smoke check is not configured',
run: async () => await runExecuteSmokeCheck(env),
})
}
5 changes: 5 additions & 0 deletions packages/worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { isNonProductionRuntime } from '#app/deployment-env.ts'
import { checkRateLimit, authRateLimitConfig } from '#app/rate-limit.ts'
import { getRequestIp } from '#app/audit-log.ts'
import { handleCapabilityReindexRequest } from './capability-maintenance.ts'
import { handleExecuteSmokeRequest } from './execute-maintenance.ts'
import { handleJobReindexRequest } from './job-maintenance.ts'
import { handleMemoryReindexRequest } from './memory-maintenance.ts'
import { reconcileArtifactsPushes } from './jobs/reconcile-artifacts-pushes.ts'
Expand Down Expand Up @@ -211,6 +212,10 @@ const appHandler = withCors({
return handleCapabilityReindexRequest(request, env)
}

if (url.pathname === '/__maintenance/execute-smoke') {
return handleExecuteSmokeRequest(request, env)
}

if (url.pathname === '/__maintenance/reindex-memories') {
return handleMemoryReindexRequest(request, env)
}
Expand Down
31 changes: 31 additions & 0 deletions packages/worker/src/mcp/executor.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ import {
createKodyRemoteProxy,
createKodyProviderProxySource,
createExecuteExecutor,
createExecutorModuleSource,
extractRawContent,
formatExecutionOutput,
formatLimitedExecutionOutput,
getExecutionErrorDetails,
limitExecutionResultValue,
} from './executor.ts'
import { assertGeneratedExecutorSourceIsBundleSafe } from './kody-remote-proxy-source.ts'

type FakeWorkerOptions = Record<string, unknown>

Expand Down Expand Up @@ -152,6 +154,35 @@ test('kody remote proxy dispatches and reports connector/capability errors clear
)
})

test('generated kody provider source avoids bundle-scoped __name helpers', () => {
const source = createKodyProviderProxySource({
providerName: 'kody',
remoteConnectors: [],
})
expect(source).not.toMatch(/\b__name\b/u)
assertGeneratedExecutorSourceIsBundleSafe(source)

const bundledFactorySource = `const __kodyCreateRemoteProxy = __name(function createKodyRemoteProxy() { return {}; }, "createKodyRemoteProxy");`
expect(bundledFactorySource).toMatch(/\b__name\b/u)
expect(() => new Function('__dispatchers', bundledFactorySource)({})).toThrow(
/__name is not defined/u,
)

const moduleSource = createExecutorModuleSource({
code: 'async () => "ok"',
providers: [
{
name: 'kody',
fns: {},
kodyRemoteConnectors: [],
},
],
shadowGlobalThis: false,
timeoutMs: 1_000,
})
assertGeneratedExecutorSourceIsBundleSafe(moduleSource)
})

test('generated kody provider source wires remote proxy dispatch', async () => {
const calls: Array<{ name: string; argsJson: string }> = []
const source = createKodyProviderProxySource({
Expand Down
17 changes: 16 additions & 1 deletion packages/worker/src/mcp/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ import {
type KodyRemoteConnectorMetadata,
type KodyResolvedProvider,
} from '#mcp/kody-remote-types.ts'
import {
assertGeneratedExecutorSourceIsBundleSafe,
kodyRemoteProxyFactorySource,
} from '#mcp/kody-remote-proxy-source.ts'

type WorkerLoopbackExports = Exclude<typeof workerExports, undefined>

Expand Down Expand Up @@ -383,6 +387,15 @@ function createExecutorModule(input: {
].join('\n')
}

export function createExecutorModuleSource(input: {
code: string
providers: Array<ResolvedProvider>
shadowGlobalThis: boolean
timeoutMs: number
}) {
return createExecutorModule(input)
}

function createProviderProxySource(provider: ResolvedProvider) {
const kodyProvider = provider as KodyResolvedProvider
if (provider.name === 'kody' && kodyProvider.kodyRemoteConnectors) {
Expand All @@ -401,7 +414,7 @@ export function createKodyProviderProxySource(input: {
remoteConnectors: Array<KodyRemoteConnectorMetadata>
}) {
const metadataJson = JSON.stringify(input.remoteConnectors)
return ` const __kodyCreateRemoteProxy = ${createKodyRemoteProxy.toString()};
const source = ` const __kodyCreateRemoteProxy = ${kodyRemoteProxyFactorySource};
const __kodyRemote = __kodyCreateRemoteProxy({
remoteConnectors: ${metadataJson},
callTool: async (dispatchName, args) => {
Expand All @@ -427,6 +440,8 @@ export function createKodyProviderProxySource(input: {
};
}
});`
assertGeneratedExecutorSourceIsBundleSafe(source)
return source
}

function createToolDispatchers(
Expand Down
81 changes: 81 additions & 0 deletions packages/worker/src/mcp/kody-remote-proxy-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Static factory source for dynamic execute modules. Do not serialize bundled
// functions with Function.prototype.toString() here — production wrangler/esbuild
// can rewrite named functions to use a bundle-scoped __name helper that does not
// exist inside dynamically loaded worker modules.
export const kodyRemoteProxyFactorySource = [
'function createKodyRemoteProxy(input) {',
' const connectors = Object.fromEntries(',
' input.remoteConnectors.map((connector) => [',
' connector.name,',
' {',
' ...connector,',
' capabilitiesByName: Object.fromEntries(',
' connector.capabilities.map((capability) => [',
' capability.name,',
' capability,',
' ]),',
' ),',
' },',
' ]),',
' );',
' const formatNames = (names) =>',
' names.length > 0',
' ? names.map((name) => JSON.stringify(name)).join(", ")',
' : "none";',
'',
' return new Proxy(',
' {},',
' {',
' get(_target, connectorName) {',
' if (typeof connectorName === "symbol" || connectorName === "then") {',
' return undefined;',
' }',
' const normalizedConnectorName = String(connectorName);',
' const connector = connectors[normalizedConnectorName];',
' if (!connector) {',
' throw new Error(',
' "Unknown remote connector \\"" + normalizedConnectorName + "\\". Available remote connectors: " + formatNames(Object.keys(connectors)) + ".",',
' );',
' }',
' return new Proxy(',
' {},',
' {',
' get(_connectorTarget, capabilityName) {',
' if (',
' typeof capabilityName === "symbol" ||',
' capabilityName === "then"',
' ) {',
' return undefined;',
' }',
' const normalizedCapabilityName = String(capabilityName);',
' if (',
' !connector.status.connected ||',
' connector.status.toolCount === 0',
' ) {',
' throw new Error(connector.status.unavailableMessage);',
' }',
' const capability =',
' connector.capabilitiesByName[normalizedCapabilityName];',
' if (!capability) {',
' throw new Error(',
' "Unknown remote capability \\"" + normalizedCapabilityName + "\\" for connector \\"" + normalizedConnectorName + "\\". Available capabilities: " + formatNames(connector.capabilities.map((entry) => entry.name)) + ".",',
' );',
' }',
' return async (args) =>',
' await input.callTool(capability.dispatchName, args);',
' },',
' },',
' );',
' },',
' },',
' );',
'}',
].join('\n')

export function assertGeneratedExecutorSourceIsBundleSafe(source: string) {
if (/\b__name\b/u.test(source)) {
throw new Error(
'Generated executor source must not reference bundle-scoped __name helpers.',
)
}
}
Comment on lines +75 to +81

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Regex can false-positive on interpolated data, not just bundler output.

This helper is invoked against fully-assembled source that includes JSON-serialized connector/capability metadata (metadataJson in executor.ts). If a remote connector or capability is ever named "__name", the whole-word check will match that data and incorrectly throw "must not reference bundle-scoped __name helpers", blocking legitimate execution even though no actual bundler artifact is present.

Real esbuild/wrangler output always uses __name as a call, e.g. __name(fn, "name"). Narrowing the pattern to require the call syntax avoids matching plain string data.

🐛 Proposed fix
 export function assertGeneratedExecutorSourceIsBundleSafe(source: string) {
-	if (/\b__name\b/u.test(source)) {
+	if (/\b__name\s*\(/u.test(source)) {
 		throw new Error(
 			'Generated executor source must not reference bundle-scoped __name helpers.',
 		)
 	}
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function assertGeneratedExecutorSourceIsBundleSafe(source: string) {
if (/\b__name\b/u.test(source)) {
throw new Error(
'Generated executor source must not reference bundle-scoped __name helpers.',
)
}
}
export function assertGeneratedExecutorSourceIsBundleSafe(source: string) {
if (/\b__name\s*\(/u.test(source)) {
throw new Error(
'Generated executor source must not reference bundle-scoped __name helpers.',
)
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/worker/src/mcp/kody-remote-proxy-source.ts` around lines 75 - 81,
The bundle-safety check in assertGeneratedExecutorSourceIsBundleSafe is too
broad because it matches plain serialized metadata as well as real bundler
output. Update the regex so it only flags actual esbuild/wrangler __name call
syntax (for example in assembled executor source from executor.ts) rather than
any whole-word "__name" string, and keep the existing error path unchanged for
true bundle-scoped helper references.

Loading