@celljs/ta-harness 4.5.0 → 4.6.0

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 (70) hide show
  1. package/README.md +6 -5
  2. package/esm/node/brand-extension.js +2 -2
  3. package/esm/node/bug-report.js +2 -2
  4. package/esm/node/extensions.js +1 -1
  5. package/esm/node/index.d.ts +2 -0
  6. package/esm/node/index.js +2 -0
  7. package/esm/node/index.js.map +1 -1
  8. package/esm/node/pi-types.d.ts +1 -0
  9. package/esm/node/serve-state.d.ts +18 -0
  10. package/esm/node/serve-state.js +44 -0
  11. package/esm/node/serve-state.js.map +1 -0
  12. package/esm/node/ta-brand.d.ts +2 -0
  13. package/esm/node/ta-brand.js +12 -0
  14. package/esm/node/ta-brand.js.map +1 -1
  15. package/esm/node/ta-cli.js +152 -6
  16. package/esm/node/ta-cli.js.map +1 -1
  17. package/esm/node/ta-header.js +3 -3
  18. package/esm/node/ta-packages.d.ts +67 -0
  19. package/esm/node/ta-packages.js +173 -0
  20. package/esm/node/ta-packages.js.map +1 -0
  21. package/lib/node/brand-extension.js +2 -2
  22. package/lib/node/brand-extension.spec.js +3 -3
  23. package/lib/node/bug-report.js +2 -2
  24. package/lib/node/extensions.js +1 -1
  25. package/lib/node/index.d.ts +2 -0
  26. package/lib/node/index.d.ts.map +1 -1
  27. package/lib/node/index.js +2 -0
  28. package/lib/node/index.js.map +1 -1
  29. package/lib/node/pi-types.d.ts +1 -0
  30. package/lib/node/pi-types.d.ts.map +1 -1
  31. package/lib/node/serve-state.d.ts +19 -0
  32. package/lib/node/serve-state.d.ts.map +1 -0
  33. package/lib/node/serve-state.js +47 -0
  34. package/lib/node/serve-state.js.map +1 -0
  35. package/lib/node/serve-state.spec.d.ts +2 -0
  36. package/lib/node/serve-state.spec.d.ts.map +1 -0
  37. package/lib/node/serve-state.spec.js +35 -0
  38. package/lib/node/serve-state.spec.js.map +1 -0
  39. package/lib/node/ta-brand.d.ts +2 -0
  40. package/lib/node/ta-brand.d.ts.map +1 -1
  41. package/lib/node/ta-brand.js +12 -0
  42. package/lib/node/ta-brand.js.map +1 -1
  43. package/lib/node/ta-cli.d.ts.map +1 -1
  44. package/lib/node/ta-cli.js +152 -6
  45. package/lib/node/ta-cli.js.map +1 -1
  46. package/lib/node/ta-header.js +3 -3
  47. package/lib/node/ta-header.spec.js +2 -2
  48. package/lib/node/ta-packages.d.ts +68 -0
  49. package/lib/node/ta-packages.d.ts.map +1 -0
  50. package/lib/node/ta-packages.js +172 -0
  51. package/lib/node/ta-packages.js.map +1 -0
  52. package/lib/node/ta-packages.spec.d.ts +2 -0
  53. package/lib/node/ta-packages.spec.d.ts.map +1 -0
  54. package/lib/node/ta-packages.spec.js +89 -0
  55. package/lib/node/ta-packages.spec.js.map +1 -0
  56. package/package.json +5 -4
  57. package/src/node/brand-extension.spec.ts +3 -3
  58. package/src/node/brand-extension.ts +2 -2
  59. package/src/node/bug-report.ts +2 -2
  60. package/src/node/extensions.ts +1 -1
  61. package/src/node/index.ts +2 -0
  62. package/src/node/pi-types.ts +1 -0
  63. package/src/node/serve-state.spec.ts +36 -0
  64. package/src/node/serve-state.ts +51 -0
  65. package/src/node/ta-brand.ts +10 -0
  66. package/src/node/ta-cli.ts +155 -6
  67. package/src/node/ta-header.spec.ts +2 -2
  68. package/src/node/ta-header.ts +3 -3
  69. package/src/node/ta-packages.spec.ts +95 -0
  70. package/src/node/ta-packages.ts +200 -0
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@celljs/ta-harness",
3
- "version": "4.5.0",
4
- "description": "The agent runtime of ta on pi: branding, session locks and execution environment adapters",
3
+ "version": "4.6.0",
4
+ "description": "The agent runtime of Ta on pi: branding, session locks and execution environment adapters",
5
5
  "homepage": "https://github.com/cellbang/cell",
6
6
  "bugs": {
7
7
  "url": "https://github.com/cellbang/cell/issues"
@@ -28,8 +28,9 @@
28
28
  "watch": "tsc -b -w --preserveWatchOutput"
29
29
  },
30
30
  "dependencies": {
31
- "@celljs/ai-coding-agent": "4.5.0",
32
- "@celljs/ta-exec": "4.5.0",
31
+ "@celljs/ai-coding-agent": "4.6.0",
32
+ "@celljs/ta-exec": "4.6.0",
33
+ "@celljs/ta-relay": "4.6.0",
33
34
  "@earendil-works/pi-coding-agent": "^1.5.0",
34
35
  "@earendil-works/pi-mcp": "^1.5.0"
35
36
  },
@@ -48,8 +48,8 @@ describe('BrandExtension', () => {
48
48
  await commands.get('bug')!.handler('it crashed', { model: { provider: 'fake', id: 'm1' }, ui: { notify: (text: string) => notes.push(text) } });
49
49
  const url = new URL(notes[0].slice(notes[0].indexOf('https://')));
50
50
  expect(url.origin + url.pathname).toBe(BugReport.ISSUES_URL);
51
- expect(url.searchParams.get('title')).toBe('[ta] it crashed');
52
- expect(url.searchParams.get('body')).toContain('- ta 9.9.9');
51
+ expect(url.searchParams.get('title')).toBe('[Ta] it crashed');
52
+ expect(url.searchParams.get('body')).toContain('- Ta 9.9.9');
53
53
  expect(url.searchParams.get('body')).toContain('- model: fake/m1');
54
54
  });
55
55
  });
@@ -57,7 +57,7 @@ describe('BrandExtension', () => {
57
57
  describe('BugReport', () => {
58
58
  it('leaves a placeholder when the user wrote nothing', () => {
59
59
  const url = new URL(BugReport.issueUrl('', { version: '1.0.0', platform: 'linux x64', node: '24.0.0' }));
60
- expect(url.searchParams.get('title')).toBe('[ta] Describe the bug');
60
+ expect(url.searchParams.get('title')).toBe('[Ta] Describe the bug');
61
61
  expect(url.searchParams.get('body')).toContain('- model: none');
62
62
  });
63
63
  });
@@ -21,7 +21,7 @@ export class BrandExtension implements TaExtension {
21
21
  }
22
22
  });
23
23
  pi.registerCommand('bug', {
24
- description: 'Open an issue for ta on GitHub',
24
+ description: 'Open an issue for Ta on GitHub',
25
25
  handler: async (args, ctx) => {
26
26
  const url = BugReport.issueUrl(args, BugReport.currentEnvironment(this.sdk.VERSION, ctx.model));
27
27
  // In the terminal UI the browser is on this machine; a client of ta serve shows the link itself.
@@ -29,7 +29,7 @@ export class BrandExtension implements TaExtension {
29
29
  BugReport.open(url);
30
30
  }
31
31
  ctx.ui.notify(
32
- `A new issue for ta, with its version, the model and the platform and nothing else, opens in the browser. If it did not:\n${url}`,
32
+ `A new issue for Ta, with its version, the model and the platform and nothing else, opens in the browser. If it did not:\n${url}`,
33
33
  'info',
34
34
  );
35
35
  },
@@ -15,7 +15,7 @@ export namespace BugReport {
15
15
  /** A new issue on GitHub, filled in with the description and the environment. */
16
16
  export function issueUrl(description: string, environment: BugReportEnvironment): string {
17
17
  const url = new URL(ISSUES_URL);
18
- url.searchParams.set('title', `[ta] ${description.trim() || 'Describe the bug'}`);
18
+ url.searchParams.set('title', `[Ta] ${description.trim() || 'Describe the bug'}`);
19
19
  url.searchParams.set('labels', 'ta');
20
20
  url.searchParams.set(
21
21
  'body',
@@ -26,7 +26,7 @@ export namespace BugReport {
26
26
  '',
27
27
  '## Environment',
28
28
  '',
29
- `- ta ${environment.version}`,
29
+ `- Ta ${environment.version}`,
30
30
  `- model: ${environment.model ?? 'none'}`,
31
31
  `- ${environment.platform}, Node.js ${environment.node}`,
32
32
  ].join('\n'),
@@ -57,7 +57,7 @@ export class SessionLockExtension implements TaExtension {
57
57
  * can only end the process. `ctx.shutdown` restores the terminal; print modes do not act on it.
58
58
  */
59
59
  protected refuse(file: string, ctx: ExtensionContext): void {
60
- const message = `This session is open in another ta process. If that process is gone, delete ${this.lock.path(file)}.`;
60
+ const message = `This session is open in another Ta process. If that process is gone, delete ${this.lock.path(file)}.`;
61
61
  if (ctx.mode === 'tui') {
62
62
  ctx.ui.notify(message, 'error');
63
63
  ctx.shutdown();
package/src/node/index.ts CHANGED
@@ -7,7 +7,9 @@ export * from './exec-operations';
7
7
  export * from './extensions';
8
8
  export * from './glob-util';
9
9
  export * from './pi-types';
10
+ export * from './serve-state';
10
11
  export * from './session-lock';
11
12
  export * from './ta-brand';
12
13
  export * from './ta-cli';
13
14
  export * from './ta-header';
15
+ export * from './ta-packages';
@@ -3,6 +3,7 @@ export type { PiSdk } from '@celljs/ai-coding-agent/lib/node/pi/pi-sdk-util';
3
3
 
4
4
  export type ExtensionAPI = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ExtensionAPI;
5
5
  export type ExtensionContext = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ExtensionContext;
6
+ export type LoadExtensionsResult = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).LoadExtensionsResult;
6
7
  export type InlineExtension = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).InlineExtension;
7
8
  export type BashOperations = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).BashOperations;
8
9
  export type ReadOperations = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ReadOperations;
@@ -0,0 +1,36 @@
1
+ import { afterAll, describe, expect, it } from 'bun:test';
2
+ import { mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
+ import { createServer } from 'node:net';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { TaServeStateUtil } from './serve-state';
7
+
8
+ describe('TaServeStateUtil', () => {
9
+ const dir = mkdtempSync(join(tmpdir(), 'ta-serve-state-'));
10
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
11
+
12
+ it('keeps the port and the token in a file only this user reads', () => {
13
+ const file = join(dir, 'agent', TaServeStateUtil.FILE);
14
+ TaServeStateUtil.write({ port: 4100, token: 'secret' }, file);
15
+ expect(TaServeStateUtil.read(file)).toEqual({ port: 4100, token: 'secret' });
16
+ expect(statSync(file).mode & 0o777).toBe(0o600);
17
+ });
18
+
19
+ it('reads nothing from a missing or broken file', () => {
20
+ expect(TaServeStateUtil.read(join(dir, 'missing.json'))).toEqual({});
21
+ const broken = join(dir, 'broken.json');
22
+ writeFileSync(broken, 'not json');
23
+ expect(TaServeStateUtil.read(broken)).toEqual({});
24
+ writeFileSync(broken, JSON.stringify({ port: 70000, token: '' }));
25
+ expect(TaServeStateUtil.read(broken)).toEqual({ port: undefined, token: undefined });
26
+ });
27
+
28
+ it('knows whether a port is taken', async () => {
29
+ const server = createServer();
30
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
31
+ const { port } = server.address() as { port: number };
32
+ expect(await TaServeStateUtil.isFree(port, '127.0.0.1')).toBe(false);
33
+ await new Promise(resolve => server.close(resolve));
34
+ expect(await TaServeStateUtil.isFree(port, '127.0.0.1')).toBe(true);
35
+ });
36
+ });
@@ -0,0 +1,51 @@
1
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { createServer } from 'node:net';
3
+ import { dirname, join } from 'node:path';
4
+ import { TaBrand } from './ta-brand';
5
+
6
+ /**
7
+ * What `ta serve` keeps across restarts: its port and its token. A web app installed from it (a PWA)
8
+ * belongs to one address, and remembers the token it signed in with; both must stay the same.
9
+ */
10
+ export interface TaServeState {
11
+ port?: number;
12
+ token?: string;
13
+ }
14
+
15
+ export namespace TaServeStateUtil {
16
+ /** In the agent directory, readable only by this user, like serve.json. Removing it gives a new token. */
17
+ export const FILE = 'serve-state.json';
18
+
19
+ export function file(agentDir = TaBrand.agentDir()): string {
20
+ return join(agentDir, FILE);
21
+ }
22
+
23
+ /** Nothing when the file is missing or is not what {@link write} wrote. */
24
+ export function read(path = file()): TaServeState {
25
+ try {
26
+ const { port, token } = JSON.parse(readFileSync(path, 'utf8')) as TaServeState;
27
+ return {
28
+ port: typeof port === 'number' && Number.isInteger(port) && port > 0 && port < 65536 ? port : undefined,
29
+ token: typeof token === 'string' && token.length > 0 ? token : undefined,
30
+ };
31
+ } catch {
32
+ return {};
33
+ }
34
+ }
35
+
36
+ export function write(state: TaServeState, path = file()): void {
37
+ mkdirSync(dirname(path), { recursive: true });
38
+ writeFileSync(path, JSON.stringify(state), { mode: 0o600 });
39
+ // The mode above only applies to a new file.
40
+ chmodSync(path, 0o600);
41
+ }
42
+
43
+ /** Whether a server could listen on `port` of `host` now. */
44
+ export function isFree(port: number, host: string): Promise<boolean> {
45
+ return new Promise(resolve => {
46
+ const server = createServer();
47
+ server.once('error', () => resolve(false));
48
+ server.listen(port, host, () => server.close(() => resolve(true)));
49
+ });
50
+ }
51
+ }
@@ -1,3 +1,4 @@
1
+ import { readFileSync } from 'node:fs';
1
2
  import { homedir } from 'node:os';
2
3
  import { join } from 'node:path';
3
4
 
@@ -17,6 +18,15 @@ export namespace TaBrand {
17
18
  return process.env.TA_CODING_AGENT_DIR ?? join(homedir(), '.ta', 'agent');
18
19
  }
19
20
 
21
+ /** The version of ta, from the package.json that {@link activate} named. */
22
+ export function version(): string {
23
+ try {
24
+ return JSON.parse(readFileSync(join(process.env.PI_PACKAGE_DIR ?? '', 'package.json'), 'utf8')).version ?? 'unknown';
25
+ } catch {
26
+ return 'unknown';
27
+ }
28
+ }
29
+
20
30
  /**
21
31
  * Makes pi `ta`: its name, `~/.ta/agent`, project `.ta/` and `TA_CODING_AGENT_DIR` come from the
22
32
  * `piConfig` of the package.json in `brandDir`, next to pi's assets and ta's patched build of pi
@@ -1,22 +1,59 @@
1
+ import { randomBytes } from 'node:crypto';
1
2
  import { parseArgs } from 'node:util';
2
3
  import { PiBundleUtil } from '@celljs/ai-coding-agent/lib/node/pi/pi-bundle-util';
3
4
  import { BrandExtension } from './brand-extension';
4
5
  import { SessionLockExtension, TaExtensionUtil } from './extensions';
5
6
  import type { PiSdk } from './pi-types';
7
+ import { TaServeStateUtil } from './serve-state';
6
8
  import { SessionLock } from './session-lock';
7
9
  import { TaBrand } from './ta-brand';
10
+ import { TaPackages } from './ta-packages';
8
11
 
9
- const SERVE_HELP = `Usage: ta serve [--host <host>] [--port <port>]
12
+ const SERVE_HELP = `Usage: ta serve [--host <host>] [--port <port>] [--web] [--exec <url>]
10
13
 
11
- Serves pi sessions over WebSocket to any number of clients. Stops on SIGINT or SIGTERM.
14
+ Serves ta sessions over WebSocket to any number of clients, and the web client. Stops on SIGINT or SIGTERM.
12
15
 
13
16
  --host Address to listen on. Default: 127.0.0.1
14
- --port Port to listen on. Default: a free port
17
+ --port Port to listen on. Default: the port of the last start if it is free, so that a web app
18
+ installed from it finds it again; otherwise a free port
19
+ --web Open the web client in the browser
20
+ --exec Run the sessions' commands and file operations on a ta exec-server; TA_EXEC_TOKEN is its token
15
21
 
16
- The URL and the access token are written to serve.json in the agent directory.
22
+ The URL and the access token are written to serve.json in the agent directory. The token stays the
23
+ same across restarts (serve-state.json there; remove it for a new token and port).
17
24
  Set TA_SERVE_TOKEN to choose the token.
18
25
  `;
19
26
 
27
+ const EXEC_SERVER_HELP = `Usage: ta exec-server [--host <host>] [--port <port>] [--cwd <dir>]
28
+
29
+ Runs the commands and file operations of the sessions of a ta serve on this machine, for example a
30
+ container or a sandbox, while the agent runs elsewhere: ta serve --exec <url>. Stops on SIGINT or SIGTERM.
31
+
32
+ --host Address to listen on. Default: 127.0.0.1
33
+ --port Port to listen on. Default: a free port
34
+ --cwd Where sessions run when the host names no directory. Default: the current directory
35
+
36
+ Set TA_EXEC_TOKEN to choose the token hosts must present; otherwise a random one is printed.
37
+ `;
38
+
39
+ const RELAY_HELP = `Usage: ta relay [--host <host>] [--port <port>]
40
+
41
+ Runs a relay, through which paired devices reach a ta serve from anywhere (ta pair). It only forwards:
42
+ what goes through is encrypted end to end. Put it behind HTTPS. Stops on SIGINT or SIGTERM.
43
+
44
+ --host Address to listen on. Default: 127.0.0.1
45
+ --port Port to listen on. Default: 8080
46
+ `;
47
+
48
+ const PAIR_HELP = `Usage: ta pair [<relay url>] [--name <device>]
49
+ ta pair --list
50
+ ta pair --remove <device id>
51
+
52
+ Pairs a device, such as a phone, with the ta serve of this user: prints a link to paste in the Ta app on
53
+ it. The relay is https://relay.cellbang.com unless named. With a device paired, ta serve connects to the relay; what goes through it is encrypted end to end,
54
+ with a key only the device and ta serve have. The devices are in relay.json in the agent directory.
55
+ `;
56
+
20
57
  export interface TaCliOptions {
21
58
  /** The directory with ta's package.json and pi's assets. */
22
59
  brandDir: string;
@@ -35,24 +72,136 @@ export namespace TaCli {
35
72
  await serve(argv.slice(1), options.serveEntry);
36
73
  return;
37
74
  }
75
+ if (argv[0] === 'relay') {
76
+ await relay(argv.slice(1));
77
+ return;
78
+ }
79
+ if (argv[0] === 'pair') {
80
+ await pair(argv.slice(1));
81
+ return;
82
+ }
83
+ if (argv[0] === 'exec-server') {
84
+ await execServer(argv.slice(1));
85
+ return;
86
+ }
38
87
  const sdk: PiSdk = await import(/* @vite-ignore */ PiBundleUtil.specifier());
39
88
  const builtIn = TaExtensionUtil.bundle([new SessionLockExtension(new SessionLock()), new BrandExtension(sdk)]);
40
- await sdk.main(argv, { extensionFactories: [builtIn] });
89
+ await sdk.main(TaPackages.withExtensions(argv, TaBrand.agentDir()), { extensionFactories: [builtIn] });
41
90
  }
42
91
 
43
92
  async function serve(argv: string[], entry: string): Promise<void> {
44
- const { values } = parseArgs({ args: argv, options: { host: { type: 'string' }, port: { type: 'string' }, help: { type: 'boolean', short: 'h' } } });
93
+ const { values } = parseArgs({
94
+ args: argv,
95
+ options: {
96
+ host: { type: 'string' },
97
+ port: { type: 'string' },
98
+ web: { type: 'boolean' },
99
+ exec: { type: 'string' },
100
+ help: { type: 'boolean', short: 'h' },
101
+ },
102
+ });
45
103
  if (values.help) {
46
104
  process.stdout.write(SERVE_HELP);
47
105
  return;
48
106
  }
107
+ // This process is already Node.js; in the commands of the agent, an Electron app would start as Node.js too.
108
+ delete process.env.ELECTRON_RUN_AS_NODE;
49
109
  // Read by the server like any other key of its configuration.
50
110
  if (values.host) {
51
111
  process.env.CELL_SERVER__HOST = values.host;
52
112
  }
53
113
  if (values.port) {
54
114
  process.env.CELL_SERVER__PORT = values.port;
115
+ } else if (!process.env.CELL_SERVER__PORT) {
116
+ const { port } = TaServeStateUtil.read();
117
+ if (port && (await TaServeStateUtil.isFree(port, process.env.CELL_SERVER__HOST ?? '127.0.0.1'))) {
118
+ process.env.CELL_SERVER__PORT = String(port);
119
+ }
120
+ }
121
+ if (values.web) {
122
+ process.env.TA_SERVE_OPEN_WEB = '1';
123
+ }
124
+ if (values.exec) {
125
+ process.env.CELL_TA__EXEC__URL = values.exec;
126
+ }
127
+ if (process.env.TA_EXEC_TOKEN) {
128
+ process.env.CELL_TA__EXEC__TOKEN = process.env.TA_EXEC_TOKEN;
55
129
  }
56
130
  await import(/* @vite-ignore */ entry);
57
131
  }
132
+
133
+ /** Without Cell, as the exec server. */
134
+ async function relay(argv: string[]): Promise<void> {
135
+ const { values } = parseArgs({ args: argv, options: { host: { type: 'string' }, port: { type: 'string' }, help: { type: 'boolean', short: 'h' } } });
136
+ if (values.help) {
137
+ process.stdout.write(RELAY_HELP);
138
+ return;
139
+ }
140
+ const { RelayServer } = await import('@celljs/ta-relay/lib/node/relay-server');
141
+ const server = new RelayServer({ host: values.host, port: values.port ? Number(values.port) : 8080 });
142
+ console.log(`ta relay: ${await server.listen()}`);
143
+ const stop = () => void server.close().then(() => process.exit(0));
144
+ process.once('SIGINT', stop);
145
+ process.once('SIGTERM', stop);
146
+ }
147
+
148
+ async function pair(argv: string[]): Promise<void> {
149
+ const { values, positionals } = parseArgs({
150
+ args: argv,
151
+ allowPositionals: true,
152
+ options: { name: { type: 'string' }, list: { type: 'boolean' }, remove: { type: 'string' }, help: { type: 'boolean', short: 'h' } },
153
+ });
154
+ const { RelayStore } = await import('@celljs/ta-relay/lib/node/relay-store');
155
+ const { RelayPairingUtil } = await import('@celljs/ta-relay/lib/common/relay-pairing');
156
+ const store = new RelayStore(TaBrand.agentDir());
157
+ if (values.list) {
158
+ const { url, devices } = store.read();
159
+ console.log(devices.length === 0 ? 'No devices are paired.' : `Relay: ${url}`);
160
+ for (const device of devices) {
161
+ console.log(`${device.id} ${device.name} ${new Date(device.createdAt).toISOString()}`);
162
+ }
163
+ return;
164
+ }
165
+ if (values.remove) {
166
+ if (!store.remove(values.remove)) {
167
+ console.error(`ta pair: no device ${values.remove}`);
168
+ process.exitCode = 1;
169
+ }
170
+ return;
171
+ }
172
+ const { RELAY_DEFAULT_URL } = await import('@celljs/ta-relay/lib/common/relay-protocol');
173
+ const [relayUrl = RELAY_DEFAULT_URL] = positionals;
174
+ if (values.help || !/^https?:\/\//.test(relayUrl)) {
175
+ process.stdout.write(PAIR_HELP);
176
+ process.exitCode = values.help ? 0 : 1;
177
+ return;
178
+ }
179
+ const pairing = store.pair(relayUrl, values.name ?? 'device');
180
+ console.log('Paste this link in the Ta app on the device. Anyone with it can reach your Ta: keep it to yourself.\n');
181
+ console.log(RelayPairingUtil.link(pairing));
182
+ console.log(`\nDevice id: ${pairing.device} (ta pair --remove ${pairing.device} to unpair it)`);
183
+ }
184
+
185
+ /** Without Cell: the exec server is a plain HTTP server, as small as it can be. */
186
+ async function execServer(argv: string[]): Promise<void> {
187
+ const { values } = parseArgs({
188
+ args: argv,
189
+ options: { host: { type: 'string' }, port: { type: 'string' }, cwd: { type: 'string' }, help: { type: 'boolean', short: 'h' } },
190
+ });
191
+ if (values.help) {
192
+ process.stdout.write(EXEC_SERVER_HELP);
193
+ return;
194
+ }
195
+ const { ExecServer } = await import('@celljs/ta-exec/lib/node/exec-server');
196
+ const token = process.env.TA_EXEC_TOKEN || randomBytes(32).toString('base64url');
197
+ const server = new ExecServer({ host: values.host, port: values.port ? Number(values.port) : undefined, cwd: values.cwd, token });
198
+ const url = await server.listen();
199
+ console.log(`ta exec-server: ${url}`);
200
+ if (!process.env.TA_EXEC_TOKEN) {
201
+ console.log(`token: ${token}`);
202
+ }
203
+ const stop = () => void server.close().then(() => process.exit(0));
204
+ process.once('SIGINT', stop);
205
+ process.once('SIGTERM', stop);
206
+ }
58
207
  }
@@ -30,7 +30,7 @@ describe('TaHeader', () => {
30
30
  it('draws the dinosaur beside the name, version and keys when there is room', () => {
31
31
  const lines = header().render(100).map(plain);
32
32
  expect(lines.length).toBe(DinoLogo.HEIGHT + 1);
33
- expect(lines.some(line => line.includes('█') && line.includes('ta v4.4.1'))).toBe(true);
33
+ expect(lines.some(line => line.includes('█') && line.includes('Ta v4.4.1'))).toBe(true);
34
34
  expect(lines.join('\n')).toContain('escape interrupt · ctrl+c clear · ctrl+d exit');
35
35
  expect(lines.join('\n')).toContain('/ commands · ! bash · ctrl+o more');
36
36
  });
@@ -38,7 +38,7 @@ describe('TaHeader', () => {
38
38
  it('leaves the dinosaur out where the terminal is narrow or cannot draw it', () => {
39
39
  expect(header().render(50).map(plain).join('')).not.toContain('█');
40
40
  expect(header(false).render(120).map(plain).join('')).not.toContain('█');
41
- expect(plain(header().render(50)[0])).toBe(' ta v4.4.1');
41
+ expect(plain(header().render(50)[0])).toBe(' Ta v4.4.1');
42
42
  });
43
43
 
44
44
  it('lists every bound key when expanded, and skips unbound ones', () => {
@@ -115,15 +115,15 @@ export class TaHeader {
115
115
 
116
116
  protected intro(width: number): Span[] {
117
117
  const { theme } = this;
118
- const title = `ta v${this.options.version}`;
118
+ const title = `Ta v${this.options.version}`;
119
119
  const green = (text: string) => DinoLogo.paint(theme.getColorMode(), text);
120
120
  return [
121
- this.span(title, width, text => (text === title ? `${theme.bold(green('ta'))} ${theme.fg('dim', title.slice(4))}` : green(text))),
121
+ this.span(title, width, text => (text === title ? `${theme.bold(green('Ta'))} ${theme.fg('dim', title.slice(4))}` : green(text))),
122
122
  this.span('a coding agent on Cell and pi', width, text => theme.fg('muted', text)),
123
123
  { text: '', width: 0 },
124
124
  ...COMPACT_HINTS.flatMap(group => this.flow(this.hints(group), width)),
125
125
  { text: '', width: 0 },
126
- this.span('Ask ta how to use or extend it.', width, text => theme.fg('dim', text)),
126
+ this.span('Ask Ta how to use or extend it.', width, text => theme.fg('dim', text)),
127
127
  ];
128
128
  }
129
129
 
@@ -0,0 +1,95 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
2
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { TaPackages } from './ta-packages';
6
+
7
+ function write(file: string, content: string) {
8
+ mkdirSync(join(file, '..'), { recursive: true });
9
+ writeFileSync(file, content);
10
+ }
11
+
12
+ describe('TaPackages', () => {
13
+ let home: string;
14
+ let packageDir: string;
15
+ let agentDir: string;
16
+ beforeEach(() => {
17
+ home = mkdtempSync(join(tmpdir(), 'ta-packages-'));
18
+ packageDir = join(home, 'pi');
19
+ agentDir = join(home, 'agent');
20
+ write(join(packageDir, 'packages/ta-channels/package.json'), JSON.stringify({ name: '@celljs/ta-channels', pi: { web: ['web/index.js'] } }));
21
+ write(join(packageDir, 'packages/ta-notes/package.json'), JSON.stringify({ name: '@celljs/ta-notes', pi: { extensions: ['./index.ts'] } }));
22
+ write(join(packageDir, 'packages/ta-skills/package.json'), JSON.stringify({ name: '@celljs/ta-skills', pi: { skills: ['./skills'] } }));
23
+ mkdirSync(join(packageDir, 'packages/empty'));
24
+ });
25
+ afterEach(() => rmSync(home, { recursive: true, force: true }));
26
+
27
+ it('lists the packages of the package directory, with or without what pi loads', () => {
28
+ expect(TaPackages.builtins(packageDir)).toEqual([
29
+ { name: '@celljs/ta-channels', root: join(packageDir, 'packages/ta-channels'), resources: false },
30
+ { name: '@celljs/ta-notes', root: join(packageDir, 'packages/ta-notes'), resources: true },
31
+ { name: '@celljs/ta-skills', root: join(packageDir, 'packages/ta-skills'), resources: true },
32
+ ]);
33
+ });
34
+
35
+ it('finds the workspace packages when ta is not built', () => {
36
+ const names = TaPackages.builtins(join(home, 'nowhere')).map(pkg => pkg.name);
37
+ expect(names).toContain('@celljs/ta-channels');
38
+ expect(names.every(name => TaPackages.BUILTIN.includes(name))).toBe(true);
39
+ });
40
+
41
+ it('turns packages off and on in ta.json, keeping the other settings', () => {
42
+ write(join(agentDir, 'ta.json'), JSON.stringify({ other: 1 }));
43
+ TaPackages.setEnabled(agentDir, '@celljs/ta-notes', false);
44
+ TaPackages.setEnabled(agentDir, '@celljs/ta-skills', false);
45
+ expect(TaPackages.enabled(agentDir, packageDir).map(pkg => pkg.name)).toEqual(['@celljs/ta-channels']);
46
+ expect(TaPackages.extensionPaths(agentDir, packageDir)).toEqual([]);
47
+ TaPackages.setEnabled(agentDir, '@celljs/ta-skills', true);
48
+ expect(JSON.parse(readFileSync(join(agentDir, 'ta.json'), 'utf8'))).toEqual({ other: 1, disabledPackages: ['@celljs/ta-notes'] });
49
+ TaPackages.setEnabled(agentDir, '@celljs/ta-notes', true);
50
+ expect(TaPackages.extensionPaths(agentDir, packageDir)).toEqual([join(packageDir, 'packages/ta-notes'), join(packageDir, 'packages/ta-skills')]);
51
+ });
52
+
53
+ it('adds the pi extensions to the command line, except for package commands and --no-extensions', () => {
54
+ const root = join(packageDir, 'packages/ta-notes');
55
+ const skills = join(packageDir, 'packages/ta-skills');
56
+ expect(TaPackages.withExtensions(['-p', 'hi'], agentDir, packageDir)).toEqual(['-p', 'hi', '--extension', root, '--extension', skills]);
57
+ expect(TaPackages.withExtensions(['install', 'npm:x'], agentDir, packageDir)).toEqual(['install', 'npm:x']);
58
+ expect(TaPackages.withExtensions(['-ne'], agentDir, packageDir)).toEqual(['-ne']);
59
+ });
60
+
61
+ it('leaves out of what pi loaded the extensions of the packages turned off, as the setting is now', () => {
62
+ const root = join(packageDir, 'packages/ta-notes');
63
+ const options = TaPackages.loaderOptions(agentDir, packageDir);
64
+ expect(options.additionalExtensionPaths).toEqual([root, join(packageDir, 'packages/ta-skills')]);
65
+ const extension = (path: string) => ({ path, resolvedPath: path }) as never;
66
+ const loaded = {
67
+ extensions: [extension(join(root, 'index.ts')), extension('/elsewhere/index.ts')],
68
+ errors: [{ path: join(root, 'bad.ts'), error: 'x' }],
69
+ } as never;
70
+ expect(options.extensionsOverride(loaded).extensions).toHaveLength(2);
71
+ TaPackages.setEnabled(agentDir, '@celljs/ta-notes', false);
72
+ const after = options.extensionsOverride(loaded);
73
+ expect(after.extensions.map(item => item.path)).toEqual(['/elsewhere/index.ts']);
74
+ expect(after.errors).toEqual([]);
75
+ });
76
+
77
+ it('leaves out the skills and prompts of the packages turned off', () => {
78
+ const root = join(packageDir, 'packages/ta-skills');
79
+ const options = TaPackages.loaderOptions(agentDir, packageDir);
80
+ const skills = {
81
+ skills: [{ filePath: join(root, 'skills/a/SKILL.md') }, { filePath: '/elsewhere/SKILL.md' }],
82
+ diagnostics: [{ path: join(root, 'skills/b') }],
83
+ };
84
+ const prompts = { prompts: [{ filePath: join(root, 'prompts/p.md') }], diagnostics: [] };
85
+ expect(options.skillsOverride(skills)).toEqual(skills);
86
+ TaPackages.setEnabled(agentDir, '@celljs/ta-skills', false);
87
+ expect(options.skillsOverride(skills)).toEqual({ skills: [{ filePath: '/elsewhere/SKILL.md' }], diagnostics: [] });
88
+ expect(options.promptsOverride(prompts).prompts).toEqual([]);
89
+ });
90
+
91
+ it('names the directory of a package without its scope', () => {
92
+ expect(TaPackages.directoryName('@celljs/ta-channels')).toBe('ta-channels');
93
+ expect(TaPackages.directoryName('notes')).toBe('notes');
94
+ });
95
+ });