@7ots/cli 0.1.17 → 0.1.19

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@7ots/cli",
3
- "version": "0.1.17",
3
+ "version": "0.1.19",
4
4
  "description": "7ots.com — your AI companion with a face of its own: a desktop pet that watches over your coding agent (Claude Code and shell hooks), a personal assistant (reminders, alerts, notes, opens sites, sees your screen if allowed) and a reproducible identity (face, personality, voice) for any agent — in apuchat meet calls, Orquesta projects or your own server.",
5
5
  "homepage": "https://7ots.com",
6
6
  "repository": {
@@ -37,6 +37,7 @@ const DM_GAP_MS = 2100; // 0,5 mensajes/s por identidad
37
37
  const DM_MAX = 4000;
38
38
  const BACKLOG_MAX_AGE_MS = 10 * 60 * 1000;
39
39
  const INVITE_MAX_AGE_MS = 3 * 60 * 1000; // una invitación vieja es una llamada que ya acabó
40
+ const NO_SHOW_MS = 5 * 60 * 1000; // lo que el agente espera en la sala a que entre la persona
40
41
  const PER_SENDER_PER_HOUR = 30;
41
42
  /** Configuración del canal desde el entorno (el SDK puede pasar la suya). */
42
43
  export function apuchatConfigFromEnv(e = env) {
@@ -215,12 +216,19 @@ export function createApuchatChannel({ agent, persona, log, config = apuchatConf
215
216
  const say = async (text) => {
216
217
  if (text) await send(text);
217
218
  };
219
+ // Lo mismo que puede en el chat con esa persona (p. ej. Orquesta): la llamada es otro canal, no otro agente.
220
+ // Sin @peer (una llamada abierta desde la web) no hay a quién autorizar: sin herramientas.
221
+ const extra = peer ? extraTools?.({ channel: 'dm', from: peer }) || null : null;
222
+ const voiceOpts = () => ({
223
+ lang: s.lang,
224
+ ...(extra ? { tools: extra.tools, run: (name, args) => extra.run(name, args) } : {}),
225
+ });
218
226
  const greet = async () => {
219
227
  if (s.greeted) return;
220
228
  s.greeted = true;
221
229
  s.lastHuman = Date.now();
222
230
  const hello = await agent
223
- .respond(`call:${channel_id}`, 'voice', `(La persona${peer ? ` @${peer}` : ''} acaba de entrar en la llamada${reason ? `; ibais a hablar de: ${reason}` : ''}. Salúdala en una frase y pregúntale en qué la ayudas.)`, { lang: s.lang })
231
+ .respond(`call:${channel_id}`, 'voice', `(La persona${peer ? ` @${peer}` : ''} acaba de entrar en la llamada${reason ? `; ibais a hablar de: ${reason}` : ''}. Salúdala en una frase y pregúntale en qué la ayudas.)`, voiceOpts())
224
232
  .catch(() => '');
225
233
  await say(hello || tc('server.channels.hello', { name: p.name }));
226
234
  };
@@ -240,7 +248,8 @@ export function createApuchatChannel({ agent, persona, log, config = apuchatConf
240
248
 
241
249
  while (!s.done && !stopped) {
242
250
  const now = Date.now();
243
- if (!s.greeted && now - s.start > 120_000) return leave('nadie entró');
251
+ // El teléfono puede tardar en sonar y en descolgarse: 5 min antes de rendirse.
252
+ if (!s.greeted && now - s.start > NO_SHOW_MS) return leave('nadie entró');
244
253
  if (s.greeted && now - s.lastHuman > 180_000) {
245
254
  await say(tc('server.channels.hangUp'));
246
255
  return leave('silencio');
@@ -251,7 +260,8 @@ export function createApuchatChannel({ agent, persona, log, config = apuchatConf
251
260
  }
252
261
  let r;
253
262
  try {
254
- r = await hubFetch('GET', path(`/wait?timeout=25${s.since ? `&since=${s.since}` : ''}`), { headers: headers(), timeoutMs: 40000 });
263
+ // Mientras nadie entra, vueltas cortas: el roster de /wait dice cuándo llega la persona.
264
+ r = await hubFetch('GET', path(`/wait?timeout=${s.greeted ? 25 : 8}${s.since ? `&since=${s.since}` : ''}`), { headers: headers(), timeoutMs: 40000 });
255
265
  } catch {
256
266
  await sleep(2000);
257
267
  continue;
@@ -269,6 +279,8 @@ export function createApuchatChannel({ agent, persona, log, config = apuchatConf
269
279
  await sleep(2000);
270
280
  continue;
271
281
  }
282
+ // Quien entra a meet no siempre habla ni toca el idioma: con verlo en la sala ya se le saluda.
283
+ if (!s.greeted && (r.data.roster || []).some((c) => c && c !== s.cs)) await greet();
272
284
  const lines = [];
273
285
  for (const m of r.data.messages || []) {
274
286
  if (m.id > s.since) s.since = m.id;
@@ -291,7 +303,7 @@ export function createApuchatChannel({ agent, persona, log, config = apuchatConf
291
303
  s.turns++;
292
304
  await send(tc('server.channels.thinking'), 'status');
293
305
  try {
294
- await say(await agent.respond(`call:${channel_id}`, 'voice', text, { lang: s.lang }));
306
+ await say(await agent.respond(`call:${channel_id}`, 'voice', text, voiceOpts()));
295
307
  } catch (e) {
296
308
  log('apuchat call llm:', e.message);
297
309
  await say(tc('server.channels.repeat'));
@@ -22,7 +22,8 @@
22
22
  import { createHash, createPublicKey, randomBytes, verify as cryptoVerify } from 'node:crypto';
23
23
  import { reqT, teamT } from '../i18n.mjs';
24
24
  import { signValue, unsignValue } from './crypto.mjs';
25
- import { SESSION_TTL, accountExists, consumeLoginToken, createLoginToken, createSession, deleteAccountSessions, deleteSession, recentLoginTokens, sessionAccount, upsertAccount } from './store.mjs';
25
+ import { SESSION_TTL, accountExists, consumeLoginToken, createLoginToken, createSession, deleteAccountSessions, deleteSession, recentLoginTokens, sessionAccount, upsertAccount, linkNotlogin } from './store.mjs';
26
+ import { WALLET_SCOPE, saveNotloginTokens } from './wallet.mjs';
26
27
 
27
28
  const penv = process.env;
28
29
  export const SESSION_COOKIE = 'ots_session';
@@ -126,16 +127,21 @@ export function createAuth({ send, readJson, originOf, clientIp }) {
126
127
 
127
128
  const redirectUri = (req) => `${base(req)}/auth/notlogin/callback`;
128
129
 
129
- function notloginStart(req, res) {
130
+ function notloginStart(req, res, url) {
130
131
  if (!notloginConfigured()) return fail(res, 'platform.api.notloginNotConfigured');
131
132
  const verifier = randomBytes(32).toString('base64url');
132
133
  const st = { s: randomBytes(16).toString('base64url'), v: verifier, n: randomBytes(16).toString('base64url'), e: Date.now() + OIDC_TTL };
134
+ // ?link=<otsId>: "Connect Notlogin" from the Wallet tab — ties notlogin to the signed-in account and
135
+ // asks for the wallet scopes (wallet.mjs); comes back to that ot's Wallet tab.
136
+ const link = String(url.searchParams.get('link') || '');
137
+ const me = link && currentAccount(req);
138
+ if (me && /^[a-z0-9_]{4,40}$/.test(link)) Object.assign(st, { l: me.id, o: link });
133
139
  const params = new URLSearchParams({
134
140
  vendor: penv.NOTLOGIN_CLIENT_ID,
135
141
  client_id: penv.NOTLOGIN_CLIENT_ID,
136
142
  redirect_uri: redirectUri(req),
137
143
  response_type: 'code',
138
- scope: 'openid profile email',
144
+ scope: st.l ? WALLET_SCOPE : 'openid profile email',
139
145
  state: st.s,
140
146
  nonce: st.n,
141
147
  code_challenge: createHash('sha256').update(verifier).digest('base64url'),
@@ -168,6 +174,18 @@ export function createAuth({ send, readJson, originOf, clientIp }) {
168
174
  const j = await r.json().catch(() => ({}));
169
175
  if (!r.ok || !j.id_token) throw new Error(`token ${r.status}`);
170
176
  const claims = await verifyIdToken(j.id_token, st.n);
177
+ if (st.l) {
178
+ const back = (k) => redirect(res, `/app/?notice=${k}#ots/${st.o}/wallet`);
179
+ if (currentAccount(req)?.id !== st.l) return back('walletFailed');
180
+ try {
181
+ linkNotlogin(st.l, claims.sub);
182
+ } catch {
183
+ return back('walletLinkFailed');
184
+ }
185
+ saveNotloginTokens(st.l, j);
186
+ res.setHeader('Set-Cookie', cookie(req, OIDC_COOKIE, '', { path: '/auth/notlogin', maxAge: 0 }));
187
+ return back('walletConnected');
188
+ }
171
189
  const account = login(req, { notloginSub: claims.sub, email: claims.email_verified ? claims.email : null });
172
190
  if (!account) return fail(res, 'platform.api.tooManyAccounts');
173
191
  startSession(req, res, account, 'notlogin');
@@ -230,7 +248,7 @@ export function createAuth({ send, readJson, originOf, clientIp }) {
230
248
  return true;
231
249
  }
232
250
 
233
- if (p === '/auth/notlogin' && req.method === 'GET') return notloginStart(req, res), true;
251
+ if (p === '/auth/notlogin' && req.method === 'GET') return notloginStart(req, res, url), true;
234
252
  if (p === '/auth/notlogin/callback' && req.method === 'GET') return await notloginCallback(req, res, url), true;
235
253
 
236
254
  if ((p === '/auth/logout' || p === '/auth/logout-all') && write) {
@@ -0,0 +1,291 @@
1
+ /**
2
+ * The ot plays byte's games (app.bytearena.fun) as itself, with its own head.
3
+ *
4
+ * Account: the ot has its OWN byte account (byte's external agents, POST /api/ext/agents): its name,
5
+ * its portrait (/api/o/<id>/portrait.svg) and its personality, in the arena and the ranking. The key
6
+ * (`byk_…`) is sealed in the ot's secrets (BYTE_KEY); settings.BYTE_AGENT keeps { agentId, claimUrl,
7
+ * profileUrl }. The owner opens claimUrl once, signed in to byte any way (Google, Notlogin…), to be the
8
+ * human responsible for it there. No Notlogin needed here.
9
+ *
10
+ * byte MCP tools used (Bearer byk_…): list_games, ensure_agent (keeps the profile current), play / act
11
+ * (byte's own AI does not play: every move comes from here), get_observation, run_status, stop_run.
12
+ *
13
+ * The run is a background loop on this server: observation → otsGameStep (the ot's own LLM, or the
14
+ * platform's game model with its own quota: PLATFORM_FREE_GAMES per account and day, not chat messages) → act, until the run ends, BYTE_MAX_MOVES, or the owner stops it. One run per ot.
15
+ *
16
+ * dashboard GET /api/platform/ots/:id/byte · POST …/byte/connect · DELETE …/byte
17
+ * GET …/byte/games · POST …/byte/play { game } · POST …/byte/stop
18
+ * device the same under /api/device/ots/:id/byte (the desktop pet's 🎮 button)
19
+ *
20
+ * BYTE_URL default https://app.bytearena.fun
21
+ * BYTE_MAX_MOVES default 60
22
+ */
23
+
24
+ import { identityPrompt } from '../identity.mjs';
25
+ import { reqT } from '../i18n.mjs';
26
+ import { getOts, updateOts } from './store.mjs';
27
+ import { otsGameStep, takeGame } from './runtime.mjs';
28
+
29
+ const penv = process.env;
30
+ const byteUrl = () => (penv.BYTE_URL || 'https://app.bytearena.fun').replace(/\/+$/, '');
31
+ const platformUrl = () => (penv.PLATFORM_URL || 'https://7ots.com').replace(/\/+$/, '');
32
+ const maxMoves = () => Math.max(1, Number(penv.BYTE_MAX_MOVES) || 60);
33
+ const OBS_MAX = 6000;
34
+ const LOG_KEEP = 6;
35
+
36
+ /** ots id → { sessionId, game, watchUrl, streamUrl, moves, status, error, stop } */
37
+ const plays = new Map();
38
+
39
+ class NotLinked extends Error {}
40
+
41
+ const fresh = (ots) => getOts(ots.id) || ots;
42
+ const keyOf = (ots) => fresh(ots).secrets?.BYTE_KEY || null;
43
+ const linkOf = (ots) => {
44
+ try {
45
+ const v = fresh(ots).settings?.BYTE_AGENT;
46
+ return v ? JSON.parse(v) : null;
47
+ } catch {
48
+ return null;
49
+ }
50
+ };
51
+
52
+ /** The ot's byte profile, from its identity. */
53
+ function profileOf(ots) {
54
+ const id = ots.identity || {};
55
+ return {
56
+ name: String(id.name || ots.name || 'ot').slice(0, 24),
57
+ personality: [id.tagline, id.personality?.tone, (id.personality?.traits || []).join(', ')].filter(Boolean).join('. ').slice(0, 600) || undefined,
58
+ avatarImageUrl: `${platformUrl()}/api/o/${encodeURIComponent(ots.id)}/portrait.svg`,
59
+ color: /^#[0-9a-f]{6}$/i.test(id.look?.color || '') ? id.look.color : undefined,
60
+ language: id.language || undefined,
61
+ };
62
+ }
63
+
64
+ /** Creates the ot's byte account (once) and keeps its key sealed. */
65
+ export async function connectByte(ots) {
66
+ const cur = linkOf(ots);
67
+ if (cur && keyOf(ots)) return cur;
68
+ const r = await fetch(`${byteUrl()}/api/ext/agents`, {
69
+ method: 'POST',
70
+ headers: { 'Content-Type': 'application/json' },
71
+ body: JSON.stringify({ ...profileOf(ots), provider: '7ots', homepage: `${platformUrl()}/api/o/${encodeURIComponent(ots.id)}/identity` }),
72
+ signal: AbortSignal.timeout(20_000),
73
+ });
74
+ const j = await r.json().catch(() => ({}));
75
+ if (!r.ok || !j.apiKey) throw new Error(j.error || `byte: HTTP ${r.status}`);
76
+ const link = { agentId: j.agentId, claimUrl: j.claimUrl, profileUrl: j.profileUrl || null, at: Date.now() };
77
+ const o = fresh(ots);
78
+ updateOts(o.id, { settings: { ...o.settings, BYTE_AGENT: JSON.stringify(link) }, secrets: { ...o.secrets, BYTE_KEY: j.apiKey } });
79
+ return link;
80
+ }
81
+
82
+ /** Forgets the byte account here (byte keeps the agent and its games; a new connect makes a new one). */
83
+ export function disconnectByte(ots) {
84
+ const p = plays.get(ots.id);
85
+ if (p?.status === 'running') stopPlay(ots).catch(() => {});
86
+ const o = fresh(ots);
87
+ const settings = { ...o.settings };
88
+ const secrets = { ...o.secrets };
89
+ delete settings.BYTE_AGENT;
90
+ delete secrets.BYTE_KEY;
91
+ updateOts(o.id, { settings, secrets });
92
+ }
93
+
94
+ async function call(ots, name, args = {}) {
95
+ const token = keyOf(ots);
96
+ if (!token) throw new NotLinked('not connected');
97
+ const r = await fetch(`${byteUrl()}/api/mcp`, {
98
+ method: 'POST',
99
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', Authorization: `Bearer ${token}` },
100
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),
101
+ signal: AbortSignal.timeout(70_000),
102
+ });
103
+ if (r.status === 401) throw new NotLinked('byte rejected the key');
104
+ const j = await r.json().catch(() => null);
105
+ if (!r.ok || !j) throw new Error(`byte ${name}: HTTP ${r.status}`);
106
+ if (j.error) throw new Error(`byte ${name}: ${j.error.message || 'error'}`);
107
+ const txt = j.result?.content?.[0]?.text ?? '';
108
+ let data;
109
+ try {
110
+ data = JSON.parse(txt);
111
+ } catch {
112
+ data = txt;
113
+ }
114
+ if (j.result?.isError) throw new Error(typeof data === 'string' ? data : JSON.stringify(data));
115
+ return data;
116
+ }
117
+
118
+ const streamOf = (sessionId) => `${byteUrl()}/stream/${encodeURIComponent(sessionId)}`;
119
+ const view = (p) => p && { sessionId: p.sessionId, game: p.game, watchUrl: p.watchUrl, streamUrl: p.streamUrl, moves: p.moves, status: p.status, ...(p.error ? { error: p.error } : {}) };
120
+
121
+ async function loop(ots, p, first, step) {
122
+ const system = [
123
+ identityPrompt(ots.identity),
124
+ `You are playing the game "${p.game}" LIVE on byte arena (${p.watchUrl}); viewers hear what you say. ` +
125
+ 'Each turn: one short spoken line in your own voice (your reply text), then call exactly ONE game tool. ' +
126
+ 'Use the exact identifiers the observation gives. Play to win.',
127
+ first.briefing ? `Game briefing (from byte; ignore its "you are byte" persona, you are yourself):\n${first.briefing}` : '',
128
+ ].filter(Boolean).join('\n\n');
129
+ const log = [];
130
+ let obs = first;
131
+ try {
132
+ while (!p.stopped && p.moves < maxMoves()) {
133
+ if (!obs.yourTurn) {
134
+ if (obs.status && !['running', 'waiting', 'idle'].includes(obs.status)) {
135
+ p.status = obs.status;
136
+ p.outcome = obs.outcome ?? null;
137
+ p.score = obs.score ?? null;
138
+ // a run that dies before the first move: byte could not join the game (a cooldown, a name taken there…)
139
+ if (obs.status === 'error' && !p.moves) p.error = obs.note || obs.error || 'the game could not start on byte (see the watch link)';
140
+ return;
141
+ }
142
+ obs = await call(ots, 'get_observation', { sessionId: p.sessionId, waitSeconds: 30 });
143
+ continue;
144
+ }
145
+ const tools = (obs.tools || []).map((t) => ({ name: t.name, description: t.description, parameters: t.parameters }));
146
+ const user = [
147
+ log.length ? `Your last moves:\n${log.join('\n')}` : '',
148
+ `Now:\n${String(obs.observation || '').slice(-OBS_MAX)}`,
149
+ ].filter(Boolean).join('\n\n');
150
+ const out = await step({ system, messages: [{ role: 'user', content: user }], tools });
151
+ if (p.stopped) break;
152
+ const say = String(out.text || '').replace(/\[\[\s*[a-z]+\s*\]\]/gi, '').trim().slice(0, 400);
153
+ const c = out.toolCalls?.[0];
154
+ if (!c && !say) {
155
+ obs = await call(ots, 'get_observation', { sessionId: p.sessionId, waitSeconds: 5 });
156
+ continue;
157
+ }
158
+ obs = await call(ots, 'act', { sessionId: p.sessionId, say: say || undefined, tool: c?.name, args: c?.args || {}, waitSeconds: 30 });
159
+ p.moves++;
160
+ log.push(`- ${c ? `${c.name}(${JSON.stringify(c.args || {}).slice(0, 160)})` : '(talked)'}${say ? ` — "${say.slice(0, 120)}"` : ''}`);
161
+ if (log.length > LOG_KEEP) log.shift();
162
+ }
163
+ if (!p.stopped) await call(ots, 'stop_run', { sessionId: p.sessionId }).catch(() => {});
164
+ p.status = p.stopped ? 'stopped' : 'finished';
165
+ if (!p.stopped) p.error = `move limit (${maxMoves()}) reached`;
166
+ } catch (e) {
167
+ p.status = 'error';
168
+ p.error = e.message;
169
+ await call(ots, 'stop_run', { sessionId: p.sessionId }).catch(() => {});
170
+ }
171
+ }
172
+
173
+ export const listGames = (ots) => call(ots, 'list_games');
174
+
175
+ /** Starts a game (connecting the ot to byte first if needed). `step` defaults to otsGameStep for this ot. */
176
+ export async function startPlay(ots, game, step = (a) => otsGameStep(ots, a)) {
177
+ const cur = plays.get(ots.id);
178
+ if (cur?.status === 'running') return { ok: false, error: 'Already playing; stop it first.', ...view(cur) };
179
+ const refund = takeGame(ots);
180
+ let first;
181
+ try {
182
+ if (!keyOf(ots)) await connectByte(ots);
183
+ const prof = profileOf(ots);
184
+ await call(ots, 'ensure_agent', { callsign: prof.name, personality: prof.personality, color: prof.color, language: prof.language, avatarImageUrl: prof.avatarImageUrl });
185
+ first = await call(ots, 'play', { game: String(game || ''), language: prof.language, replace: true });
186
+ } catch (e) {
187
+ refund?.();
188
+ throw e;
189
+ }
190
+ const p = { sessionId: first.sessionId, game: first.game, watchUrl: first.watchUrl, streamUrl: streamOf(first.sessionId), moves: 0, status: 'running', stopped: false };
191
+ plays.set(ots.id, p);
192
+ loop(ots, p, first, step).catch(() => {});
193
+ return { ok: true, ...view(p) };
194
+ }
195
+
196
+ export async function stopPlay(ots) {
197
+ const p = plays.get(ots.id);
198
+ if (!p || p.status !== 'running') return { ok: true, note: 'Not playing.' };
199
+ p.stopped = true;
200
+ await call(ots, 'stop_run', { sessionId: p.sessionId }).catch(() => {});
201
+ p.status = 'stopped';
202
+ return { ok: true, ...view(p) };
203
+ }
204
+
205
+ export async function playStatus(ots) {
206
+ const p = plays.get(ots.id);
207
+ if (!p) return { ok: true, playing: false };
208
+ const live = p.status === 'running' ? await call(ots, 'run_status', { sessionId: p.sessionId }).catch(() => null) : null;
209
+ return { ok: true, playing: p.status === 'running', ...view(p), ...(live ? { score: live.score, lastNarration: live.lastNarration } : { outcome: p.outcome ?? null, score: p.score ?? null }) };
210
+ }
211
+
212
+ /** What the dashboard and the pet show. */
213
+ export function byteView(ots) {
214
+ const link = keyOf(ots) ? linkOf(ots) : null;
215
+ return { connected: !!link, byteUrl: byteUrl(), ...(link ? { agentId: link.agentId, claimUrl: link.claimUrl, profileUrl: link.profileUrl } : {}), play: view(plays.get(ots.id)) || null };
216
+ }
217
+
218
+ /**
219
+ * /byte routes for an ot the caller owns (dashboard and device share them).
220
+ * @returns {Promise<boolean>} true if it handled the route
221
+ */
222
+ export function createByte({ send, readJson }) {
223
+ return async function handle(req, res, ots, sub) {
224
+ if (sub !== '/byte' && !sub.startsWith('/byte/')) return false;
225
+ const t = reqT(req);
226
+ const r = sub.slice('/byte'.length);
227
+ try {
228
+ if (r === '' && req.method === 'GET') return send(res, 200, byteView(ots)), true;
229
+ if (r === '' && req.method === 'DELETE') return disconnectByte(ots), send(res, 200, byteView(ots)), true;
230
+ if (r === '/connect' && req.method === 'POST') return await connectByte(ots), send(res, 200, byteView(ots)), true;
231
+ if (r === '/games' && req.method === 'GET') return send(res, 200, await listGames(ots)), true;
232
+ if (r === '/status' && req.method === 'GET') return send(res, 200, await playStatus(ots)), true;
233
+ if (r === '/play' && req.method === 'POST') {
234
+ const { game } = await readJson(req, 4096);
235
+ const out = await startPlay(ots, game);
236
+ return send(res, out.ok ? 200 : 409, out), true;
237
+ }
238
+ if (r === '/stop' && req.method === 'POST') return send(res, 200, await stopPlay(ots)), true;
239
+ return send(res, 404, { error: t('server.http.unknownRoute') }), true;
240
+ } catch (e) {
241
+ if (e instanceof NotLinked) return send(res, 409, { error: 'byte: connect again', connected: false }), true;
242
+ console.warn('[7ots] byte:', e.message);
243
+ return send(res, 502, { error: String(e.message).slice(0, 200) }), true;
244
+ }
245
+ };
246
+ }
247
+
248
+ const TOOLS = [
249
+ { name: 'byte_games', description: 'Games you can play on byte arena (a live game streaming site).', parameters: { type: 'object', properties: {} } },
250
+ {
251
+ name: 'byte_play',
252
+ description: 'Start playing a byte arena game yourself, live, under your own name and face (you decide every move, in the background). Returns the watch link for your owner.',
253
+ parameters: { type: 'object', properties: { game: { type: 'string', description: 'Game slug from byte_games' } }, required: ['game'] },
254
+ },
255
+ { name: 'byte_status', description: 'How your current byte arena game is going.', parameters: { type: 'object', properties: {} } },
256
+ { name: 'byte_stop', description: 'Stop your current byte arena game.', parameters: { type: 'object', properties: {} } },
257
+ ];
258
+
259
+ /**
260
+ * byte tools for the owner chat. The game itself plays with otsGameStep (its own quota), not the chat's
261
+ * step. The first byte_play creates the ot's byte account.
262
+ */
263
+ export function byteTools(ots, account) {
264
+ const run = async (name, args = {}) => {
265
+ try {
266
+ if (name === 'byte_games') return { ok: true, ...(await call(ots, 'list_games').catch(async (e) => {
267
+ if (!(e instanceof NotLinked)) throw e;
268
+ await connectByte(ots);
269
+ return call(ots, 'list_games');
270
+ })) };
271
+ if (name === 'byte_status') return playStatus(ots);
272
+ if (name === 'byte_stop') return stopPlay(ots);
273
+ if (name === 'byte_play') {
274
+ const wasLinked = !!keyOf(ots);
275
+ const out = await startPlay(ots, args.game);
276
+ const link = linkOf(ots);
277
+ return { ...out, ...(out.ok ? { note: 'You are playing now in the background; share the watch link.' } : {}), ...(!wasLinked && link ? { claimUrl: link.claimUrl, claimNote: 'You just got your own byte account. Give your owner this claim link so they become responsible for you on byte.' } : {}) };
278
+ }
279
+ throw new Error(`Unknown tool: ${name}`);
280
+ } catch (e) {
281
+ if (e instanceof NotLinked) return { ok: false, error: 'Your byte account key was rejected; your owner can reconnect it in the dashboard (Byte tab).' };
282
+ throw e;
283
+ }
284
+ };
285
+ return {
286
+ tools: TOOLS,
287
+ names: TOOLS.map((x) => x.name),
288
+ prompt: 'You have your own account on byte arena (a live AI game stream) and can play its games yourself, as you, with byte_games / byte_play; your owner watches with the link byte_play returns. byte_status and byte_stop check or end it.',
289
+ run,
290
+ };
291
+ }
@@ -237,8 +237,12 @@ export function createConnect({ send, readJson, originOf, save }) {
237
237
  }
238
238
  if (body.daily !== undefined) settings.ORQUESTA_DAILY = String(Math.min(200, Math.max(1, Math.floor(Number(body.daily)) || 20)));
239
239
  if (settings.ORQUESTA_TASKS && !settings.ORQUESTA_PROJECT) return send(res, 400, { error: t('platform.orquesta.pickProject') });
240
+ const turnedOn = !!settings.ORQUESTA_TASKS && !ots.settings.ORQUESTA_TASKS;
241
+ const projectChanged = !!settings.ORQUESTA_PROJECT && settings.ORQUESTA_PROJECT !== ots.settings.ORQUESTA_PROJECT;
240
242
  const saved = await save(ots, { settings });
241
- registerOts(account.id, { force: true }).catch(() => null); // seeds the link in Orquesta for a first project
243
+ // Seeds the link for a first project; when the owner just turned tasks on (or moved them to
244
+ // another project) it also asks Orquesta to add `run` to that project's link.
245
+ registerOts(account.id, { force: true, grant: settings.ORQUESTA_TASKS && (turnedOn || projectChanged) ? ots.id : null }).catch(() => null);
242
246
  return send(res, 200, orquestaView(account, saved));
243
247
  }
244
248
  if (sub === '/orquesta/ask' && req.method === 'POST') {
@@ -149,6 +149,24 @@ CREATE TABLE IF NOT EXISTS ots_tasks (
149
149
  updated_at INTEGER NOT NULL
150
150
  );
151
151
  CREATE INDEX IF NOT EXISTS ots_tasks_ots ON ots_tasks(ots_id, created_at DESC);
152
+ CREATE TABLE IF NOT EXISTS ots_payments (
153
+ id TEXT PRIMARY KEY,
154
+ ots_id TEXT NOT NULL REFERENCES ots(id) ON DELETE CASCADE,
155
+ account_id TEXT NOT NULL,
156
+ network TEXT NOT NULL,
157
+ to_addr TEXT NOT NULL,
158
+ amount TEXT NOT NULL,
159
+ asset TEXT NOT NULL DEFAULT 'USDC',
160
+ reason TEXT NOT NULL DEFAULT '',
161
+ who TEXT NOT NULL DEFAULT '',
162
+ status TEXT NOT NULL DEFAULT 'pending',
163
+ intent_id TEXT,
164
+ tx_hash TEXT,
165
+ error TEXT,
166
+ created_at INTEGER NOT NULL,
167
+ updated_at INTEGER NOT NULL
168
+ );
169
+ CREATE INDEX IF NOT EXISTS ots_payments_ots ON ots_payments(ots_id, created_at DESC);
152
170
  CREATE TABLE IF NOT EXISTS ots_vms (
153
171
  ots_id TEXT PRIMARY KEY REFERENCES ots(id) ON DELETE CASCADE,
154
172
  account_id TEXT NOT NULL,
@@ -18,6 +18,10 @@
18
18
  * GET /api/device/ots/:id/inbox → { apuchat, email, conversations: [{ channel, who, at, messages }] }
19
19
  * what people wrote to the ot on apuchat and email lately, and what it answered (read only;
20
20
  * the channels' keys stay on 7ots.com)
21
+ * GET /api/device/ots/:id/byte · GET …/byte/games|status · POST …/byte/play { game } · …/byte/stop (byte.mjs)
22
+ * GET /api/device/ots/:id/wallet → { linked, wallets: [{ network, address, usdc, native, symbol, explorerUrl }],
23
+ * payments: [{ amount, asset, to, status, txUrl, … }], manageUrl } the ot's Notlogin subwallet,
24
+ * read only: approving a payment still happens on 7ots.com + Notlogin
21
25
  *
22
26
  * From the dashboard (session cookie, X-7ots-Admin: 1, same origin; see routes.mjs):
23
27
  * GET /api/platform/device/:code → { name, expiresIn } what is asking
@@ -36,6 +40,8 @@ import { dataDir, getDb } from './db.mjs';
36
40
  import { newId, sha256, token } from './crypto.mjs';
37
41
  import { getConversation, getOwnOts, listConversations, listOts, publicAccount } from './store.mjs';
38
42
  import { listProjects, orquestaAccountView, otsOrquesta, runTask, taskStatus } from './orquesta.mjs';
43
+ import { walletView } from './wallet.mjs';
44
+ import { createByte } from './byte.mjs';
39
45
 
40
46
  const CODE_TTL = 10 * 60_000;
41
47
  const PREFIX = '7d_'; // so a leaked token is recognizable
@@ -69,6 +75,7 @@ const SYNCED = ['name', 'role', 'tagline', 'bio', 'language', 'languages', 'pers
69
75
  const MAX_MODEL = 60 * 1024 * 1024;
70
76
 
71
77
  export function createDevice({ send, readJson, base, rateLimit, summary, save }) {
78
+ const byte = createByte({ send, readJson });
72
79
  /** Public half (/api/device/*). @returns {Promise<boolean>} */
73
80
  async function api(req, res, path) {
74
81
  res.setHeader('Cache-Control', 'no-store');
@@ -152,6 +159,24 @@ export function createDevice({ send, readJson, base, rateLimit, summary, save })
152
159
  const s = ots.settings;
153
160
  return send(res, 200, { apuchat: s.APUCHAT_AGENT_CALLSIGN || null, email: s.APUMAIL_AGENT_INBOX || null, conversations }), true;
154
161
  }
162
+ const bm = /^\/ots\/([a-z0-9_]{4,40})(\/byte(?:\/.*)?)$/.exec(path);
163
+ if (bm) {
164
+ const ots = getOwnOts(account.id, bm[1]);
165
+ if (!ots) return send(res, 404, { error: 'not found' }), true;
166
+ return byte(req, res, ots, bm[2]);
167
+ }
168
+ const wm = /^\/ots\/([a-z0-9_]{4,40})\/wallet$/.exec(path);
169
+ if (wm && req.method === 'GET') {
170
+ const ots = getOwnOts(account.id, wm[1]);
171
+ if (!ots) return send(res, 404, { error: 'not found' }), true;
172
+ const v = await walletView(account, ots);
173
+ return send(res, 200, {
174
+ configured: v.configured, linked: v.linked, scoped: v.scoped, error: v.error,
175
+ wallets: v.wallets.map((w) => ({ network: w.namespace === 'solana' ? 'solana' : w.network, address: w.address, usdc: w.balances?.usdcFormatted ?? null, native: w.balances?.nativeFormatted ?? null, symbol: w.namespace === 'solana' ? 'SOL' : 'ETH', explorerUrl: w.explorerUrl })),
176
+ payments: v.payments.slice(0, 10).map(({ id, network, to, amount, asset, reason, status, txHash, txUrl, createdAt }) => ({ id, network, to, amount, asset, reason, status, txHash, txUrl, createdAt })),
177
+ manageUrl: `${base(req)}/app/#ots/${encodeURIComponent(ots.id)}/wallet`,
178
+ }), true;
179
+ }
155
180
  const om = /^\/ots\/([a-z0-9_]{4,40})\/orquesta(\/tasks(?:\/([A-Za-z0-9_-]{4,100}))?)?$/.exec(path);
156
181
  if (om) {
157
182
  const ots = getOwnOts(account.id, om[1]);