@celljs/ta-harness 0.0.0-stage → 4.5.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 (150) hide show
  1. package/README.md +13 -2
  2. package/esm/node/brand-extension.d.ts +15 -0
  3. package/esm/node/brand-extension.js +37 -0
  4. package/esm/node/brand-extension.js.map +1 -0
  5. package/esm/node/bug-report.d.ts +19 -0
  6. package/esm/node/bug-report.js +38 -0
  7. package/esm/node/bug-report.js.map +1 -0
  8. package/esm/node/dino-logo.d.ts +18 -0
  9. package/esm/node/dino-logo.js +66 -0
  10. package/esm/node/dino-logo.js.map +1 -0
  11. package/esm/node/exec-extension.d.ts +15 -0
  12. package/esm/node/exec-extension.js +28 -0
  13. package/esm/node/exec-extension.js.map +1 -0
  14. package/esm/node/exec-mcp-transport.d.ts +27 -0
  15. package/esm/node/exec-mcp-transport.js +76 -0
  16. package/esm/node/exec-mcp-transport.js.map +1 -0
  17. package/esm/node/exec-operations.d.ts +22 -0
  18. package/esm/node/exec-operations.js +95 -0
  19. package/esm/node/exec-operations.js.map +1 -0
  20. package/esm/node/extensions.d.ts +24 -0
  21. package/esm/node/extensions.js +61 -0
  22. package/esm/node/extensions.js.map +1 -0
  23. package/esm/node/glob-util.d.ts +7 -0
  24. package/esm/node/glob-util.js +57 -0
  25. package/esm/node/glob-util.js.map +1 -0
  26. package/esm/node/index.d.ts +13 -0
  27. package/esm/node/index.js +14 -0
  28. package/esm/node/index.js.map +1 -0
  29. package/esm/node/pi-types.d.ts +13 -0
  30. package/esm/node/pi-types.js +2 -0
  31. package/esm/node/pi-types.js.map +1 -0
  32. package/esm/node/session-lock.d.ts +27 -0
  33. package/esm/node/session-lock.js +96 -0
  34. package/esm/node/session-lock.js.map +1 -0
  35. package/esm/node/ta-brand.d.ts +14 -0
  36. package/esm/node/ta-brand.js +44 -0
  37. package/esm/node/ta-brand.js.map +1 -0
  38. package/esm/node/ta-cli.d.ts +13 -0
  39. package/esm/node/ta-cli.js +50 -0
  40. package/esm/node/ta-cli.js.map +1 -0
  41. package/esm/node/ta-header.d.ts +61 -0
  42. package/esm/node/ta-header.js +149 -0
  43. package/esm/node/ta-header.js.map +1 -0
  44. package/esm/package.json +3 -0
  45. package/lib/node/brand-extension.d.ts +16 -0
  46. package/lib/node/brand-extension.d.ts.map +1 -0
  47. package/lib/node/brand-extension.js +41 -0
  48. package/lib/node/brand-extension.js.map +1 -0
  49. package/lib/node/brand-extension.spec.d.ts +2 -0
  50. package/lib/node/brand-extension.spec.d.ts.map +1 -0
  51. package/lib/node/brand-extension.spec.js +57 -0
  52. package/lib/node/brand-extension.spec.js.map +1 -0
  53. package/lib/node/bug-report.d.ts +20 -0
  54. package/lib/node/bug-report.d.ts.map +1 -0
  55. package/lib/node/bug-report.js +41 -0
  56. package/lib/node/bug-report.js.map +1 -0
  57. package/lib/node/dino-logo.d.ts +19 -0
  58. package/lib/node/dino-logo.d.ts.map +1 -0
  59. package/lib/node/dino-logo.js +69 -0
  60. package/lib/node/dino-logo.js.map +1 -0
  61. package/lib/node/exec-extension.d.ts +16 -0
  62. package/lib/node/exec-extension.d.ts.map +1 -0
  63. package/lib/node/exec-extension.js +32 -0
  64. package/lib/node/exec-extension.js.map +1 -0
  65. package/lib/node/exec-mcp-transport.d.ts +28 -0
  66. package/lib/node/exec-mcp-transport.d.ts.map +1 -0
  67. package/lib/node/exec-mcp-transport.js +80 -0
  68. package/lib/node/exec-mcp-transport.js.map +1 -0
  69. package/lib/node/exec-operations.d.ts +23 -0
  70. package/lib/node/exec-operations.d.ts.map +1 -0
  71. package/lib/node/exec-operations.js +99 -0
  72. package/lib/node/exec-operations.js.map +1 -0
  73. package/lib/node/exec-operations.spec.d.ts +2 -0
  74. package/lib/node/exec-operations.spec.d.ts.map +1 -0
  75. package/lib/node/exec-operations.spec.js +76 -0
  76. package/lib/node/exec-operations.spec.js.map +1 -0
  77. package/lib/node/extensions.d.ts +25 -0
  78. package/lib/node/extensions.d.ts.map +1 -0
  79. package/lib/node/extensions.js +65 -0
  80. package/lib/node/extensions.js.map +1 -0
  81. package/lib/node/extensions.spec.d.ts +2 -0
  82. package/lib/node/extensions.spec.d.ts.map +1 -0
  83. package/lib/node/extensions.spec.js +94 -0
  84. package/lib/node/extensions.spec.js.map +1 -0
  85. package/lib/node/glob-util.d.ts +8 -0
  86. package/lib/node/glob-util.d.ts.map +1 -0
  87. package/lib/node/glob-util.js +60 -0
  88. package/lib/node/glob-util.js.map +1 -0
  89. package/lib/node/glob-util.spec.d.ts +2 -0
  90. package/lib/node/glob-util.spec.d.ts.map +1 -0
  91. package/lib/node/glob-util.spec.js +27 -0
  92. package/lib/node/glob-util.spec.js.map +1 -0
  93. package/lib/node/index.d.ts +14 -0
  94. package/lib/node/index.d.ts.map +1 -0
  95. package/lib/node/index.js +30 -0
  96. package/lib/node/index.js.map +1 -0
  97. package/lib/node/pi-types.d.ts +14 -0
  98. package/lib/node/pi-types.d.ts.map +1 -0
  99. package/lib/node/pi-types.js +3 -0
  100. package/lib/node/pi-types.js.map +1 -0
  101. package/lib/node/session-lock.d.ts +28 -0
  102. package/lib/node/session-lock.d.ts.map +1 -0
  103. package/lib/node/session-lock.js +100 -0
  104. package/lib/node/session-lock.js.map +1 -0
  105. package/lib/node/session-lock.spec.d.ts +2 -0
  106. package/lib/node/session-lock.spec.d.ts.map +1 -0
  107. package/lib/node/session-lock.spec.js +53 -0
  108. package/lib/node/session-lock.spec.js.map +1 -0
  109. package/lib/node/ta-brand.d.ts +15 -0
  110. package/lib/node/ta-brand.d.ts.map +1 -0
  111. package/lib/node/ta-brand.js +47 -0
  112. package/lib/node/ta-brand.js.map +1 -0
  113. package/lib/node/ta-brand.spec.d.ts +2 -0
  114. package/lib/node/ta-brand.spec.d.ts.map +1 -0
  115. package/lib/node/ta-brand.spec.js +43 -0
  116. package/lib/node/ta-brand.spec.js.map +1 -0
  117. package/lib/node/ta-cli.d.ts +14 -0
  118. package/lib/node/ta-cli.d.ts.map +1 -0
  119. package/lib/node/ta-cli.js +53 -0
  120. package/lib/node/ta-cli.js.map +1 -0
  121. package/lib/node/ta-header.d.ts +62 -0
  122. package/lib/node/ta-header.d.ts.map +1 -0
  123. package/lib/node/ta-header.js +153 -0
  124. package/lib/node/ta-header.js.map +1 -0
  125. package/lib/node/ta-header.spec.d.ts +2 -0
  126. package/lib/node/ta-header.spec.d.ts.map +1 -0
  127. package/lib/node/ta-header.spec.js +67 -0
  128. package/lib/node/ta-header.spec.js.map +1 -0
  129. package/package.json +57 -4
  130. package/src/node/brand-extension.spec.ts +63 -0
  131. package/src/node/brand-extension.ts +43 -0
  132. package/src/node/bug-report.ts +48 -0
  133. package/src/node/dino-logo.ts +70 -0
  134. package/src/node/exec-extension.ts +33 -0
  135. package/src/node/exec-mcp-transport.ts +89 -0
  136. package/src/node/exec-operations.spec.ts +83 -0
  137. package/src/node/exec-operations.ts +106 -0
  138. package/src/node/extensions.spec.ts +110 -0
  139. package/src/node/extensions.ts +69 -0
  140. package/src/node/glob-util.spec.ts +29 -0
  141. package/src/node/glob-util.ts +47 -0
  142. package/src/node/index.ts +13 -0
  143. package/src/node/pi-types.ts +15 -0
  144. package/src/node/session-lock.spec.ts +56 -0
  145. package/src/node/session-lock.ts +105 -0
  146. package/src/node/ta-brand.spec.ts +46 -0
  147. package/src/node/ta-brand.ts +41 -0
  148. package/src/node/ta-cli.ts +58 -0
  149. package/src/node/ta-header.spec.ts +74 -0
  150. package/src/node/ta-header.ts +192 -0
@@ -0,0 +1,106 @@
1
+ import { join, relative } from 'node:path';
2
+ import type { ExecEnvironment } from '@celljs/ta-exec';
3
+ import { GlobUtil } from './glob-util';
4
+ import type { BashOperations, EditOperations, FindOperations, LsOperations, ReadOperations, WriteOperations } from './pi-types';
5
+
6
+ /** The file and process operations of pi's built-in tools, on an {@link ExecEnvironment}. */
7
+ export class ExecOperations {
8
+ constructor(protected readonly environment: ExecEnvironment) {}
9
+
10
+ readonly bash: BashOperations = {
11
+ exec: (command, cwd, options) =>
12
+ this.environment.exec(command, {
13
+ cwd,
14
+ env: options.env,
15
+ signal: options.signal,
16
+ // pi's timeouts are in seconds.
17
+ timeout: options.timeout ? options.timeout * 1000 : undefined,
18
+ onData: data => options.onData(Buffer.from(data)),
19
+ }),
20
+ };
21
+
22
+ readonly read: ReadOperations = {
23
+ readFile: path => this.readBuffer(path),
24
+ access: path => this.access(path),
25
+ };
26
+
27
+ readonly write: WriteOperations = {
28
+ writeFile: (path, content) => this.environment.writeFile(path, content),
29
+ mkdir: dir => this.environment.mkdir(dir),
30
+ };
31
+
32
+ readonly edit: EditOperations = {
33
+ readFile: path => this.readBuffer(path),
34
+ writeFile: (path, content) => this.environment.writeFile(path, content),
35
+ access: path => this.access(path),
36
+ };
37
+
38
+ readonly ls: LsOperations = {
39
+ exists: path => this.exists(path),
40
+ stat: async path => {
41
+ const info = await this.environment.stat(path);
42
+ if (!info) {
43
+ throw this.notFound(path);
44
+ }
45
+ return { isDirectory: () => info.isDirectory };
46
+ },
47
+ readdir: async path => (await this.environment.readdir(path)).map(entry => entry.name),
48
+ };
49
+
50
+ readonly find: FindOperations = {
51
+ exists: path => this.exists(path),
52
+ glob: (pattern, cwd, options) => this.glob(pattern, cwd, options.ignore, options.limit),
53
+ };
54
+
55
+ protected async readBuffer(path: string): Promise<Buffer> {
56
+ return Buffer.from(await this.environment.readFile(path));
57
+ }
58
+
59
+ protected async access(path: string): Promise<void> {
60
+ if (!(await this.exists(path))) {
61
+ throw this.notFound(path);
62
+ }
63
+ }
64
+
65
+ protected async exists(path: string): Promise<boolean> {
66
+ return (await this.environment.stat(path)) !== undefined;
67
+ }
68
+
69
+ protected notFound(path: string): NodeJS.ErrnoException {
70
+ return Object.assign(new Error(`ENOENT: no such file or directory, '${path}'`), { code: 'ENOENT' });
71
+ }
72
+
73
+ /**
74
+ * Lists the files with `find`, the one tool every environment has, and matches them here. Stops the
75
+ * listing at `limit` matches, so that a huge tree costs no more than the answer needs.
76
+ */
77
+ protected async glob(pattern: string, cwd: string, ignore: string[], limit: number): Promise<string[]> {
78
+ const matches = GlobUtil.matcher(pattern);
79
+ const ignored = ignore.map(GlobUtil.matcher);
80
+ const found: string[] = [];
81
+ const stop = new AbortController();
82
+ let rest = '';
83
+ const accept = (line: string) => {
84
+ const path = relative('.', line);
85
+ if (found.length < limit && path && matches(path) && !ignored.some(isIgnored => isIgnored(path))) {
86
+ found.push(join(cwd, path));
87
+ if (found.length === limit) {
88
+ stop.abort();
89
+ }
90
+ }
91
+ };
92
+ await this.environment.exec('find . -type f -not -path "*/.git/*"', {
93
+ cwd,
94
+ signal: stop.signal,
95
+ onData: data => {
96
+ const lines = (rest + Buffer.from(data).toString()).split('\n');
97
+ rest = lines.pop() ?? '';
98
+ lines.forEach(accept);
99
+ },
100
+ });
101
+ if (rest) {
102
+ accept(rest);
103
+ }
104
+ return found;
105
+ }
106
+ }
@@ -0,0 +1,110 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { mkdtempSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { PiBundleUtil } from '@celljs/ai-coding-agent/lib/node/pi/pi-bundle-util';
6
+ import { LocalExecEnvironment } from '@celljs/ta-exec';
7
+ import { ExecExtension } from './exec-extension';
8
+ import { SessionLockExtension, TaExtensionUtil } from './extensions';
9
+ import type { ExtensionAPI, PiSdk } from './pi-types';
10
+ import { SessionLock } from './session-lock';
11
+
12
+ type Handler = (event: unknown, ctx: unknown) => any;
13
+
14
+ /** The part of pi's extension API these extensions use. */
15
+ function fakePi(activeTools: string[] = []) {
16
+ const handlers = new Map<string, Handler>();
17
+ const tools = new Map<string, any>();
18
+ const state = { activeTools };
19
+ const pi = {
20
+ on: (event: string, handler: Handler) => handlers.set(event, handler),
21
+ registerTool: (tool: { name: string }) => tools.set(tool.name, tool),
22
+ getActiveTools: () => state.activeTools,
23
+ setActiveTools: (names: string[]) => {
24
+ state.activeTools = names;
25
+ },
26
+ } as unknown as ExtensionAPI;
27
+ return { pi, handlers, tools, state };
28
+ }
29
+
30
+ const context = (sessionFile: string | undefined, extra: object = {}) => ({ sessionManager: { getSessionFile: () => sessionFile }, ...extra });
31
+
32
+ describe('SessionLockExtension', () => {
33
+ const file = () => join(mkdtempSync(join(tmpdir(), 'ta-ext-')), 'a.jsonl');
34
+
35
+ it('holds the session from its start to its shutdown', () => {
36
+ const lock = new SessionLock();
37
+ const { pi, handlers } = fakePi();
38
+ new SessionLockExtension(lock).register(pi);
39
+ const session = file();
40
+ const other = new SessionLock();
41
+ handlers.get('session_start')!({}, context(session));
42
+ expect(other.isHeldByOther(session)).toBe(true);
43
+ handlers.get('session_shutdown')!({}, context(session));
44
+ expect(other.isHeldByOther(session)).toBe(false);
45
+ });
46
+
47
+ it('cancels switching to a session another owner holds', () => {
48
+ const { pi, handlers } = fakePi();
49
+ new SessionLockExtension(new SessionLock()).register(pi);
50
+ const session = file();
51
+ new SessionLock().acquire(session);
52
+ expect(handlers.get('session_before_switch')!({ targetSessionFile: session }, context(undefined))).toEqual({ cancel: true });
53
+ expect(handlers.get('session_before_switch')!({ targetSessionFile: file() }, context(undefined))).toBeUndefined();
54
+ });
55
+
56
+ it('asks the terminal UI to end when its session is held elsewhere', () => {
57
+ const { pi, handlers } = fakePi();
58
+ new SessionLockExtension(new SessionLock()).register(pi);
59
+ const session = file();
60
+ new SessionLock().acquire(session);
61
+ const calls: string[] = [];
62
+ handlers.get('session_start')!(
63
+ {},
64
+ context(session, { mode: 'tui', ui: { notify: () => calls.push('notify') }, shutdown: () => calls.push('shutdown') }),
65
+ );
66
+ expect(calls).toEqual(['notify', 'shutdown']);
67
+ });
68
+
69
+ it('ignores in-memory sessions', () => {
70
+ const { pi, handlers } = fakePi();
71
+ new SessionLockExtension(new SessionLock()).register(pi);
72
+ handlers.get('session_start')!({}, context(undefined));
73
+ });
74
+
75
+ it("is named in pi's diagnostics", () => {
76
+ expect(TaExtensionUtil.toInline(new SessionLockExtension(new SessionLock())).name).toBe('ta:session-lock');
77
+ });
78
+ });
79
+
80
+ describe('ExecExtension', () => {
81
+ async function setup() {
82
+ const sdk: PiSdk = await import(PiBundleUtil.specifier());
83
+ const environment = new LocalExecEnvironment(mkdtempSync(join(tmpdir(), 'ta-exec-ext-')));
84
+ const fake = fakePi(['read', 'bash', 'grep']);
85
+ new ExecExtension(environment, sdk).register(fake.pi);
86
+ return { ...fake, environment };
87
+ }
88
+
89
+ it('replaces the tools that work through the environment', async () => {
90
+ const { tools } = await setup();
91
+ expect([...tools.keys()].sort()).toEqual(['bash', 'edit', 'find', 'ls', 'read', 'write']);
92
+ });
93
+
94
+ it('runs them in the environment', async () => {
95
+ const { tools, environment } = await setup();
96
+ await tools.get('write').execute('c1', { path: 'a.txt', content: 'written' }, undefined, undefined, {});
97
+ expect(Buffer.from(await environment.readFile('a.txt')).toString()).toBe('written');
98
+ });
99
+
100
+ it('takes over the ! commands', async () => {
101
+ const { handlers } = await setup();
102
+ expect(typeof handlers.get('user_bash')!({}, {}).operations.exec).toBe('function');
103
+ });
104
+
105
+ it('takes away grep, which would search this machine', async () => {
106
+ const { handlers, state } = await setup();
107
+ handlers.get('session_start')!({}, {});
108
+ expect(state.activeTools).toEqual(['read', 'bash']);
109
+ });
110
+ });
@@ -0,0 +1,69 @@
1
+ import type { ExtensionAPI, ExtensionContext, InlineExtension } from './pi-types';
2
+ import type { SessionLock } from './session-lock';
3
+
4
+ /** A pi extension of ta. A plain object: the `ta` command runs without a Cell container. */
5
+ export interface TaExtension {
6
+ readonly name: string;
7
+ register(pi: ExtensionAPI): void;
8
+ }
9
+
10
+ export namespace TaExtensionUtil {
11
+ export function toInline(extension: TaExtension): InlineExtension {
12
+ return { name: extension.name, factory: pi => extension.register(pi) };
13
+ }
14
+
15
+ /** ta's built-in extensions as one, listed by pi as `ta` among the loaded extensions. */
16
+ export function bundle(extensions: TaExtension[]): InlineExtension {
17
+ return {
18
+ name: 'ta',
19
+ factory: pi => {
20
+ for (const extension of extensions) {
21
+ extension.register(pi);
22
+ }
23
+ },
24
+ };
25
+ }
26
+ }
27
+
28
+ /** Holds the lock of the session file that is open. See {@link SessionLock}. */
29
+ export class SessionLockExtension implements TaExtension {
30
+ readonly name = 'ta:session-lock';
31
+
32
+ constructor(protected readonly lock: SessionLock) {}
33
+
34
+ register(pi: ExtensionAPI): void {
35
+ pi.on('session_before_switch', event => {
36
+ if (event.targetSessionFile && this.lock.isHeldByOther(event.targetSessionFile)) {
37
+ return { cancel: true };
38
+ }
39
+ return undefined;
40
+ });
41
+ pi.on('session_start', (_event, ctx) => {
42
+ const file = ctx.sessionManager.getSessionFile();
43
+ if (file && !this.lock.acquire(file)) {
44
+ this.refuse(file, ctx);
45
+ }
46
+ });
47
+ pi.on('session_shutdown', (_event, ctx) => {
48
+ const file = ctx.sessionManager.getSessionFile();
49
+ if (file) {
50
+ this.lock.release(file);
51
+ }
52
+ });
53
+ }
54
+
55
+ /**
56
+ * pi has opened the session by the time an extension can see it (`--continue`, `--resume`), so this
57
+ * can only end the process. `ctx.shutdown` restores the terminal; print modes do not act on it.
58
+ */
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)}.`;
61
+ if (ctx.mode === 'tui') {
62
+ ctx.ui.notify(message, 'error');
63
+ ctx.shutdown();
64
+ return;
65
+ }
66
+ process.stderr.write(`${message}\n`);
67
+ process.exit(1);
68
+ }
69
+ }
@@ -0,0 +1,29 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { GlobUtil } from './glob-util';
3
+
4
+ const matches = (pattern: string, path: string) => GlobUtil.matcher(pattern)(path);
5
+
6
+ describe('GlobUtil', () => {
7
+ it('matches names at any depth when the pattern has no slash', () => {
8
+ expect(matches('*.ts', 'src/a/b.ts')).toBe(true);
9
+ expect(matches('*.ts', 'src/a/b.js')).toBe(false);
10
+ });
11
+
12
+ it('matches paths from the root when the pattern has a slash', () => {
13
+ expect(matches('src/*.ts', 'src/a.ts')).toBe(true);
14
+ expect(matches('src/*.ts', 'src/a/b.ts')).toBe(false);
15
+ expect(matches('src/**/*.ts', 'src/b.ts')).toBe(true);
16
+ expect(matches('src/**/*.ts', 'src/a/b/c.ts')).toBe(true);
17
+ });
18
+
19
+ it('understands braces, question marks and classes', () => {
20
+ expect(matches('*.{ts,tsx}', 'a.tsx')).toBe(true);
21
+ expect(matches('a?.ts', 'ab.ts')).toBe(true);
22
+ expect(matches('[ab].ts', 'c.ts')).toBe(false);
23
+ });
24
+
25
+ it('takes other characters literally', () => {
26
+ expect(matches('a.b', 'axb')).toBe(false);
27
+ expect(matches('a+(b)', 'a+(b)')).toBe(true);
28
+ });
29
+ });
@@ -0,0 +1,47 @@
1
+ export namespace GlobUtil {
2
+ /**
3
+ * A matcher for the glob syntax of fd, which pi's find tool documents: `*`, `?`, `**`, `{a,b}` and
4
+ * `[...]`. A pattern without `/` matches the name of the file at any depth.
5
+ */
6
+ export function matcher(pattern: string): (path: string) => boolean {
7
+ const anywhere = !pattern.includes('/');
8
+ const regexp = new RegExp(`^${toRegExp(pattern)}$`);
9
+ return path => regexp.test(anywhere ? path.slice(path.lastIndexOf('/') + 1) : path);
10
+ }
11
+
12
+ function toRegExp(glob: string): string {
13
+ let out = '';
14
+ let braces = 0;
15
+ for (let i = 0; i < glob.length; i++) {
16
+ const char = glob[i];
17
+ if (char === '*' && glob[i + 1] === '*') {
18
+ const slash = glob[i + 2] === '/';
19
+ out += slash ? '(?:.*/)?' : '.*';
20
+ i += slash ? 2 : 1;
21
+ } else if (char === '*') {
22
+ out += '[^/]*';
23
+ } else if (char === '?') {
24
+ out += '[^/]';
25
+ } else if (char === '{') {
26
+ braces++;
27
+ out += '(?:';
28
+ } else if (char === '}' && braces) {
29
+ braces--;
30
+ out += ')';
31
+ } else if (char === ',' && braces) {
32
+ out += '|';
33
+ } else if (char === '[') {
34
+ const end = glob.indexOf(']', i + 2);
35
+ if (end === -1) {
36
+ out += '\\[';
37
+ } else {
38
+ out += glob.slice(i, end + 1);
39
+ i = end;
40
+ }
41
+ } else {
42
+ out += char.replace(/[\\^$.|+()]/g, '\\$&');
43
+ }
44
+ }
45
+ return out;
46
+ }
47
+ }
@@ -0,0 +1,13 @@
1
+ export * from './brand-extension';
2
+ export * from './bug-report';
3
+ export * from './dino-logo';
4
+ export * from './exec-extension';
5
+ export * from './exec-mcp-transport';
6
+ export * from './exec-operations';
7
+ export * from './extensions';
8
+ export * from './glob-util';
9
+ export * from './pi-types';
10
+ export * from './session-lock';
11
+ export * from './ta-brand';
12
+ export * from './ta-cli';
13
+ export * from './ta-header';
@@ -0,0 +1,15 @@
1
+ // Only types: importing them does not load pi or @celljs/ai-coding-agent. See PiBundleUtil.
2
+ export type { PiSdk } from '@celljs/ai-coding-agent/lib/node/pi/pi-sdk-util';
3
+
4
+ export type ExtensionAPI = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ExtensionAPI;
5
+ export type ExtensionContext = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ExtensionContext;
6
+ export type InlineExtension = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).InlineExtension;
7
+ export type BashOperations = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).BashOperations;
8
+ export type ReadOperations = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).ReadOperations;
9
+ export type WriteOperations = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).WriteOperations;
10
+ export type EditOperations = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).EditOperations;
11
+ export type LsOperations = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).LsOperations;
12
+ export type FindOperations = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).FindOperations;
13
+ export type McpServerEntry = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' }}).McpServerEntry;
14
+ export type McpTransport = import('@earendil-works/pi-mcp', { with: { 'resolution-mode': 'import' }}).McpTransport;
15
+ export type JsonRpcMessage = import('@earendil-works/pi-mcp', { with: { 'resolution-mode': 'import' }}).JsonRpcMessage;
@@ -0,0 +1,56 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { existsSync, mkdtempSync, readdirSync, writeFileSync } from 'node:fs';
4
+ import { hostname, tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { SessionLock } from './session-lock';
7
+
8
+ const sessionFile = () => join(mkdtempSync(join(tmpdir(), 'ta-lock-')), 'sessions', 'a.jsonl');
9
+
10
+ describe('SessionLock', () => {
11
+ it('lets one owner hold a session and refuses the others', () => {
12
+ const file = sessionFile();
13
+ const [first, second] = [new SessionLock(), new SessionLock()];
14
+ expect(first.acquire(file)).toBe(true);
15
+ expect(first.acquire(file)).toBe(true);
16
+ expect(second.acquire(file)).toBe(false);
17
+ expect(second.isHeldByOther(file)).toBe(true);
18
+ expect(first.isHeldByOther(file)).toBe(false);
19
+ });
20
+
21
+ it('frees the session on release', () => {
22
+ const file = sessionFile();
23
+ const [first, second] = [new SessionLock(), new SessionLock()];
24
+ first.acquire(file);
25
+ first.release(file);
26
+ expect(existsSync(first.path(file))).toBe(false);
27
+ expect(second.acquire(file)).toBe(true);
28
+ });
29
+
30
+ it('takes over the lock of a process that is gone', () => {
31
+ const file = sessionFile();
32
+ const lock = new SessionLock();
33
+ lock.acquire(file);
34
+ writeFileSync(lock.path(file), JSON.stringify({ owner: 'gone', pid: spawnSync('true').pid, host: hostname(), createdAt: 1 }));
35
+ const next = new SessionLock();
36
+ expect(next.isHeldByOther(file)).toBe(false);
37
+ expect(next.acquire(file)).toBe(true);
38
+ });
39
+
40
+ it('respects the lock of another host, whose processes it cannot see', () => {
41
+ const file = sessionFile();
42
+ const first = new SessionLock();
43
+ first.acquire(file);
44
+ writeFileSync(first.path(file), JSON.stringify({ owner: 'other', pid: 1, host: 'another-host', createdAt: 1 }));
45
+ expect(new SessionLock().acquire(file)).toBe(false);
46
+ });
47
+
48
+ it('leaves nothing but the lock behind', () => {
49
+ const file = sessionFile();
50
+ const lock = new SessionLock();
51
+ lock.acquire(file);
52
+ expect(readdirSync(join(file, '..'))).toEqual(['a.jsonl.lock']);
53
+ lock.releaseAll();
54
+ expect(readdirSync(join(file, '..'))).toEqual([]);
55
+ });
56
+ });
@@ -0,0 +1,105 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { linkSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { hostname } from 'node:os';
4
+ import { dirname } from 'node:path';
5
+
6
+ interface LockFile {
7
+ owner: string;
8
+ pid: number;
9
+ host: string;
10
+ createdAt: number;
11
+ }
12
+
13
+ /**
14
+ * Keeps a session file to one writer: pi appends to it without a lock, so two processes on one session
15
+ * would interleave their entries. The lock is a file next to the session, created atomically, and is
16
+ * void once the process that made it is gone. Each instance is one owner, so that two open sessions of
17
+ * one process exclude each other too.
18
+ */
19
+ export class SessionLock {
20
+ protected readonly owner = randomUUID();
21
+ protected readonly held = new Set<string>();
22
+
23
+ /** False when another owner holds it. Taking a lock this owner holds succeeds. */
24
+ acquire(sessionFile: string): boolean {
25
+ if (this.held.has(sessionFile)) {
26
+ return true;
27
+ }
28
+ mkdirSync(dirname(sessionFile), { recursive: true });
29
+ // A second round after removing a stale lock; losing that race to another process ends in false.
30
+ for (let attempt = 0; attempt < 2; attempt++) {
31
+ if (this.create(sessionFile)) {
32
+ this.held.add(sessionFile);
33
+ return true;
34
+ }
35
+ if (this.isHeldByOther(sessionFile)) {
36
+ return false;
37
+ }
38
+ rmSync(this.path(sessionFile), { force: true });
39
+ }
40
+ return false;
41
+ }
42
+
43
+ isHeldByOther(sessionFile: string): boolean {
44
+ const lock = this.read(sessionFile);
45
+ return lock !== undefined && lock.owner !== this.owner && this.isAlive(lock);
46
+ }
47
+
48
+ release(sessionFile: string): void {
49
+ if (this.held.delete(sessionFile)) {
50
+ rmSync(this.path(sessionFile), { force: true });
51
+ }
52
+ }
53
+
54
+ releaseAll(): void {
55
+ for (const sessionFile of [...this.held]) {
56
+ this.release(sessionFile);
57
+ }
58
+ }
59
+
60
+ path(sessionFile: string): string {
61
+ return `${sessionFile}.lock`;
62
+ }
63
+
64
+ /** Writes the lock aside and links it into place, so that nobody can read a half-written lock. */
65
+ protected create(sessionFile: string): boolean {
66
+ const lock: LockFile = { owner: this.owner, pid: process.pid, host: hostname(), createdAt: Date.now() };
67
+ const draft = `${this.path(sessionFile)}.${this.owner}`;
68
+ writeFileSync(draft, JSON.stringify(lock));
69
+ try {
70
+ linkSync(draft, this.path(sessionFile));
71
+ return true;
72
+ } catch (error) {
73
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
74
+ return false;
75
+ }
76
+ throw error;
77
+ } finally {
78
+ rmSync(draft, { force: true });
79
+ }
80
+ }
81
+
82
+ protected read(sessionFile: string): LockFile | undefined {
83
+ try {
84
+ return JSON.parse(readFileSync(this.path(sessionFile), 'utf8'));
85
+ } catch (error) {
86
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
87
+ return undefined;
88
+ }
89
+ throw error;
90
+ }
91
+ }
92
+
93
+ protected isAlive(lock: LockFile): boolean {
94
+ if (lock.host !== hostname()) {
95
+ // Its process cannot be checked from here (a shared volume): respect it.
96
+ return true;
97
+ }
98
+ try {
99
+ process.kill(lock.pid, 0);
100
+ return true;
101
+ } catch (error) {
102
+ return (error as NodeJS.ErrnoException).code === 'EPERM';
103
+ }
104
+ }
105
+ }
@@ -0,0 +1,46 @@
1
+ import { afterEach, describe, expect, it } from 'bun:test';
2
+ import { TaBrand } from './ta-brand';
3
+
4
+ describe('TaBrand.activate', () => {
5
+ const saved = { ...process.env };
6
+ const title = process.title;
7
+ const emitWarning = process.emitWarning;
8
+
9
+ afterEach(() => {
10
+ process.env = { ...saved };
11
+ process.title = title;
12
+ process.emitWarning = emitWarning;
13
+ });
14
+
15
+ function clean(): void {
16
+ for (const name of [...Object.keys(TaBrand.ENV_ALIASES), ...Object.values(TaBrand.ENV_ALIASES)]) {
17
+ delete process.env[name];
18
+ }
19
+ }
20
+
21
+ it("points pi at ta's package directory", () => {
22
+ TaBrand.activate('/opt/ta/dist/pi');
23
+ expect(process.env.PI_PACKAGE_DIR).toBe('/opt/ta/dist/pi');
24
+ expect(process.env.AI_AGENT).toBe('ta');
25
+ });
26
+
27
+ it("passes the TA_ names of pi's settings on to pi", () => {
28
+ clean();
29
+ process.env.TA_OFFLINE = '1';
30
+ process.env.TA_SELF_UPDATE_COMMAND = 'brew upgrade ta';
31
+ TaBrand.activate('/opt/ta/dist/pi');
32
+ expect(process.env.PI_OFFLINE).toBe('1');
33
+ expect(process.env.PI_SELF_UPDATE_COMMAND).toBe('brew upgrade ta');
34
+ });
35
+
36
+ it("turns pi's reports to pi.dev off, unless asked for", () => {
37
+ clean();
38
+ TaBrand.activate('/opt/ta/dist/pi');
39
+ expect(process.env.PI_TELEMETRY).toBe('0');
40
+ expect(process.env.PI_SKIP_VERSION_CHECK).toBe('1');
41
+ clean();
42
+ process.env.TA_TELEMETRY = '1';
43
+ TaBrand.activate('/opt/ta/dist/pi');
44
+ expect(process.env.PI_TELEMETRY).toBe('1');
45
+ });
46
+ });
@@ -0,0 +1,41 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+
4
+ export namespace TaBrand {
5
+ export const NAME = 'ta';
6
+
7
+ /** The settings of pi that ta's help lists as `TA_*`; pi reads only the `PI_*` names. */
8
+ export const ENV_ALIASES: Record<string, string> = {
9
+ TA_OFFLINE: 'PI_OFFLINE',
10
+ TA_SELF_UPDATE_COMMAND: 'PI_SELF_UPDATE_COMMAND',
11
+ TA_TELEMETRY: 'PI_TELEMETRY',
12
+ TA_SKIP_VERSION_CHECK: 'PI_SKIP_VERSION_CHECK',
13
+ };
14
+
15
+ /** Where pi keeps ta's files, without loading pi: an idle `ta serve` must not pay for it. */
16
+ export function agentDir(): string {
17
+ return process.env.TA_CODING_AGENT_DIR ?? join(homedir(), '.ta', 'agent');
18
+ }
19
+
20
+ /**
21
+ * Makes pi `ta`: its name, `~/.ta/agent`, project `.ta/` and `TA_CODING_AGENT_DIR` come from the
22
+ * `piConfig` of the package.json in `brandDir`, next to pi's assets and ta's patched build of pi
23
+ * (see the build of apps/ta), which `PiBundleUtil` then loads. Call it before pi is imported: pi
24
+ * reads them when it loads. The rest is what pi's own command does before `main`.
25
+ */
26
+ export function activate(brandDir: string): void {
27
+ process.env.PI_PACKAGE_DIR = brandDir;
28
+ for (const [ta, pi] of Object.entries(ENV_ALIASES)) {
29
+ if (process.env[ta] !== undefined) {
30
+ process.env[pi] = process.env[ta];
31
+ }
32
+ }
33
+ // pi's update check and install telemetry report to pi.dev about pi releases, which say nothing about ta's.
34
+ process.env.PI_SKIP_VERSION_CHECK ??= '1';
35
+ process.env.PI_TELEMETRY ??= '0';
36
+ process.env.PI_CODING_AGENT = 'true';
37
+ process.env.AI_AGENT = NAME;
38
+ process.title = NAME;
39
+ process.emitWarning = () => undefined;
40
+ }
41
+ }