anybot-connector 0.0.0-stage → 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +119 -2
  3. package/bin/anybot-status +93 -0
  4. package/docs/DEPENDENCIES.md +25 -0
  5. package/docs/HOST-INTEGRATION.md +59 -0
  6. package/docs/PROVENANCE.md +27 -0
  7. package/docs/SUPPORT-MATRIX.md +36 -0
  8. package/examples/cli-config.example.json +25 -0
  9. package/examples/http-server.mjs +81 -0
  10. package/examples/knocket-channel.mjs +110 -0
  11. package/examples/lib/demo-connector.mjs +90 -0
  12. package/examples/mcp-server.mjs +57 -0
  13. package/package.json +62 -4
  14. package/spec/0001-connector-contract.md +144 -0
  15. package/spec/0002-alpha-api.md +153 -0
  16. package/spec/0003-bindings.md +92 -0
  17. package/src/channels/knocket/index.mjs +264 -0
  18. package/src/cli/config.mjs +98 -0
  19. package/src/cli/index.mjs +99 -0
  20. package/src/contract.mjs +28 -0
  21. package/src/core/index.mjs +195 -0
  22. package/src/core/storage.mjs +81 -0
  23. package/src/index.mjs +15 -0
  24. package/src/providers/openbot/fixture.mjs +58 -0
  25. package/src/providers/openbot/provider.mjs +97 -0
  26. package/src/providers/reference/index.mjs +40 -0
  27. package/src/providers/teambot/index.mjs +83 -0
  28. package/src/status/console.mjs +54 -0
  29. package/src/status/health.mjs +179 -0
  30. package/src/status/query.mjs +29 -0
  31. package/src/status/registry.mjs +92 -0
  32. package/src/status/schema.mjs +99 -0
  33. package/src/status/snapshot.mjs +63 -0
  34. package/src/transports/common/validate.mjs +93 -0
  35. package/src/transports/http/body.mjs +62 -0
  36. package/src/transports/http/errors.mjs +31 -0
  37. package/src/transports/http/index.mjs +223 -0
  38. package/src/transports/mcp/index.mjs +150 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Harzva and AnyBot-Connector contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,120 @@
1
- # Temporary Holding Version
1
+ # AnyBot-Connector
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A small, open interoperability layer that connects bot providers to HTTP, MCP and
4
+ application channels through one explicit task and authority contract.
5
+
6
+ **Status: runnable reference alpha; isolated TeamBot backend verified.**
7
+ The deterministic reference provider runs without a model account or private
8
+ repository. The TeamBot adapter and chat channel also passed isolated backend checks; **real enterprise and Knocket acceptance is pending**.
9
+ Prepared for npm alpha release (`anybot-connector@0.1.0-alpha.1`); no production deployment claim.
10
+
11
+ ```mermaid
12
+ flowchart LR
13
+ HTTP[HTTP applications] --> Core[Shared connector service]
14
+ MCP[MCP tools] --> Core
15
+ Chat[Chat Completions text subset] --> Core
16
+ Core --> Reference[Durable deterministic reference provider]
17
+ Core --> TeamBot[Independent TeamBot API adapter]
18
+ ```
19
+
20
+ ## Run the reference provider
21
+
22
+ Requires Node.js 22.16+ and npm. No compilation or private dependency is needed.
23
+
24
+ Once published, you can install or invoke the CLI via npm:
25
+
26
+ ```sh
27
+ npm install anybot-connector@alpha
28
+ npx anybot-connector --help
29
+ ```
30
+
31
+ Or run directly from source:
32
+
33
+ ```sh
34
+ git clone https://github.com/Harzva/anybot-connector.git
35
+ cd anybot-connector
36
+ npm ci --ignore-scripts
37
+ export ANYBOT_TOKEN="$(node -e "process.stdout.write(require('node:crypto').randomBytes(24).toString('hex'))")"
38
+ node src/cli/index.mjs init connector.local.json ./state
39
+ node src/cli/index.mjs check connector.local.json
40
+ node src/cli/index.mjs serve connector.local.json
41
+ ```
42
+
43
+ In a second terminal with the same token:
44
+
45
+ ```sh
46
+ curl -s http://127.0.0.1:8790/v1/connections/demo/tasks \
47
+ -H "Authorization: Bearer $ANYBOT_TOKEN" -H 'Content-Type: application/json' \
48
+ -d '{"requestKey":"hello-1","input":{"type":"text","text":"Hello"}}'
49
+ ```
50
+
51
+ The response contains an opaque `handle`. Query `/v1/tasks/<handle>` with the same
52
+ bearer credential. The completed text is `[reference] Hello`: this is a fixture,
53
+ not an LLM response. Submit the same key and payload again to recover the same
54
+ task; changing the text with that key returns `IDEMPOTENCY_CONFLICT`.
55
+
56
+ Stop with `node src/cli/index.mjs stop connector.local.json` or Ctrl+C. Keep the
57
+ state directory to recover tasks after restart. It contains private reference
58
+ input/output and must not be committed. Edit the config's identity operations or
59
+ remove an identity to revoke access; policy is rechecked during operations and
60
+ before result disclosure. [Host and recovery details](docs/HOST-INTEGRATION.md).
61
+
62
+ ## MCP and channel examples
63
+
64
+ Start the same service with `serve connector.local.json --stdio demo` to expose
65
+ MCP tools over stdio alongside HTTP. The launching host fixes the MCP principal;
66
+ tool arguments cannot choose an identity. MCP clients should launch the CLI
67
+ process and preserve stdout for the protocol. Logs go to stderr.
68
+
69
+ These self-contained synthetic examples demonstrate the exported bindings:
70
+
71
+ ```sh
72
+ node examples/http-server.mjs
73
+ node examples/mcp-server.mjs
74
+ node examples/knocket-channel.mjs
75
+ ```
76
+
77
+ They use a small in-memory demo service, not the durable provider. The channel
78
+ accepts only fixed model aliases, bounded user/assistant text messages and optional
79
+ `stream:false`. It rejects system/developer roles, tools, attachments, unknown
80
+ options and streaming. Missing retry keys produce independent request contexts;
81
+ a shared application credential does not identify a visitor. See the exact
82
+ [HTTP, MCP and channel bindings](spec/0003-bindings.md).
83
+
84
+ ## Guarantees and limits
85
+
86
+ - One process per state directory. Atomic/fsynced correlation journal; provider
87
+ owns task outcomes. No distributed writer or task scheduler.
88
+ - Same-key concurrency, caller/end-user isolation, crash recovery and cancellation
89
+ races have focused tests. An uncertain submission is queried, never silently
90
+ replayed as another POST. TeamBot requires its opaque receipt: a response lost
91
+ before receipt persistence may need operator reconciliation. No unlimited exactly-once claim.
92
+ - Core journals routing metadata, private provider receipts and input digests. Reference provider stores
93
+ its own task facts. State is capped at 10000 tasks and 8 MiB per store; admission
94
+ fails when capacity is reached. No automatic retention cleanup.
95
+ - TeamBot requires explicit operator trust and a fixed endpoint. Publication
96
+ consistency checks do not prove enterprise ownership. Credentials remain with
97
+ the host. No private TeamBot code is vendored.
98
+ - A2A, AG-UI, attachments, input continuation, token streams and programmatic
99
+ human handoff are not implemented. No real-platform or production claim.
100
+
101
+ ## Verify and contribute
102
+
103
+ ```sh
104
+ npm test
105
+ npm run check
106
+ ```
107
+
108
+ Tests use synthetic data and ephemeral loopback ports. The package check audits
109
+ public dependency sources/licenses and shipped contents; it is not a security
110
+ certification. [Verification report](docs/VERIFICATION.md) records exact results
111
+ and limitations. Source is [MIT licensed](LICENSE); dependencies retain their
112
+ own licenses. The package is configured for public npm alpha publication (`publishConfig.access = "public"`) with automated provenance checks.
113
+
114
+ | Document | Purpose |
115
+ | --- | --- |
116
+ | [Host integration](docs/HOST-INTEGRATION.md) | Config, recovery and bearer policy details |
117
+ | [Contract](spec/0001-connector-contract.md) / [API](spec/0002-alpha-api.md) | Public implementation boundary |
118
+ | [Bindings](spec/0003-bindings.md) | HTTP, MCP and channel specifications |
119
+ | [Support matrix](docs/SUPPORT-MATRIX.md) | Evidence levels and live gates |
120
+ | [Provenance](docs/PROVENANCE.md) / [Dependencies](docs/DEPENDENCIES.md) | Reuse and licenses |
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ import { renderStatusConsole, querySnapshotFile } from '../src/status/console.mjs';
3
+ import { loadSnapshot } from '../src/status/snapshot.mjs';
4
+ import { OBJECT_TYPES } from '../src/status/schema.mjs';
5
+
6
+ const usage = `Usage:
7
+ anybot-status render <snapshot.json> [--now <iso|ms>]
8
+ anybot-status query <snapshot.json> --scope <scope> [--scope <scope> ...] [--type bot|harness|model|account|route]
9
+ [--id <id>] ... [--before <id>] [--limit <n>] [--principal <name>] [--json] [--now <iso|ms>]
10
+ anybot-status check <snapshot.json>`;
11
+
12
+ function fail(message, code = 2) {
13
+ process.stderr.write(`error: ${message}\n`);
14
+ process.exit(code);
15
+ }
16
+
17
+ function parseInstant(value) {
18
+ if (value === undefined) return Date.now();
19
+ if (/^\d+$/.test(value)) {
20
+ const ms = Number(value);
21
+ if (!Number.isSafeInteger(ms) || ms < 0) fail(`invalid --now "${value}"`);
22
+ return ms;
23
+ }
24
+ const parsed = Date.parse(value);
25
+ if (!Number.isFinite(parsed)) fail(`invalid --now "${value}"`);
26
+ return parsed;
27
+ }
28
+
29
+ function collect(values, value) {
30
+ values.push(value);
31
+ return values;
32
+ }
33
+
34
+ async function main(argv) {
35
+ const [command, file, ...rest] = argv;
36
+ if (!command || !file || rest.includes('--help')) {
37
+ process.stderr.write(`${usage}\n`);
38
+ process.exit(command && rest.includes('--help') ? 0 : 2);
39
+ }
40
+ const options = { scopes: [], ids: [], json: false };
41
+ for (let index = 0; index < rest.length; index += 1) {
42
+ const flag = rest[index];
43
+ const value = rest[index + 1];
44
+ switch (flag) {
45
+ case '--scope': if (value === undefined) fail('--scope requires a value'); options.scopes = collect(options.scopes, value); index += 1; break;
46
+ case '--id': if (value === undefined) fail('--id requires a value'); options.ids = collect(options.ids, value); index += 1; break;
47
+ case '--type': if (value === undefined) fail('--type requires a value'); if (!OBJECT_TYPES.includes(value)) fail(`--type must be one of ${OBJECT_TYPES.join(', ')}`); options.type = value; index += 1; break;
48
+ case '--before': if (value === undefined) fail('--before requires a value'); options.before = value; index += 1; break;
49
+ case '--limit': {
50
+ if (value === undefined || !/^\d+$/.test(value)) fail('--limit requires a positive integer');
51
+ const limit = Number(value);
52
+ if (limit < 1) fail('--limit requires a positive integer');
53
+ options.limit = limit; index += 1; break;
54
+ }
55
+ case '--principal': if (value === undefined) fail('--principal requires a value'); options.principal = value; index += 1; break;
56
+ case '--json': if (value === 'true' || value === 'false') { options.json = value === 'true'; index += 1; } else options.json = true; break;
57
+ case '--now': if (value === undefined) fail('--now requires a value'); options.now = value; index += 1; break;
58
+ default: fail(`unknown argument "${flag}"`);
59
+ }
60
+ }
61
+ const now = parseInstant(options.now);
62
+ if (command === 'render') {
63
+ const { savedAt, objects } = await loadSnapshot(file);
64
+ process.stdout.write(`${renderStatusConsole(objects, { now, savedAt })}\n`);
65
+ return;
66
+ }
67
+ if (command === 'query') {
68
+ if (!options.scopes.length) fail('NO_SCOPE: query must grant at least one --scope; the console is fail-closed without granted scopes', 3);
69
+ const entries = await querySnapshotFile(file, {
70
+ principal: options.principal,
71
+ scopes: options.scopes,
72
+ objectType: options.type,
73
+ ids: options.ids.length ? options.ids : undefined,
74
+ before: options.before,
75
+ limit: options.limit,
76
+ });
77
+ if (options.json) process.stdout.write(`${JSON.stringify(entries, null, 2)}\n`);
78
+ else process.stdout.write(`${renderStatusConsole(entries, { now })}\n`);
79
+ return;
80
+ }
81
+ if (command === 'check') {
82
+ const { format, savedAt, objects } = await loadSnapshot(file);
83
+ process.stdout.write(`ok: ${format} savedAt=${savedAt ?? '-'} objects=${objects.length} all valid\n`);
84
+ return;
85
+ }
86
+ fail(`unknown command "${command}"\n${usage}`);
87
+ }
88
+
89
+ main(process.argv.slice(2)).catch(error => {
90
+ const code = error?.code ?? 'ERROR';
91
+ const detail = error?.detail ? ` (${error.field}: ${error.detail})` : '';
92
+ fail(`${code}: ${error?.message ?? String(error)}${detail}`);
93
+ });
@@ -0,0 +1,25 @@
1
+ # Dependency inventory
2
+
3
+ Initial lock: Node >=22.16, native ESM; npm lockfile v3, exact direct versions.
4
+ No private registry, product tarball, vendored SDK or install script is required.
5
+
6
+ | Package | Version | License | Purpose |
7
+ | --- | --- | --- | --- |
8
+ | @modelcontextprotocol/server | 2.4.0 | Apache-2.0 | Official MCP server and stdio transport |
9
+ | @modelcontextprotocol/client | 2.4.0 | Apache-2.0 | Development: real handshake/client verification |
10
+ | @modelcontextprotocol/core | 2.4.0 | Apache-2.0 | SDK transitive protocol implementation |
11
+ | zod | 4.6.7 | MIT | MCP schemas |
12
+
13
+ Lockfile transitives: cross-spawn 7.0.6, eventsource-parser 3.1.1, eventsource 3.0.7,
14
+ jose 6.2.13, path-key 3.1.1, pkce-challenge 5.0.1, shebang-command 2.0.0,
15
+ shebang-regex 3.0.0 and which 2.0.2 (MIT); isexe 2.0.0 (ISC).
16
+ `npm run check` verifies installed versions/licenses, public registry integrity
17
+ entries, package inclusion boundaries, and credential-shaped/local-path content.
18
+ This is a bounded packaging check, not a comprehensive security audit.
19
+
20
+ SDK source: [official TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk).
21
+ SDK v2 is the current stable line; its own exported supported protocol versions
22
+ and actual negotiated test version belong in the verification report. Node's
23
+ built-in HTTP, crypto, filesystem and test runner provide the rest of the runtime.
24
+ Updates require lock review and the same interoperability suite. No npm publish
25
+ or production deployment has been authorized; package remains `private: true`.
@@ -0,0 +1,59 @@
1
+ # Host integration and authority
2
+
3
+ The host owns credential verification. HTTP `authenticate(req)` returns a trusted
4
+ identity object; the same object reaches `authorize({operation,identity,connection})`.
5
+ An MCP stdio process receives its identity from its launching host, never from a
6
+ tool argument. Sharing a bearer token intentionally shares the calling principal;
7
+ that token cannot prove which visitor sent a message.
8
+
9
+ The bundled CLI reads a private JSON policy and token values from named environment
10
+ variables. On every operation and result disclosure it reloads the policy. Removing
11
+ an identity/operation/connection grant denies subsequent operations, including late
12
+ responses. Unreadable or malformed policy denies access. Route edits are rejected
13
+ as `AUTHORITY_CHANGED`; start a new immutable connection id instead of rebinding
14
+ old task handles. Environment changes outside a running process do not rotate its
15
+ tokens: remove the identity from policy immediately, then restart with new secrets.
16
+
17
+ HTTP listens only on literal `127.0.0.1`. A separate ephemeral loopback control
18
+ socket implements CLI shutdown; its random control secret stays in the private
19
+ state directory. It is not a public administration endpoint. SIGINT/SIGTERM also
20
+ request shutdown. TLS, remote exposure, enterprise login, external identity claims,
21
+ rate limiting at an ingress, and production deployment remain host responsibilities.
22
+ The sample CLI is a local alpha harness, not an enterprise identity server.
23
+
24
+ ## TeamBot boundary
25
+
26
+ The independent TeamBot adapter is designed against a fixed publication endpoint.
27
+ The host supplies a token and an explicit operator binding to publication/bot id.
28
+ The publication check rejects mismatched ids and upstream authorization failures.
29
+ Withdrawal detection depends on the upstream rejecting withdrawn grants; ids alone
30
+ cannot attest publication lifecycle or ownership. It cannot prove
31
+ enterprise membership or enterprise ownership of a publication. No automatic
32
+ enterprise discovery or verification is advertised. Do not connect real enterprise
33
+ data until that separate acceptance gate has evidence.
34
+
35
+ An isolated test of the real enterprise HTTP service with synthetic accounts and
36
+ controlled model output verifies that integration only. Operator-pinning a URL
37
+ and checking a member online do not jointly prove the publication belongs to that
38
+ enterprise. Keep those evidence levels separate. A shared channel token also
39
+ shares authority: independent conversations are not per-visitor access control.
40
+
41
+ ## Recovery
42
+
43
+ The provider owns task state and output. The core's journal is a routing and retry
44
+ ledger, including private provider receipts. Protect it as service state and keep
45
+ both storage roots for recovery. An unknown submission is not a
46
+ failed task and is never automatically repeated as a new POST. Retain its returned
47
+ handle/request key and query the original request when the provider supports it.
48
+ TeamBot requires its server-issued receipt: if the response is lost before that
49
+ receipt is fsynced, the connector cannot query or cancel the task. It returns
50
+ outcome-unknown on the same handle without resubmitting; trusted operator
51
+ reconciliation is required. A recovery handle does not guarantee automatic
52
+ recovery. State-directory corruption or
53
+ an active writer lock must fail closed. On a single host, a stale lock is reclaimed only after the recorded PID is proven
54
+ absent, under a separate recovery guard. Live, reused, malformed or unknown owner
55
+ locks fail closed and require operator investigation. Do not delete such locks.
56
+
57
+ Alpha has no retention/garbage-collection automation, shared-volume multi-host
58
+ coordination, or automatic reconciliation that replays uncertain submissions.
59
+ A fixture's durability cannot certify another provider's storage guarantees.
@@ -0,0 +1,27 @@
1
+ # Sources and reuse policy
2
+
3
+ The bootstrap documentation is an original design proposal. It does not vendor product code, private repository history, SDK source or agent transcripts.
4
+
5
+ ## Standards to adopt or adapt
6
+
7
+ - [MCP architecture](https://modelcontextprotocol.io/docs/learn/architecture): protocol and SDK foundations for tool/resource connections. Exact implemented protocol and SDK versions will be pinned when implementation begins.
8
+ - [A2A and MCP](https://a2a-protocol.org/latest/topics/a2a-and-mcp/): complementary responsibilities for tools and independent agents.
9
+ - [A2A specification](https://a2a-protocol.org/latest/specification/): evaluate existing task and capability semantics before defining new ones.
10
+ - [AG-UI introduction](https://docs.ag-ui.com/introduction): event-based agent/application interaction, including channel clients. Its scope overlaps some connector scenarios; this must be considered during architecture review.
11
+ - [Knocket AI Agent tutorial](https://knocket.trtc.io/tutorials/ai-agent/): integration reference to revalidate against the actual account and current product. The documentation link does not constitute a working integration or confirmation of general Developer API / webhook / MCP availability.
12
+
13
+ Standards retain their respective ownership and licenses. Any implementation dependency must add its version, license, provenance and update policy here or in a dedicated dependency manifest.
14
+
15
+ ## Product adapters
16
+
17
+ TeamBot and OpenBot are intended providers. An adapter should use an explicitly documented interface and be independently implementable. Existing private implementations may inform interface verification in an authorized environment, but their source, bundled packages, credentials and development history are not automatically redistributable.
18
+
19
+ Before copying any existing code, record origin repository, exact revision, file paths, applicable license, retained notices, modifications and authorization to publish. If this cannot be established, implement the narrow adapter from the contract without copying that code.
20
+
21
+ ## Evidence
22
+
23
+ An actual agent response is required before naming that agent as a reviewer or implementer. Public decision summaries may record reasoning and accepted findings; raw transcripts and local execution receipts remain outside this repository when they contain private context.
24
+
25
+ ## Implementation dependencies
26
+
27
+ Exact dependency versions and licenses are recorded in [DEPENDENCIES.md](DEPENDENCIES.md) and package-lock.json. The SDK v2 stable line was checked against its official repository; Knocket documentation describes a custom Chat Completions endpoint but does not prove this strict subset will accept the platform's real default fields. Actual provider/channel verification remains separate.
@@ -0,0 +1,36 @@
1
+ # Support matrix
2
+
3
+ Updated: 2026-10-31. Alpha `0.1.0-alpha.1`, contract `anybot.connector/0.1`.
4
+
5
+ | Component | Implemented | Verified scope | Live platform |
6
+ | --- | --- | --- | --- |
7
+ | Core text invocation / authority / durable correlation | Yes | Concurrency, isolation, revocation, crash, storage failure | Host integration required |
8
+ | Deterministic reference provider | Yes | Durable same-key lookup, terminal facts, cancel, restart | No model calls |
9
+ | TeamBot provider | Yes | Synthetic contract + 26 actual isolated backend assertions | Real enterprise pending |
10
+ | HTTP binding | Yes | Bounded input, error mapping, same core, actual loopback requests | No public deployment |
11
+ | MCP binding | Yes | SDK 2.4.0, observed protocol 2025-11-25, official client and stdio | No remote OAuth / Streamable HTTP |
12
+ | Knocket text subset | Yes | Contract tests + 13 actual backend channel assertions | Knocket account pending |
13
+ | OpenBot-specific provider | Fixture skeleton | 10 adapter tests (idempotency, outcome-unknown non-replay, cancel, response validation) | Real local Bot API bridge pending |
14
+ | Status health probes (direct API / harness install check) | Yes | 20 tests: pinned response→state mapping over a 127.0.0.1 fixture server + real child-process harness checks; freshness TTL/stale helpers | Real accounts and paid probes not run; ready ≠ model-executable |
15
+ | Status snapshot store (`anybot.status/1`) | Yes | 12 tests incl. atomic rewrite, corrupt-file rejection, fail-closed registry restore | Host wiring pending |
16
+ | Status console CLI (`bin/anybot-status`) | Yes | Real child-process CLI tests: render/query/check, scope fail-closed exit 3, pagination, secret redaction via the authorized query path | Human-native UI acceptance still pending in OpenBot mainline |
17
+ | Independent third-party provider | No | None | Pending |
18
+ | A2A / AG-UI | No | None | Pending |
19
+ | Attachments / approvals / programmatic handoff | No | Explicit rejection | Pending |
20
+
21
+ Both providers expose describe/submit/get/cancel. Input is at most 20000 UTF-8
22
+ bytes; TeamBot additionally requires at most 6000 UTF-16 units, non-whitespace
23
+ text, and no NUL. The whole serialized channel history must fit. Cancellation is
24
+ request-and-observe; an acknowledgment or disconnected socket is not terminal
25
+ cancellation. All output is a complete text result, never token events.
26
+
27
+ Reference facts are retained without automatic expiry in its bounded durable
28
+ store. TeamBot retention/deduplication guarantees are not certified; the connector
29
+ journal prevents repeated POSTs. TeamBot needs the returned opaque receipt for
30
+ get/cancel. Missing receipt remains outcome-unknown, including after restart.
31
+ See [verification](VERIFICATION.md) and [bindings](../spec/0003-bindings.md).
32
+
33
+ Independent conversations do not establish visitor identities. Shared credentials
34
+ share authority unless a host supplies verified endUserRef values. Enterprise
35
+ publication ownership, actual Knocket request fields/retries, two real visitors,
36
+ and human handoff still require their own acceptance evidence.
@@ -0,0 +1,25 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "stateDir": "./state",
4
+ "port": 8790,
5
+ "identities": [
6
+ {
7
+ "principal": "demo",
8
+ "tokenEnv": "ANYBOT_TOKEN",
9
+ "connections": ["demo"],
10
+ "operations": ["describe", "submit", "get", "cancel"]
11
+ }
12
+ ],
13
+ "connections": [
14
+ {
15
+ "id": "demo",
16
+ "revision": "1",
17
+ "publication": "demo",
18
+ "grantId": "local",
19
+ "provider": { "type": "reference", "delayMs": 20 }
20
+ }
21
+ ],
22
+ "knocket": {
23
+ "models": { "demo": "demo" }
24
+ }
25
+ }
@@ -0,0 +1,81 @@
1
+ // Runnable example: HTTP binding of the connector contract.
2
+ //
3
+ // node examples/http-server.mjs
4
+ //
5
+ // What it shows: the host creates the connector service, plugs an
6
+ // authenticate() host callback into createHttpServer(), and binds the
7
+ // returned Node HTTP server (here on an ephemeral loopback port).
8
+ //
9
+ // Alpha limits enforced by the binding (published, narrow on purpose):
10
+ // - request bodies: at most 65536 bytes, content-type application/json
11
+ // - text input: nonempty, at most 20000 UTF-8 bytes
12
+ // - requestKey/conversationRef: [A-Za-z0-9_.:-]{1,128}
13
+ // - invocation has exactly { requestKey?, conversationRef?, input }
14
+ // - errors are { error: { code, message, retryable } }; unknown fields,
15
+ // routes and methods are rejected; no CORS headers
16
+ //
17
+ // Identity NEVER comes from the request body. This demo uses a per-run
18
+ // random in-process bearer credential mapped to ONE fixed demo principal:
19
+ // it exists only so the example is runnable, is never printed or persisted,
20
+ // and must not be copied into real deployments — those wire host-verified
21
+ // identity (mTLS, SSO, token introspection, ...) into authenticate().
22
+ // All data in this example is synthetic; the demo service is in-memory and
23
+ // non-durable, not for production use.
24
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
25
+ import { createHttpServer } from '../src/transports/http/index.mjs';
26
+ import { createDemoConnector } from './lib/demo-connector.mjs';
27
+
28
+ const connector = createDemoConnector();
29
+
30
+ // Fixture-only credential: random per run, kept in memory, never logged.
31
+ const DEMO_CREDENTIAL = randomBytes(24).toString('base64url');
32
+ const EXPECTED = Buffer.from(DEMO_CREDENTIAL);
33
+
34
+ async function authenticate(req) {
35
+ const authorization = req.headers.authorization;
36
+ if (typeof authorization !== 'string' || !authorization.startsWith('Bearer ')) return null;
37
+ const presented = Buffer.from(authorization.slice('Bearer '.length));
38
+ if (presented.length !== EXPECTED.length || !timingSafeEqual(presented, EXPECTED)) return null;
39
+ return { principal: 'demo' }; // one fixed demo principal for this run
40
+ }
41
+
42
+ const server = createHttpServer({ connector, authenticate });
43
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
44
+ const { port } = server.address();
45
+ const base = `http://127.0.0.1:${port}`;
46
+ console.log(`demo connector listening on ${base} (loopback only; bearer required)`);
47
+
48
+ async function call(method, path, body) {
49
+ const response = await fetch(`${base}${path}`, {
50
+ method,
51
+ headers: {
52
+ 'content-type': 'application/json',
53
+ authorization: `Bearer ${DEMO_CREDENTIAL}`,
54
+ },
55
+ body: body === undefined ? undefined : JSON.stringify(body),
56
+ });
57
+ return { status: response.status, body: await response.json() };
58
+ }
59
+
60
+ try {
61
+ console.log('describe ->', (await call('GET', '/v1/connections/demo')).body.operations);
62
+
63
+ const submitted = await call('POST', '/v1/connections/demo/tasks', {
64
+ requestKey: 'example-request-001',
65
+ input: { type: 'text', text: 'What are your support hours?' },
66
+ });
67
+ console.log('submit ->', submitted.body);
68
+
69
+ console.log('get ->', (await call('GET', `/v1/tasks/${submitted.body.handle}`)).body);
70
+
71
+ const denied = await fetch(`${base}/v1/connections/demo`);
72
+ console.log('missing bearer ->', denied.status, JSON.stringify(await denied.json()));
73
+
74
+ const wrong = await fetch(`${base}/v1/connections/demo`, {
75
+ headers: { authorization: 'Bearer not-the-demo-credential' },
76
+ });
77
+ console.log('wrong bearer ->', wrong.status, JSON.stringify(await wrong.json()));
78
+ } finally {
79
+ await new Promise((resolve) => server.close(resolve));
80
+ await connector.close();
81
+ }
@@ -0,0 +1,110 @@
1
+ // Runnable example: Knocket-compatible chat-completions channel (strict
2
+ // text subset) mounted on the HTTP server.
3
+ //
4
+ // node examples/knocket-channel.mjs
5
+ //
6
+ // What it shows: the host maps FIXED public model aliases to configured
7
+ // connection ids; createHttpServer() delegates POST /v1/chat/completions to
8
+ // the Knocket handler. The demo connector answers immediately, so no waiting
9
+ // is visible here.
10
+ //
11
+ // Accepted request body (exact fields): { model, messages, stream? } with
12
+ // stream only false; messages are 1..64 { role: 'user'|'assistant', content }
13
+ // entries with at least one user, each content nonempty and at most 20000
14
+ // UTF-8 bytes; the serialized history (including role labels) is at most
15
+ // 20000 UTF-8 bytes; the request body is at most 65536 bytes. Rejected with
16
+ // explicit errors: stream=true, tools, functions, system/developer messages,
17
+ // attachments, unknown parameters.
18
+ //
19
+ // Idempotency-Key header -> connector requestKey (1..128 chars of
20
+ // [A-Za-z0-9_.:-], empty or duplicate headers rejected); without it, every
21
+ // call is an independent conversation. On slow tasks the handler polls up to
22
+ // waitMs (default 5000ms) and then returns 504 WAIT_TIMEOUT with an
23
+ // authorized recovery handle; client disconnects stop polling without
24
+ // cancelling or resubmitting the task. Responses carry no usage fields and
25
+ // there is no token streaming.
26
+ //
27
+ // Identity NEVER comes from request bodies or message text. This demo uses a
28
+ // per-run random in-process bearer credential mapped to ONE fixed demo
29
+ // principal; it is never printed and must not be copied into real
30
+ // deployments. Live Knocket platform compatibility is UNVERIFIED; this is
31
+ // the documented contract subset only. All data is synthetic.
32
+ //
33
+ // A matching coordinator CLI configuration example (schemaVersion 1) lives
34
+ // at examples/cli-config.example.json; it validates against the real
35
+ // src/cli/config.mjs loader.
36
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
37
+ import { createHttpServer } from '../src/transports/http/index.mjs';
38
+ import { createKnocketHandler } from '../src/channels/knocket/index.mjs';
39
+ import { createDemoConnector } from './lib/demo-connector.mjs';
40
+
41
+ const connector = createDemoConnector();
42
+
43
+ // Fixed public alias -> configured connection id. The client never chooses
44
+ // the connection; it only names the alias.
45
+ const knocket = createKnocketHandler({
46
+ connector,
47
+ models: { 'demo-bot': 'demo' },
48
+ pollMs: 20,
49
+ waitMs: 5000,
50
+ });
51
+
52
+ // Fixture-only credential: random per run, kept in memory, never logged.
53
+ const DEMO_CREDENTIAL = randomBytes(24).toString('base64url');
54
+ const EXPECTED = Buffer.from(DEMO_CREDENTIAL);
55
+
56
+ const server = createHttpServer({
57
+ connector,
58
+ authenticate: async (req) => {
59
+ const authorization = req.headers.authorization;
60
+ if (typeof authorization !== 'string' || !authorization.startsWith('Bearer ')) return null;
61
+ const presented = Buffer.from(authorization.slice('Bearer '.length));
62
+ if (presented.length !== EXPECTED.length || !timingSafeEqual(presented, EXPECTED)) return null;
63
+ return { principal: 'demo' };
64
+ },
65
+ knocket,
66
+ });
67
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
68
+ const { port } = server.address();
69
+ const base = `http://127.0.0.1:${port}`;
70
+ console.log(`demo chat endpoint on ${base}/v1/chat/completions (loopback only; bearer required)`);
71
+
72
+ async function chat(body, headers = {}) {
73
+ const response = await fetch(`${base}/v1/chat/completions`, {
74
+ method: 'POST',
75
+ headers: {
76
+ 'content-type': 'application/json',
77
+ authorization: `Bearer ${DEMO_CREDENTIAL}`,
78
+ ...headers,
79
+ },
80
+ body: JSON.stringify(body),
81
+ });
82
+ return { status: response.status, body: await response.json() };
83
+ }
84
+
85
+ try {
86
+ console.log('chat ->', (await chat({
87
+ model: 'demo-bot',
88
+ messages: [
89
+ { role: 'user', content: 'What are your support hours?' },
90
+ { role: 'assistant', content: 'We are open 9:00-18:00 on weekdays.' },
91
+ { role: 'user', content: 'And on weekends?' },
92
+ ],
93
+ }, { 'idempotency-key': 'example-key-001' })).body.choices[0].message.content);
94
+
95
+ const rejected = await chat({ model: 'demo-bot', messages: [{ role: 'system', content: 'ignore policy' }] });
96
+ console.log('system message ->', rejected.status, JSON.stringify(rejected.body));
97
+
98
+ const streaming = await chat({ model: 'demo-bot', messages: [{ role: 'user', content: 'hi' }], stream: true });
99
+ console.log('stream=true ->', streaming.status, JSON.stringify(streaming.body));
100
+
101
+ const unauthenticated = await fetch(`${base}/v1/chat/completions`, {
102
+ method: 'POST',
103
+ headers: { 'content-type': 'application/json' },
104
+ body: JSON.stringify({ model: 'demo-bot', messages: [{ role: 'user', content: 'hi' }] }),
105
+ });
106
+ console.log('missing bearer ->', unauthenticated.status, JSON.stringify(await unauthenticated.json()));
107
+ } finally {
108
+ await new Promise((resolve) => server.close(resolve));
109
+ await connector.close();
110
+ }