Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
17 changes: 17 additions & 0 deletions docs/guides/package-authoring.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,23 @@ This package exists to ...
Keep the section concise. It should explain why the package exists and what
success means for the user, not duplicate every implementation detail.

## Package app routing

Hosted package apps are mounted at `/@username/packages/<kody-id>/<path>`. The
app receives only `/<path>` in its fetch request. Root-relative links such as
`/audio/123` therefore escape the mount and are not routed back to the package
app.

Import `packageContext` from `kody:runtime` and build every in-app link,
redirect, share/email URL, and OAuth callback against its public base:

- `packageContext.hostedUrl` is the full public URL of the app mount.
- `packageContext.appBasePath` is the origin-relative mount path.

Kody derives both fields from the package's current serving username and
`kody.id`, including after a rename or fork. Do not hard-code either path
segment.

## `kody.description` (short public tagline)

`package.json#kody.description` is a **short public tagline**, not a feature
Expand Down
26 changes: 26 additions & 0 deletions docs/use/packages.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,32 @@ session handoff to that origin. Package author JavaScript cannot use the
first-party `kody_session` cookie or call authenticated Kody pages as the
signed-in user.

Package app URLs follow this mount contract:
`/@username/packages/<kody-id>/<path>`. Kody removes the mount before forwarding
the request, so an app sees `/<path>`. A root-relative browser URL such as
`/audio/123` escapes the mount and is not dispatched to the app. Build in-app
links, redirects, shared links, email links, and OAuth callback URLs against the
public base exposed by `packageContext`:

```ts
import { packageContext } from 'kody:runtime'

if (!packageContext?.hostedUrl) {
throw new Error('This module must run as a package app.')
}

const audioUrl = new URL(
`${packageContext.appBasePath}/audio/123`,
packageContext.hostedUrl,
)
```

For package apps, `packageContext.hostedUrl` is the full public URL of the app
mount and `packageContext.appBasePath` is its origin-relative mount path. Both
are derived from the username and `kody.id` currently serving the package, so
they remain correct after a rename or fork. Other saved-package runtime surfaces
may omit these app-specific fields.

Use the package app model when the package needs:

- interactive UI
Expand Down
2 changes: 2 additions & 0 deletions packages/worker/src/app/handlers/package-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,8 @@ export async function servePackageAppRequest(input: {
},
runtime: {
callerContext,
servingUsername: packagePath.username,
hostedOrigin: requestUrl.origin,
},
})
entrypoint = appWorker.stub.getEntrypoint(appWorker.entrypointName)
Expand Down
15 changes: 14 additions & 1 deletion packages/worker/src/app/package-app-origin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,19 @@ function createPackageAppOriginConfigurationErrorResponse(message: string) {
})
}

function createUnmatchedPackageAppPathResponse() {
return new Response(
'Package app URL not found. Package app URLs use /@username/packages/<kody-id>/<path>. Requests outside a package app mount are not dispatched to any app.',
{
status: 404,
headers: {
'Cache-Control': 'no-store',
'Content-Type': 'text/plain; charset=utf-8',
},
},
)
}

/**
* Terminal response for a package-app request with no usable package-app
* session. Deliberately not a redirect back to the app origin: only the visitor
Expand Down Expand Up @@ -211,7 +224,7 @@ async function handleRequestOnPackageAppOrigin(input: {
if (url.pathname === '/') {
return redirectResponse({ location: `${appBaseUrl}/`, status: 302 })
}
return new Response('Not Found', { status: 404 })
return createUnmatchedPackageAppPathResponse()
}

const handoffToken = url.searchParams.get(packageAppHandoffQueryParam)
Expand Down
6 changes: 5 additions & 1 deletion packages/worker/src/app/package-app-origin.workers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,11 @@ test('hosted package apps move to the package-app origin behind a single-use han
headers: { Cookie: `${packageSessionCookie}; ${sessionCookie}` },
})
expect(response.status, `expected 404 for ${path}`).toBe(404)
await expect(response.text()).resolves.toBe('Not Found')
const body = await response.text()
expect(body).toContain('/@username/packages/<kody-id>/<path>')
expect(body).toContain(
'Requests outside a package app mount are not dispatched to any app.',
)
}

// 8. The bare package-app origin is a plausible bookmark; send it home.
Expand Down
20 changes: 15 additions & 5 deletions packages/worker/src/mcp/package-app-storage.mcp-e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ type AppStorageResponse = {
bucketId: string
read: unknown
sqlRows: Array<Record<string, unknown>>
packageContext: {
appBasePath: string
hostedUrl: string
}
}

function readExecuteResult<T>(toolResult: CallToolResult): T {
Expand Down Expand Up @@ -67,7 +71,7 @@ function buildPackageFiles(username: string) {
},
{
path: 'src/app.ts',
content: `import { packageStorage } from 'kody:runtime'
content: `import { packageContext, packageStorage } from 'kody:runtime'

export default {
async fetch() {
Expand All @@ -87,7 +91,8 @@ export default {
bucketId: storage.id,
read,
sqlRows: sqlResult.rows,
})
packageContext,
}, { status: 201 })
},
}
`,
Expand Down Expand Up @@ -128,7 +133,8 @@ export default async function main(input) {
const expectedBucketId = `package:${encodeURIComponent(packageId)}`

const cookie = await createAppSessionCookie(server.origin, database.user)
const appUrl = `${server.origin}/@${username}/packages/${kodyId}`
const appBasePath = `/@${username}/packages/${kodyId}`
const appUrl = `${server.origin}${appBasePath}?audio=1`

const firstResponse = await fetch(appUrl, {
headers: { Cookie: cookie, Accept: 'application/json' },
Expand All @@ -138,11 +144,15 @@ export default async function main(input) {
expect(
firstResponse.status,
`first app fetch failed: ${firstBodyText}`,
).toBe(200)
).toBe(201)
const firstBody = JSON.parse(firstBodyText) as AppStorageResponse
expect(firstBody.bucketId).toBe(expectedBucketId)
expect(firstBody.read).toBe(markerValue)
expect(firstBody.sqlRows).toEqual([{ id: 1, note: markerValue }])
expect(firstBody.packageContext).toMatchObject({
appBasePath,
hostedUrl: `${server.origin}${appBasePath}`,
})

const secondResponse = await fetch(appUrl, {
headers: { Cookie: cookie, Accept: 'application/json' },
Expand All @@ -152,7 +162,7 @@ export default async function main(input) {
expect(
secondResponse.status,
`second app fetch failed: ${secondBodyText}`,
).toBe(200)
).toBe(201)
const secondBody = JSON.parse(secondBodyText) as AppStorageResponse
expect(secondBody.bucketId).toBe(expectedBucketId)
expect(secondBody.read).toBe(markerValue)
Expand Down
116 changes: 116 additions & 0 deletions packages/worker/src/package-runtime/package-app.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,78 @@ test('buildPackageAppWorker aligns dynamic worker compatibility with shared opti
expect(factory?.()).toMatchObject(createDynamicWorkerCompatibilityOptions())
})

test('package app worker exposes its public mount and records fetch query and response status', async () => {
resetPackageAppRuntimeMocks()
const { env } = createPackageAppTestEnv()
packageAppRuntimeMock.loadPublishedBundleArtifactByIdentity.mockResolvedValue(
{
row: {
id: 'artifact-row-public-context',
artifactName: null,
entryPoint: 'app.js',
},
artifact: {
mainModule: 'dist/app.js',
modules: {
'dist/app.js':
'export default { fetch() { return new Response("ok", { status: 201 }) } }',
},
dependencies: [],
dynamicDependencies: [],
},
},
)

await buildPackageAppWorker({
env,
baseUrl: 'https://app.kody.test',
userId: 'user-public-context',
savedPackage: {
id: 'package-public-context',
kodyId: 'renamed-app',
name: '@current-owner/renamed-app',
sourceId: 'source-1',
publishedCommit: 'commit-1',
manifestPath: 'package.json',
sourceRoot: '/',
},
source: createPackageAppTestSource(),
manifest: createPackageAppTestManifest(),
runtime: {
callerContext: {
user: {
email: 'owner@example.com',
displayName: 'Owner',
},
} as never,
servingUsername: 'serving-owner',
hostedOrigin: 'https://packages.kody.test',
},
})

const loader = env.APP_LOADER as unknown as {
get: ReturnType<typeof vi.fn>
}
const factory = loader.get.mock.calls[0]?.[1] as
| (() => {
env: Record<string, unknown>
modules: Record<string, string>
})
| undefined
const workerOptions = factory?.()
expect(workerOptions?.env['__kodyPackageContext']).toEqual({
packageId: 'package-public-context',
kodyId: 'renamed-app',
sourceId: 'source-1',
publishedCommit: 'commit-1',
appBasePath: '/@serving-owner/packages/renamed-app',
hostedUrl: 'https://packages.kody.test/@serving-owner/packages/renamed-app',
})
const wrapperSource = workerOptions?.modules['package-app-entry.js']
expect(wrapperSource).toContain('queryString: requestUrl.search')
expect(wrapperSource).toContain('httpStatus: response.status')
})

test('createPackageAppWorkerId changes when compatibility settings change', async () => {
const cacheKey = JSON.stringify([
'user-compat-id',
Expand Down Expand Up @@ -907,6 +979,50 @@ test('package app runtime bridge redacts resolved secrets from run record logs a
expect(finishInput.error.message).not.toContain(secretValue)
})

test('package app runtime bridge adds response status to finish metadata', async () => {
resetPackageAppRuntimeMocks()
const { bridge, waitUntilTasks } = createPackageAppRuntimeBridgeForTest()
const runHandle = {
id: 'run-status',
userId: 'user-1',
startedAt: '2026-07-26T00:00:00.000Z',
persistence: 'eager' as const,
context: {
surface: 'app_fetch' as const,
packageId: 'package-1',
metadata: {
method: 'GET',
queryString: '?audio=1',
},
},
}

await bridge.packageRuntimeRunFinish({
run: runHandle,
status: 'success',
metadata: { httpStatus: 201 },
})
await Promise.all(waitUntilTasks)

expect(packageAppRuntimeMock.finishRunRecord).toHaveBeenCalledWith({
env: {},
handle: {
...runHandle,
context: {
...runHandle.context,
metadata: {
method: 'GET',
queryString: '?audio=1',
httpStatus: 201,
},
},
},
status: 'success',
error: undefined,
logs: undefined,
})
})

test('package app runtime bridge redacts secrets from Error instances in finish payload', async () => {
resetPackageAppRuntimeMocks()
const secretValue = 'pkg-app-thrown-secret-value-4a1b'
Expand Down
Loading
Loading