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
9 changes: 9 additions & 0 deletions .baseline/identity.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"_comment": "THIS TREE'S OWN IDENTITY — the FROM side of every rebrand. tooling/rebrand/rebrand.mjs reads it to know what to rename AWAY from; a product's identity is the --values file, which is the TO side. Change a value here only together with the tree: these strings must be what the tree actually contains, or the rename silently misses and the product ships carrying this baseline's name. `productName` is the BOT_NAME seam in apps/bot/src/identity.ts; `slug` also names the KV namespace titles (terraform `repo`), the Worker (`<slug>-bot`) and the secret project; `domain` and `subdomain` are placeholders, because this baseline has never deployed under a name of its own; `githubOwner` is the owner in SOURCE_URL.",
"slug": "telegram-ai-bot",
"pascal": "TelegramAiBot",
"productName": "AI Telegram Bot",
"domain": "telegram-ai-bot.example.com",
"subdomain": "your-workers-subdomain",
"githubOwner": "sourceplane"
}
160 changes: 160 additions & 0 deletions .baseline/product/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# telegram-ai-bot

A Telegram bot — TBXark's [ChatGPT-Telegram-Workers](https://github.com/TBXark/ChatGPT-Telegram-Workers)
— that answers in private and group chats with the model API you choose,
streams its replies, draws images, runs custom commands and plugins, and is
managed from a Telegram Mini-App. It runs as **one Cloudflare Worker**, its
settings and every chat's history in a **Workers KV** namespace Terraform
provisions per environment, and it answers with **Workers AI** through the
Worker's own `AI` binding until you add any other provider — no vendor key
needed.

## Live deployment

<!-- 02-docs:begin -->
Not recorded yet. The bootstrap's last phase writes the live URLs, the
workspace and the secrets the bot uses into
[ai/context/deployment.md](ai/context/deployment.md); how the bot deploys
and how to operate it is in
[ai/context/operations.md](ai/context/operations.md).
<!-- 02-docs:end -->

## What is here

| Surface | Where |
|---|---|
| The Worker — upstream's entry, `/health`, the deploy's webhook binding | `apps/bot/src` |
| The bot's name and repository (the rename's seam) | `apps/bot/src/identity.ts` |
| The bot: commands, chats, streaming, history | `packages/core` (upstream) |
| The model APIs (OpenAI-compatible, Anthropic, Responses, Workers AI) and the agent over them | `packages/ai`, `packages/agent` (upstream) |
| The configuration, its defaults (Workers AI) and its KV store | `packages/config` |
| The Telegram API client, i18n, the plugin templates, the shared types | `packages/telegram`, `packages/i18n`, `packages/plugins`, `packages/types` (upstream) |
| The single-page app and the `/admin` Mini-App | `packages/web` (upstream; Vite, inlined into one HTML string) |
| Workers build, bindings and deploy contract | `apps/bot/wrangler.template.jsonc` + `wiring.fixture.json` (→ the committed `wrangler.jsonc`), `component.yaml`, `scripts/` |
| The KV namespace (stage, prod) | `infra/terraform/cloudflare-kv` |
| Tests | `tests/bot` (every library's tests and the port's own, in workerd) |

## Getting started

```bash
pnpm install
pnpm run wire:fixture # render apps/bot/wrangler.jsonc from the offline fixture
pnpm typecheck
pnpm lint
pnpm test
pnpm build # the libraries, then wrangler deploy --dry-run → apps/bot/dist
```

```bash
pnpm --filter @app/bot dev:local # http://localhost:8787 — local KV; no account, so no Workers AI
pnpm --filter @app/bot dev # the same with Workers AI (after `wrangler login`)
curl http://localhost:8787/health # {"status":"ok",…,"kv":"ok","telegram":"connect a bot token"}
```

Copy `apps/bot/.dev.vars.example` to `apps/bot/.dev.vars` to give the local
Worker a bot token; Telegram needs a public HTTPS URL to deliver updates, so
a local bot is reached through a tunnel (`wrangler dev --tunnel`).

## Connecting a bot

The Worker deploys and serves with no bot at all: `/` and `/admin` answer,
and `/health` says `"telegram":"connect a bot token"`. To give it one, per
environment (stage and prod are two Workers and need two bots — one webhook
per token):

1. Create the bot with [@BotFather](https://t.me/BotFather) (`/newbot`) and
copy its token; find your own Telegram user id with
[@userinfobot](https://t.me/userinfobot).
2. Store them as the environment's Orun secrets:

```bash
orun secrets set TELEGRAM_TOKEN --env stage # the token from @BotFather
orun secrets set ADMIN_ID --env stage # your Telegram user id
orun secrets set ADMIN_PASSWORD --env stage # optional: /admin from a plain browser
orun secrets set TELEGRAM_SECRET_TOKEN --env stage # optional: Telegram's webhook secret header
```

3. Redeploy the environment (Orunbase's **Deploy** button, or **Run
workflow** — below). The deploy pushes the secrets to the Worker, then
binds the webhook: the Worker sets Telegram's webhook to itself,
publishes the bot's commands, and puts the admin Mini-App on the chat's
menu button.
4. Message your bot. It answers with Workers AI; open **Settings** (the menu
button) to add OpenAI, Anthropic, Groq, DeepSeek or any OpenAI-compatible
API, pick models, change the language, and add plugins and commands —
upstream's [documentation](https://github.com/TBXark/ChatGPT-Telegram-Workers/tree/master/doc/en)
covers each.

## How the namespace is wired

The Worker binds the namespace as `DATABASE` (upstream's name). Its id is
never hand-written: `apps/bot/wrangler.template.jsonc` names it as a wiring
token, and `wrangler.jsonc` is that template rendered — from
`wiring.fixture.json` (placeholder ids) for local work and verification, and
on every deploy from the document the `cloudflare-kv` Terraform root
publishes after its apply (`WIRING_CLOUDFLARE_KV`, per environment). Edit the
template, then `pnpm run wire:fixture` and commit the render with it.

## How it deploys

Merges to `main` converge through Orun: `.github/workflows/ci.yml` plans the
changed components and runs each lane against the workspace in
`intent.yaml`. The KV namespace applies first, then the Worker builds with
that environment's namespace id and deploys — to `stage`, then to `prod`
once stage has converged on the same commit; `dev` only verifies. The Worker
is `telegram-ai-bot-bot-<env>` on your account's workers.dev subdomain.
After each deploy the bot's stored secrets are pushed to it, its webhook is
bound when it has a token, and `/health` must answer `"kv":"ok"` for that
environment. A pull request runs the verify lanes, with nothing applied or
deployed: the namespace planned, the tests run, the Worker built and
dry-deployed per environment.

The pipeline holds one credential, GitHub's own `GITHUB_TOKEN`. The
Cloudflare token and account id are brokered per run from the workspace's
Cloudflare connection; the namespace ids and the bot's secrets travel as
Orun secrets. Nothing provider-shaped is stored in the repository or in
GitHub.

**Deploy by hand.** Orunbase's **Deploy** button on a component, or **Run
workflow** on the CI workflow in GitHub's Actions tab (on `main`), runs
`ci.yml` for the environment and components you pick, and each one deploys
exactly as a merge would deploy it. Leave the component blank to redeploy
every component in that environment with nothing changed — after storing
the bot's token, say. A component with nothing to run in that environment (a
test suite in `prod`) is left out with a notice.

## How it maps to the upstream's Cloudflare deploy

The upstream deploys with "Deploy to Cloudflare" and a few steps by hand; here
each of them is part of the repository:

| Upstream | Here |
|---|---|
| "Deploy to Cloudflare" creates the KV namespace | `infra/terraform/cloudflare-kv`, applied by Orun per environment before the Worker deploys |
| `wrangler.jsonc` with the namespace id filled in by hand | `apps/bot/wrangler.template.jsonc`, rendered per environment from the root's wiring document |
| `TELEGRAM_TOKEN`, `ADMIN_ID`, `ADMIN_PASSWORD` in the dashboard | optional Orun secrets per environment, pushed to the Worker as Worker secrets after each deploy |
| Open `/init` and press "bind" | the deploy binds the webhook itself (`scripts/bind-webhook.mjs` → the Worker's `POST /init/bind`); `/init` still works |
| No model until a provider is added in `/admin` | Workers AI on the `AI` binding, the default for chat and images, no key |
| Workers Builds on push | Orun applies the namespace and deploys `<repo>-bot-{stage,prod}` on merge to `main` |
| `pnpm -w run build:workers` (esbuild) | `wrangler deploy --dry-run` after turbo builds the libraries; upstream's bundle guard kept |
| Node, Vercel and Docker deploys | not ported: Workers only |

## Custom domain

The bot answers on workers.dev from its first deploy. To serve it on your
own domain, add the domain to the Cloudflare account the bot deploys into
and attach it to the Worker (dashboard → Workers & Pages →
`telegram-ai-bot-bot-prod` → Settings → Domains & Routes → Add → Custom
domain), then set the public base URL to it in `/admin`'s settings and bind
the webhook again from `/init` (or redeploy), so Telegram and the admin
links use it. The repository names the
domain in one place, `BASE_DOMAIN` in `intent.yaml`, which it was born with
as the reserved placeholder `telegram-ai-bot.example.com`. Replace it with
your domain in the same change that records it.

## Credit and licence

The bot is [ChatGPT-Telegram-Workers](https://github.com/TBXark/ChatGPT-Telegram-Workers)
by [TBXark](https://github.com/TBXark) and its contributors, released under
the MIT licence ([`apps/bot/LICENSE`](apps/bot/LICENSE)), which a product
built from this repository keeps.
27 changes: 27 additions & 0 deletions .baseline/tasks/01-product.TaskContract.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Task contract template for the 01-product landing.
# Unbound to a key on purpose: `orun.task/ensure@v1` seals and attaches it to
# the key the allocator issues. It lives under `.baseline/`, not `tasks/`,
# because `tasks/` is this repository's own work tree (`intent.yaml` `work:`),
# where an unkeyed contract is an error. gates: [] is a DECLARATION — merge
# alone finishes this task; the main convergence is the gate the bootstrap
# watches, not one the plane observes as a PR check.
#
# The whole product in one landing. `affects` names COMPONENTS, by
# metadata.name: the phase's retouch hook reads this list to decide which
# component.yaml files get the redeploy marker, so a re-run of the phase has a
# diff and exactly these components are re-planned — the deploy set and the
# task plane's statement of the work are one list.
apiVersion: orun.io/v1
kind: TaskContract
spec:
goal: The product's repository is born and linked, the whole product lands in one pull request, and one convergence applies the KV namespace and deploys the bot on stage and prod
affects:
- bot
- bot-tests
- cloudflare-kv
doneWhen:
- repo pushed, main pinned as default, workspace linked
- WIRING_CLOUDFLARE_KV published on stage and prod
- main convergence green (KV applied, then the bot built, deployed and smoke-tested on stage and prod)
- the bot answers /health on both workers.dev URLs
gates: []
13 changes: 13 additions & 0 deletions .baseline/tasks/02-docs.TaskContract.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Task contract template for the 02-docs landing. See 01-product's header.
apiVersion: orun.io/v1
kind: TaskContract
spec:
goal: The live deployment is recorded from verified facts as agent-readable state in the product's repo
affects:
- ai/context/deployment.md
- ai/context/operations.md
- README.md
doneWhen:
- committed deployment manifest matches probed reality
- prod waits on stage again, and dev verifies every merge to main again
gates: []
155 changes: 155 additions & 0 deletions .github/workflows/baseline.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
name: Baseline CI

# THE FACTORY'S OWN LANES — this repository tested as a BASELINE: that its
# build document parses with the orun a bootstrap actually runs, that its card
# agrees with it, that every component is placed by the one product phase,
# that the KV namespace's wiring reaches the Worker's config, that a placed
# tree comes up branded and carrying nothing of the factory — and plans the
# namespace before the Worker on a merge — and that the product it produces
# installs, builds, deploys (dry), serves, binds its webhook and answers.
#
# ─── WHY THIS IS NOT IN ci.yml ────────────────────────────────────────────
#
# `repo-blueprint.yaml`'s `github-workflows` module copies the WHOLE `.github`
# directory into every bot built from this repository. These jobs run
# `testing/*.sh`, and `testing/` is deliberately not placed — so in a bot they
# would be steps that cannot pass, red on its very first pull request. This
# file is in the blueprint's `ignore` list, and `testing/coverage.test.sh`
# fails on any workflow that reads `testing/` and is not.

on:
push:
branches: [main]
pull_request:

concurrency:
group: baseline-ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

permissions:
contents: read

jobs:
# Tier 0. bash, python3 and git; node for the tools. No workspace install,
# no network, no credential — the job that most certainly fails a PR.
baseline-contract:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v5
with:
node-version: 22
# setup-node v5 turns on the pnpm cache by itself when package.json
# names a packageManager, and then fails on a runner with no pnpm.
# This job installs nothing.
package-manager-cache: false
- name: Contract tests (manifest, phases, coverage, rebrand, retouch, bootstrap-defer, wire)
run: |
set -euo pipefail
python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml
for t in manifest phases coverage rebrand retouch bootstrap-defer wire; do
echo "── $t"
bash "testing/$t.test.sh"
done
# Every component's docs/{overview,architecture,runbook}.md is generated
# from what the component declares (its manifest, Worker config,
# Terraform, migrations, package scripts). A pull request that changes
# one of those facts without regenerating the pages fails here.
- name: Component docs match their manifests
run: python3 tooling/catalog/gen-component-docs.py --check

# Tier 1. THE BLUEPRINT, READ AND PLACED BY THE BINARY A BOOTSTRAP RUNS.
#
# Pinned at the bootstrap floor (BOOTSTRAP.md), not the bot's lane pin:
# every test here reads YAML with PyYAML, which parses anything well-formed;
# only the pinned orun can say whether the document is one a bootstrap can
# run. `--status` parses it, validates every hook against the action
# registry, compiles every `when` and narration template, and writes
# nothing. Then the leak gate (what a product would carry, derived by the
# floor too), and the placement tier (the offline bootstrap: both phases
# placed and finished by the blueprint's own hooks, then the product's own
# `orun plan` for the 01-product merge — the KV apply before the Worker's
# deploy — by an orun at or above the product's lane pin, below).
blueprint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: sourceplane/orun-action@v1.2.0
with:
version: v2.88.0
- uses: pnpm/action-setup@v4
with:
version: 10.12.1
- uses: actions/setup-node@v5
with:
node-version: 22
# This job installs nothing either: with no lockfile hook the offline
# bootstrap never runs pnpm, so there is no store, and the pnpm cache
# setup-node v5 turns on by itself (package.json names a packageManager)
# fails the job saving a path that does not exist whenever no earlier
# cache exists for the lockfile.
package-manager-cache: false
- name: repo-blueprint.yaml, read by the pinned CLI
run: |
set -euo pipefail
orun --version
python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml
# Required inputs must be supplied for the document to resolve; the
# values are arbitrary and nothing is written.
orun new --blueprint repo-blueprint.yaml --status \
--out "$(mktemp -d)" \
--set reponame=acme-bot \
--set "productname=Acme Assistant" \
--set githuborg=acme-inc
- name: the leak gate — what a product carries
run: bash testing/leak.test.sh
# The placement tier ENDS with the product's own `orun plan` — what the
# product's ci.yml runs — so it needs an orun at the product's lane pin
# or newer: one older than v2.78.4 plans a pull request with apps/bot
# waiting on the KV plan, because it does not apply a dependsOn edge's
# `modeRules` (advisory on a PR, enforced on main). The test refuses an
# orun older than the pin rather than assert the wrong CLI's plan. The
# offline bootstrap before it reads the blueprint, which takes the
# bootstrap floor (v2.88.0: the one `secrets` reconcile, the task set-up
# in the background, the landings checked in the box), so this tier
# runs the floor, which is newer than the lane pin.
- uses: sourceplane/orun-action@v1.2.0
with:
version: v2.88.0
- name: placement — the offline bootstrap, and the product's own plan
run: |
git config --global user.email ci@example.invalid
git config --global user.name "baseline ci"
bash testing/placement.test.sh

# Tier 2. THE PRODUCT IT PRODUCES WORKS: its one landing installed, its
# fixture rendered, type-checked, linted, tested (every upstream library's
# tests and the Worker's, in workerd) and built, the stage lane's own
# structure check, build (the live wiring render included), typecheck and
# dry deploy in the tree orun stages, and the built Worker served and
# smoke-tested with the deploy's own smoke step — with no bot token, then
# with one, bound to a stand-in Telegram API and answering an update
# through a stand-in model API. Pinned at the
# bootstrap floor (v2.88.0): the offline bootstrap reads the blueprint, and
# the floor is newer than the product's lane pin (v2.78.4), which is all the
# lane steps need.
site:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: sourceplane/orun-action@v1.2.0
with:
version: v2.88.0
- uses: pnpm/action-setup@v4
with:
version: 10.12.1
- uses: actions/setup-node@v5
with:
node-version: 22
cache: pnpm
- name: e2e — the bootstrapped product builds, deploys (dry), serves, binds its webhook and answers
run: |
python3 -c 'import yaml' 2>/dev/null || pip install --quiet pyyaml
git config --global user.email ci@example.invalid
git config --global user.name "baseline ci"
bash testing/e2e.test.sh
Loading
Loading