Skip to content
Closed
Show file tree
Hide file tree
Changes from 12 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
13 changes: 7 additions & 6 deletions docs/guides/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ Official markdown guides for agent and contributor workflows. At runtime, the
branch via `raw.githubusercontent.com` (see capability description in code for
available `guide` ids).

| File | Topic |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
| [integration-bootstrap.md](./integration-bootstrap.md) | **Start here** for third-party integrations that must work before saving dependent skills or apps |
| [oauth.md](./oauth.md) | **Start here** for third-party OAuth (`/connect/oauth`, redirect URI, params) |
| [generated-ui-oauth.md](./generated-ui-oauth.md) | Edge case: OAuth in a saved app (`@kody/ui-utils`) |
| [connect-secret.md](./connect-secret.md) | `/connect/secret` URL parameters and policies |
| File | Topic |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
| [integration-bootstrap.md](./integration-bootstrap.md) | **Start here** for third-party integrations that must work before saving dependent skills or apps |
| [integration-backed-app-happy-path.md](./integration-backed-app-happy-path.md) | Default saved-app pattern after integration smoke test passes |
| [oauth.md](./oauth.md) | **Start here** for third-party OAuth (`/connect/oauth`, redirect URI, params) |
| [generated-ui-oauth.md](./generated-ui-oauth.md) | Edge case: OAuth in a saved app (`@kody/ui-utils`) |
| [connect-secret.md](./connect-secret.md) | `/connect/secret` URL parameters and policies |
7 changes: 7 additions & 0 deletions docs/guides/generated-ui-oauth.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ When the flow needs readable, non-sensitive configuration such as a client ID,
save it with \`saveValue(...)\` and read it back with \`getValue(...)\` instead
of treating it like a secret.

Once the connector or tokens exist and the post-connect smoke test passes,
prefer to continue with a saved app that uses `serverCode` backend endpoints for
provider API calls and `clientCode` fetches through
`kodyWidget.appBackend.basePath`. Keep embedded client-side `executeCode(...)`
strings for quick prototypes or throwaway experiments, not the default
integration-backed app structure.

## Recommended capability and tool sequence

1. Generate the UI source.
Expand Down
48 changes: 48 additions & 0 deletions docs/guides/integration-backed-app-happy-path.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Integration-backed app happy path

Use this guide after `integration_bootstrap` proves the integration already
works, or when connector and secret state are already clear enough to verify
quickly.

## Recommended sequence

1. Discover connector and secret state.
- Use `search` to inspect saved connectors and secret references.
- Read full connector metadata only when you need the exact names, hosts, or
API base URL.
2. Verify the required connector exists.
- Confirm the connector name, token secret names, and API base URL match the
app you are about to build.
3. Run one cheap authenticated smoke test in `execute`.
- Prefer a small read-only request such as `GET /me`, `GET /viewer`, or
`GET /v1/me`.
4. If the smoke test passes, proceed directly to building the app.
- Prefer a saved app with `serverCode` backend endpoints such as `/api/state`
and `/api/action`.
- Keep `clientCode` mostly UI plus `fetch(...)` calls to
`kodyWidget.appBackend.basePath`.
5. Open the saved app and iterate.
- Save with `ui_save_app`.
- Reopen with `open_generated_ui({ app_id })`.
- Iterate on the hosted app instead of repeatedly pasting large inline HTML
blobs back into the model context.

## Default saved app shape

For non-trivial or integration-backed apps, prefer this split:

- `serverCode`: connector lookups, provider API calls, persistence, validation,
and mutations
- `clientCode`: rendering, form handling, button clicks, and fetches to the app
backend
- `executeCode(...)` embedded directly in client HTML: acceptable for quick
prototypes or one-off experiments, not the default saved-app pattern

## Avoid this detour

If the connector state, secret names, allowed hosts, and provider contract are
already clear enough, do **not** spend extra time spelunking the local repo
before building the app.

Inspect local source only when you specifically need repo conventions, shared
helpers, or an existing app artifact to extend.
7 changes: 7 additions & 0 deletions docs/guides/integration-bootstrap.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ If those conditions are not met, stop and fix the integration first.
hosts all work end-to-end.
5. Only after the smoke test succeeds should you build or save the dependent
skill or app.
- If the connector or tokens already exist and the smoke test passes, proceed
directly to app or skill construction.
- Do not spend extra time exploring the local repo when the connector state,
secret names, allowed hosts, and provider contract are already clear
enough.
- For the default saved-app structure after bootstrap, load
`kody_official_guide` with `guide: "integration_backed_app"`.
6. If the smoke test fails, keep working on integration setup. Do not treat the
downstream artifact as ready.

Expand Down
159 changes: 159 additions & 0 deletions docs/guides/oauth.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,162 @@ authenticating to Kody**. This guide is for **outbound** provider OAuth.
`guide: "integration_bootstrap"` before saving the downstream artifact.
6. Continue with capabilities that use \`{{secret:…}}\` or connector helpers;
host/capability approval may still be required after save.

## Example: Spotify-backed saved app after auth bootstrap

Use this pattern only **after** the hosted `/connect/oauth` flow is complete,
the Spotify connector already exists, and the authenticated smoke test passes.

The ordering is:

1. auth bootstrap first
2. smoke test second
3. save the app with `serverCode` backend routes
4. keep `clientCode` mostly UI plus fetches to `kodyWidget.appBackend.basePath`

For non-trivial apps, keep provider API calls in `serverCode`, not in embedded
client-side `executeCode(...)` strings. Those inline snippets are acceptable for
quick or throwaway prototypes only.

```ts
await codemode.ui_save_app({
title: 'Spotify playback controls',
description:
'Read current playback state and trigger simple Spotify actions through a saved app backend.',
clientCode: `
<main>
<h1>Spotify playback controls</h1>
<p id="track">Loading...</p>
<div style="display:flex;gap:0.5rem;">
<button type="button" data-action="refresh">Refresh</button>
<button type="button" data-action="next">Next track</button>
<button type="button" data-action="pause">Pause</button>
</div>
<script type="module">
import { kodyWidget } from '@kody/ui-utils'

const track = document.querySelector('#track')
const basePath = kodyWidget.appBackend?.basePath
function requireBackendBasePath() {
if (!basePath) {
track.textContent = 'Saved app backend is not available.'
return null
}
return basePath
}

async function loadState() {
const resolvedBasePath = requireBackendBasePath()
if (!resolvedBasePath) return
const response = await fetch(\`\${resolvedBasePath}/api/state\`)
const payload = await response.json()
track.textContent = payload.trackName
? \`\${payload.trackName} — \${payload.artistName}\`
: 'Nothing is currently playing.'
}

async function runAction(action) {
const resolvedBasePath = requireBackendBasePath()
if (!resolvedBasePath) return
await fetch(\`\${resolvedBasePath}/api/action\`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ action }),
})
await loadState()
}

document.querySelectorAll('[data-action]').forEach((button) => {
button.addEventListener('click', () => {
const action = button.getAttribute('data-action')
if (action === 'refresh') {
void loadState()
return
}
if (action) void runAction(action)
})
})

void loadState()
</script>
</main>
`,
serverCode: `
import { DurableObject } from 'cloudflare:workers'

export class App extends DurableObject {
async spotifyRequest(path, init = {}) {
const { connector } = await this.env.KODY.connectorGet({ name: 'spotify' })
if (!connector?.apiBaseUrl) {
return new Response('Missing spotify connector.', { status: 400 })
}

const authorization = await this.env.KODY.secretPlaceholder(
connector.accessTokenSecretName,
'user',
)
const upstream = await this.env.KODY.fetchWithResolvedSecrets({
url: new URL(path, connector.apiBaseUrl).toString(),
method: init.method ?? 'GET',
headers: {
authorization: \`Bearer \${authorization}\`,
...(init.body ? { 'content-type': 'application/json' } : {}),
},
body: init.body,
})

return await fetch(upstream.url, {
method: upstream.method,
headers: upstream.headers,
body: upstream.body,
})
}

async fetch(request) {
const url = new URL(request.url)

if (url.pathname === '/api/state' && request.method === 'GET') {
const response = await this.spotifyRequest('/me/player/currently-playing')
const payload = response.ok ? await response.json().catch(() => null) : null
return Response.json({
trackName: payload?.item?.name ?? null,
artistName: payload?.item?.artists?.[0]?.name ?? null,
})
}

if (url.pathname === '/api/action' && request.method === 'POST') {
const body = await request.json().catch(() => null)
const path =
body?.action === 'next'
? '/me/player/next'
: body?.action === 'pause'
? '/me/player/pause'
: null
if (!path) return new Response('Unsupported action.', { status: 400 })
try {
const response = await this.spotifyRequest(path, { method: 'POST' })
if (!response.ok) {
const details = await response.text().catch(() => '')
return new Response(
details || 'Spotify action request failed.',
{ status: response.status || 502 },
)
}
return Response.json({ ok: true })
} catch (error) {
return new Response(
error instanceof Error
? error.message
: 'Spotify action request failed.',
{ status: 502 },
)
}
}

return new Response('Not found.', { status: 404 })
}
}
`,
hidden: false,
})
```
30 changes: 30 additions & 0 deletions docs/use/examples/job-feed-checker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Example job: feed checker with incremental state

This example shows a scheduled job that remembers the latest seen item id in its
facet SQLite storage and only emits new items on later runs.

## Save it

Create the job with `job_create`:

```json
{
"name": "Feed checker",
"schedule": {
"intervalMs": 3600000
},
"timezone": "America/Denver",
"enabled": true,
"serverCode": "import { DurableObject } from 'cloudflare:workers'\n\nexport class Job extends DurableObject {\n\tasync run() {\n\t\tconst feedUrlValue = await KODY.valueGet('feed_url', 'user')\n\t\tif (!feedUrlValue?.value) {\n\t\t\tthrow new Error('Missing persisted value \"feed_url\".')\n\t\t}\n\n\t\tconst response = await KODY.fetchViaHostGateway({\n\t\t\turl: feedUrlValue.value,\n\t\t\tmethod: 'GET',\n\t\t\theaders: {\n\t\t\t\tAccept: 'application/json',\n\t\t\t},\n\t\t})\n\t\tif (response.status >= 400) {\n\t\t\tthrow new Error(`Feed request failed: ${response.status} ${response.statusText}`)\n\t\t}\n\n\t\tconst payload = JSON.parse(response.body)\n\t\tconst items = Array.isArray(payload.items) ? payload.items : []\n\n\t\tthis.ctx.storage.sql.exec(\n\t\t\t'CREATE TABLE IF NOT EXISTS feed_state (singleton INTEGER PRIMARY KEY CHECK (singleton = 1), item_id TEXT)',\n\t\t)\n\n\t\tconst latestSeen = this.ctx.storage.sql\n\t\t\t.exec('SELECT item_id FROM feed_state WHERE singleton = 1')\n\t\t\t.one<{ item_id?: string }>()?.item_id ?? null\n\n\t\tconst freshItems = latestSeen\n\t\t\t? items.filter((item) => item?.id && item.id !== latestSeen)\n\t\t\t: items.slice(0, 1)\n\n\t\tif (items[0]?.id) {\n\t\t\tthis.ctx.storage.sql.exec(\n\t\t\t\t'INSERT INTO feed_state (singleton, item_id) VALUES (1, ?) ON CONFLICT(singleton) DO UPDATE SET item_id = excluded.item_id',\n\t\t\t\tString(items[0].id),\n\t\t\t)\n\t\t}\n\n\t\tif (freshItems.length === 0) {\n\t\t\treturn { newItems: 0 }\n\t\t}\n\n\t\treturn {\n\t\t\tnewItems: freshItems.length,\n\t\t\tlatestItemId: String(items[0]?.id ?? ''),\n\t\t\tnotifications: freshItems.map((item) => ({\n\t\t\t\tid: String(item.id),\n\t\t\t\ttitle: String(item.title ?? item.id),\n\t\t\t})),\n\t\t}\n\t}\n}\n"
}
```
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

## Notes

- The job uses `KODY.valueGet('feed_url', 'user')` so the feed URL can be
changed without editing code.
- `KODY.fetchViaHostGateway()` uses the same secret-aware host approval path as
execute-time fetch.
- The `feed_state` table is local to the job facet, so every job keeps its own
checkpoint independently.
- Inspect the latest outcomes with `job_history({ job_id })`.
Loading