@inneranimalmedia/agentsam-sdk 2.6.0 → 2.6.2

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 (145) hide show
  1. package/docs/AUTH_IDENTITY_CONTRACT.md +25 -27
  2. package/docs/PLATFORM_RUNTIME_EVENTS.md +48 -0
  3. package/docs/RELEASES.md +7 -7
  4. package/docs/SDK_WORKER.md +4 -3
  5. package/docs/SOURCE_ARCHITECTURE.md +58 -0
  6. package/docs/TEST_TIERS.md +26 -0
  7. package/migrations/runtime/0001_cli_runtime.sql +298 -0
  8. package/package.json +28 -7
  9. package/packages/agentsam-repository/README.md +15 -0
  10. package/packages/agentsam-repository/package.json +25 -0
  11. package/packages/agentsam-repository/src/contracts.js +113 -0
  12. package/packages/agentsam-repository/src/index.js +3 -0
  13. package/{src/lib → packages/agentsam-repository/src}/merkle/cloudflare-persistence.js +14 -24
  14. package/{src/lib → packages/agentsam-repository/src}/merkle/index.js +1 -0
  15. package/{src/lib → packages/agentsam-repository/src}/merkle/persistence.js +6 -4
  16. package/{src/lib → packages/agentsam-repository/src}/merkle/policy.js +1 -0
  17. package/packages/agentsam-repository/test/contracts.test.mjs +40 -0
  18. package/packages/agentsam-repository/test/git-context.test.mjs +24 -0
  19. package/{test/merkle.test.mjs → packages/agentsam-repository/test/merkle-core.test.mjs} +2 -32
  20. package/{test → packages/agentsam-repository/test}/merkle-persistence.test.mjs +11 -6
  21. package/packages/identity/package.json +2 -2
  22. package/packages/identity/src/contracts/auth-config.js +23 -40
  23. package/packages/identity/tests/auth-config.test.mjs +14 -23
  24. package/protocol/COMPANY_REPOSITORY_GRAPH_V1.md +91 -0
  25. package/protocol/MERKLE_PERSISTENCE_V1.md +2 -0
  26. package/protocol/MERKLE_PERSISTENCE_V2.md +40 -0
  27. package/protocol/repository/repository-contract.schema.json +24 -0
  28. package/protocol/repository/repository-dependency.schema.json +24 -0
  29. package/protocol/repository/repository-identity.schema.json +17 -0
  30. package/protocol/rpc/v1/common.proto +16 -0
  31. package/protocol/rpc/v1/errors.proto +35 -0
  32. package/protocol/rpc/v1/knowledge.proto +77 -0
  33. package/services/knowledge/package-lock.json +333 -0
  34. package/services/knowledge/package.json +5 -1
  35. package/src/agent/responses-runner.js +63 -35
  36. package/src/capabilities/repository-snapshot.js +3 -3
  37. package/src/cli.js +36 -29
  38. package/src/commands/account-auth.js +1 -1
  39. package/src/commands/context-economics.js +17 -2
  40. package/src/commands/context.js +1 -1
  41. package/src/commands/db.js +20 -3
  42. package/src/commands/deploy.js +2 -2
  43. package/src/commands/env.js +90 -0
  44. package/src/commands/knowledge.js +12 -4
  45. package/src/commands/merkle-persist.js +30 -11
  46. package/src/commands/merkle.js +1 -1
  47. package/src/commands/models.js +123 -65
  48. package/src/commands/ollama.js +26 -0
  49. package/src/commands/preferences.js +53 -26
  50. package/src/commands/providers.js +308 -0
  51. package/src/commands/shell.js +240 -48
  52. package/src/commands/tunnel.js +8 -8
  53. package/src/commands/whoami.js +42 -21
  54. package/src/errors/contract.js +236 -0
  55. package/src/errors/diagnostic.js +1 -0
  56. package/src/errors/index.js +14 -0
  57. package/src/index.js +13 -1
  58. package/src/knowledge/service/auth.js +13 -0
  59. package/src/knowledge/service/grpc-client.js +115 -0
  60. package/src/knowledge/service/grpc-codec.js +237 -0
  61. package/src/knowledge/service/grpc-server.js +83 -0
  62. package/src/knowledge/service/job-engine.js +248 -0
  63. package/src/knowledge/service/server.js +87 -135
  64. package/src/knowledge/source.js +1 -1
  65. package/src/lib/account-session.js +94 -25
  66. package/src/lib/auth.js +314 -51
  67. package/src/lib/cli-preferences.js +31 -4
  68. package/src/lib/core-client.js +75 -30
  69. package/src/lib/deploy-receipt/index.js +2 -2
  70. package/src/lib/detect-context.js +14 -16
  71. package/src/lib/knowledge-docker.js +6 -3
  72. package/src/lib/local-sessions.js +23 -2
  73. package/src/lib/local-status.js +1 -1
  74. package/src/lib/project-config.js +1 -1
  75. package/src/lib/provider-credentials.js +230 -14
  76. package/src/lib/slash-commands.js +5 -3
  77. package/src/local/migrations.js +93 -0
  78. package/src/local/runtime-store.js +141 -0
  79. package/src/local/sqlite.js +2 -0
  80. package/src/local-pty/server.js +113 -51
  81. package/src/models/discovery.js +327 -0
  82. package/src/providers/anthropic-messages.js +192 -0
  83. package/src/providers/cloudflare-chat.js +183 -0
  84. package/src/providers/factory.js +69 -0
  85. package/src/providers/gemini-generate-content.js +208 -0
  86. package/src/providers/index.js +5 -0
  87. package/src/providers/ollama-chat.js +148 -0
  88. package/src/providers/openai-responses.js +226 -75
  89. package/src/repository/index.js +14 -2
  90. package/src/rpc/generated/common_grpc_pb.js +1 -0
  91. package/src/rpc/generated/common_pb.js +536 -0
  92. package/src/rpc/generated/errors_grpc_pb.js +1 -0
  93. package/src/rpc/generated/errors_pb.js +482 -0
  94. package/src/rpc/generated/knowledge_grpc_pb.js +135 -0
  95. package/src/rpc/generated/knowledge_pb.js +2168 -0
  96. package/src/rpc/generated/package.json +3 -0
  97. package/src/security/trust-boundary.js +2 -2
  98. package/src/telemetry/events.js +4 -1
  99. package/src/ui/cli/activity.js +76 -0
  100. package/src/ui/cli/compaction.js +15 -0
  101. package/src/ui/cli/footer.js +39 -0
  102. package/src/ui/cli/help.js +194 -0
  103. package/src/ui/cli/plan.js +20 -0
  104. package/src/ui/cli/runtime-events.js +110 -0
  105. package/src/ui/cli/waiting.js +16 -0
  106. package/src/ui/merkle/render.js +1 -1
  107. package/test/account-session.test.mjs +48 -11
  108. package/test/apps-scaffold-contract.test.mjs +43 -0
  109. package/test/cli/preferences-runtime.test.mjs +11 -0
  110. package/test/cli/runtime-ui.test.mjs +74 -0
  111. package/test/error-diagnostics.test.mjs +57 -1
  112. package/test/fixtures/knowledge-rpc-worker.mjs +16 -0
  113. package/test/integration/cli-help.test.mjs +37 -0
  114. package/test/integration/knowledge-rpc.test.mjs +112 -0
  115. package/test/integration/merkle-cli.test.mjs +61 -0
  116. package/test/integration/merkle-persistence-identity.test.mjs +48 -0
  117. package/test/integration/provider-env-cli.test.mjs +49 -0
  118. package/test/integration/provider-factory.test.mjs +197 -0
  119. package/test/integration/repository-company-graph.test.mjs +90 -0
  120. package/test/integration/runtime-migrations.test.mjs +82 -0
  121. package/test/knowledge-service.test.mjs +5 -0
  122. package/test/knowledge.test.mjs +16 -0
  123. package/test/live/terminal-transport.live.test.mjs +24 -0
  124. package/test/local-sessions.test.mjs +7 -1
  125. package/test/models.test.mjs +101 -4
  126. package/test/ollama.test.mjs +21 -0
  127. package/test/portable-context.test.mjs +1 -1
  128. package/test/provider-credentials.test.mjs +45 -1
  129. package/test/release-hygiene.test.mjs +13 -5
  130. package/test/responses-runner.test.mjs +3 -1
  131. package/test/sdk-worker-contract.test.mjs +5 -1
  132. package/test/shell.test.mjs +50 -8
  133. package/test/smoke.mjs +2 -1
  134. package/test/terminal/local-pty.mock.test.mjs +151 -0
  135. package/test/whoami-resume.test.mjs +6 -5
  136. package/src/lib/prompt-byok.js +0 -57
  137. package/src/lib/save-sdk-token.js +0 -19
  138. /package/{src/lib → packages/agentsam-repository/src}/git-context.js +0 -0
  139. /package/{src/lib → packages/agentsam-repository/src}/merkle/diff.js +0 -0
  140. /package/{src/lib → packages/agentsam-repository/src}/merkle/filemeta.js +0 -0
  141. /package/{src/lib → packages/agentsam-repository/src}/merkle/git-ignore.js +0 -0
  142. /package/{src/lib → packages/agentsam-repository/src}/merkle/hash.js +0 -0
  143. /package/{src/lib → packages/agentsam-repository/src}/merkle/semantic.js +0 -0
  144. /package/{src/lib → packages/agentsam-repository/src}/merkle/snapshot.js +0 -0
  145. /package/{src/lib → packages/agentsam-repository/src}/merkle/tree.js +0 -0
@@ -0,0 +1,93 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const DEFAULT_MIGRATIONS_DIR = path.resolve(
6
+ path.dirname(fileURLToPath(import.meta.url)),
7
+ '..',
8
+ '..',
9
+ 'migrations',
10
+ 'runtime',
11
+ );
12
+
13
+ function migrationFiles(dir) {
14
+ if (!fs.existsSync(dir)) return [];
15
+ return fs.readdirSync(dir, { withFileTypes: true })
16
+ .filter((entry) => entry.isFile() && /^\d+.*\.sql$/i.test(entry.name))
17
+ .map((entry) => entry.name)
18
+ .sort((a, b) => a.localeCompare(b));
19
+ }
20
+
21
+ function ensureLedger(db) {
22
+ db.exec(`
23
+ CREATE TABLE IF NOT EXISTS agentsam_schema_migrations (
24
+ id TEXT PRIMARY KEY,
25
+ applied_at_unix INTEGER NOT NULL DEFAULT (unixepoch()),
26
+ checksum TEXT
27
+ );
28
+ `);
29
+ }
30
+
31
+ function checksumSource(source) {
32
+ let hash = 2166136261;
33
+ for (let i = 0; i < source.length; i += 1) {
34
+ hash ^= source.charCodeAt(i);
35
+ hash = Math.imul(hash, 16777619);
36
+ }
37
+ return 'fnv1a32:' + (hash >>> 0).toString(16).padStart(8, '0');
38
+ }
39
+
40
+ export async function listAppliedMigrations(db) {
41
+ ensureLedger(db);
42
+ const result = await db.prepare(
43
+ 'SELECT id, applied_at_unix, checksum FROM agentsam_schema_migrations ORDER BY id'
44
+ ).all();
45
+ return result.results || [];
46
+ }
47
+
48
+ export async function applyRuntimeMigrations(db, options = {}) {
49
+ const dir = path.resolve(options.migrationsDir || DEFAULT_MIGRATIONS_DIR);
50
+ ensureLedger(db);
51
+ const appliedRows = await listAppliedMigrations(db);
52
+ const applied = new Map(appliedRows.map((row) => [String(row.id), row]));
53
+ const results = [];
54
+
55
+ for (const filename of migrationFiles(dir)) {
56
+ const id = filename.replace(/\.sql$/i, '');
57
+ const source = fs.readFileSync(path.join(dir, filename), 'utf8');
58
+ const checksum = checksumSource(source);
59
+ const previous = applied.get(id);
60
+
61
+ if (previous) {
62
+ if (previous.checksum && previous.checksum !== checksum) {
63
+ throw new Error('migration_checksum_mismatch:' + id);
64
+ }
65
+ results.push({ id, filename, status: 'already_applied', checksum });
66
+ continue;
67
+ }
68
+
69
+ db.exec('BEGIN IMMEDIATE');
70
+ try {
71
+ db.exec(source);
72
+ await db.prepare(
73
+ 'INSERT INTO agentsam_schema_migrations (id, checksum) VALUES (?, ?)'
74
+ ).bind(id, checksum).run();
75
+ db.exec('COMMIT');
76
+ results.push({ id, filename, status: 'applied', checksum });
77
+ } catch (error) {
78
+ try { db.exec('ROLLBACK'); } catch {}
79
+ throw new Error('migration_failed:' + id + ':' + (error?.message || error));
80
+ }
81
+ }
82
+
83
+ return Object.freeze({
84
+ migrationsDir: dir,
85
+ total: results.length,
86
+ applied: results.filter((row) => row.status === 'applied').length,
87
+ results: Object.freeze(results),
88
+ });
89
+ }
90
+
91
+ export function runtimeMigrationsDirectory() {
92
+ return DEFAULT_MIGRATIONS_DIR;
93
+ }
@@ -0,0 +1,141 @@
1
+ import path from 'node:path';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { createLocalSqliteDatabase } from './sqlite.js';
4
+ import { applyRuntimeMigrations } from './migrations.js';
5
+
6
+ function clean(value) { return value == null ? '' : String(value).trim(); }
7
+ function hash(value) { return createHash('sha256').update(String(value || '')).digest('hex'); }
8
+
9
+ export function runtimeDatabasePath(cwd = process.cwd()) {
10
+ return path.join(path.resolve(cwd), '.agentsam', 'data', 'agentsam.sqlite');
11
+ }
12
+
13
+ async function withStore(cwd, fn) {
14
+ const db = await createLocalSqliteDatabase(runtimeDatabasePath(cwd));
15
+ try {
16
+ await applyRuntimeMigrations(db);
17
+ return await fn(db);
18
+ } finally {
19
+ db.close();
20
+ }
21
+ }
22
+
23
+ export function createRuntimeRunId() {
24
+ return `arun_${randomUUID()}`;
25
+ }
26
+
27
+ export async function startRuntimeRun(value = {}) {
28
+ const id = clean(value.id) || createRuntimeRunId();
29
+ await withStore(value.cwd, async (db) => {
30
+ await db.prepare(`
31
+ INSERT INTO agentsam_agent_run (
32
+ id, account_id, source_client, surface, mode, model_key,
33
+ reasoning_effort, requested_service_tier, status, started_at_unix, updated_at_unix
34
+ ) VALUES (?, ?, 'agentsam-cli', 'cli', ?, ?, ?, ?, 'running', unixepoch(), unixepoch())
35
+ `).bind(
36
+ id,
37
+ clean(value.account_id) || null,
38
+ clean(value.mode) || 'agent',
39
+ clean(value.model_key) || null,
40
+ clean(value.reasoning_effort) || null,
41
+ clean(value.service_tier) || null,
42
+ ).run();
43
+ });
44
+ return id;
45
+ }
46
+
47
+ export async function finishRuntimeRun(value = {}) {
48
+ if (!clean(value.id)) return;
49
+ await withStore(value.cwd, async (db) => {
50
+ const usage = value.usage || {};
51
+ await db.prepare(`
52
+ UPDATE agentsam_agent_run
53
+ SET status = ?,
54
+ actual_service_tier = COALESCE(?, actual_service_tier),
55
+ input_tokens = ?,
56
+ cached_input_tokens = ?,
57
+ output_tokens = ?,
58
+ reasoning_tokens = ?,
59
+ cost_usd = ?,
60
+ error_code = ?,
61
+ error_message = ?,
62
+ completed_at_unix = unixepoch(),
63
+ updated_at_unix = unixepoch(),
64
+ latency_ms = ?
65
+ WHERE id = ?
66
+ `).bind(
67
+ clean(value.status) || 'completed',
68
+ clean(value.actual_service_tier) || null,
69
+ Number(usage.input_tokens || 0),
70
+ Number(usage.cached_input_tokens || 0),
71
+ Number(usage.output_tokens || 0),
72
+ Number(usage.reasoning_tokens || 0),
73
+ Math.max(0, Number(value.cost_usd || 0)),
74
+ clean(value.error_code) || null,
75
+ clean(value.error_message) || null,
76
+ Number.isFinite(Number(value.latency_ms)) ? Math.max(0, Math.round(Number(value.latency_ms))) : null,
77
+ value.id,
78
+ ).run();
79
+ });
80
+ }
81
+
82
+ export async function recordRuntimeCompaction(value = {}) {
83
+ if (!clean(value.agent_run_id)) return null;
84
+ const id = clean(value.id) || `cmp_${randomUUID()}`;
85
+ const summary = clean(value.summary_text);
86
+ const before = Math.max(0, Math.round(Number(value.tokens_before || 0)));
87
+ const after = Math.max(0, Math.round(Number(value.tokens_after || 0)));
88
+ const sourceHash = hash(summary || JSON.stringify(value.metadata || {}));
89
+
90
+ await withStore(value.cwd, async (db) => {
91
+ await db.prepare(`
92
+ INSERT INTO agentsam_compaction_events (
93
+ id, account_id, agent_run_id, compaction_type, compaction_scope,
94
+ compaction_strategy, source_kind, content_hash, provider, model_key,
95
+ tokens_before, tokens_after, status, summary_text, summary_json,
96
+ metrics_json, metadata_json, source_stored
97
+ ) VALUES (?, ?, ?, 'context_summary', 'agent_run', 'summarize', ?, ?, ?, ?, ?, ?, 'completed', ?, ?, ?, ?, ?)
98
+ `).bind(
99
+ id,
100
+ clean(value.account_id) || null,
101
+ value.agent_run_id,
102
+ clean(value.source_kind) || 'api',
103
+ sourceHash,
104
+ clean(value.provider),
105
+ clean(value.model_key),
106
+ before,
107
+ after,
108
+ summary,
109
+ JSON.stringify({ summary }),
110
+ JSON.stringify({ tokens_before: before, tokens_after: after, tokens_saved: before - after }),
111
+ JSON.stringify(value.metadata || {}),
112
+ clean(value.source_stored) || 'local:agentsam_compaction_events',
113
+ ).run();
114
+
115
+ if (summary) {
116
+ const digestId = `ctx_${randomUUID()}`;
117
+ const digestHash = hash(`${value.agent_run_id}:${id}:${summary}`);
118
+ await db.prepare(`
119
+ INSERT INTO agentsam_context_digest (
120
+ id, account_id, digest_type, agent_run_id, session_id,
121
+ source_hash, digest_hash, raw_size_bytes, reduced_size_bytes,
122
+ token_count, digest_text, generation_model, compaction_event_id
123
+ ) VALUES (?, ?, 'session', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
124
+ `).bind(
125
+ digestId,
126
+ clean(value.account_id) || null,
127
+ value.agent_run_id,
128
+ clean(value.session_id) || null,
129
+ sourceHash,
130
+ digestHash,
131
+ Number(value.raw_size_bytes || 0) || null,
132
+ Buffer.byteLength(summary, 'utf8'),
133
+ after || Math.ceil(summary.length / 4),
134
+ summary,
135
+ clean(value.model_key) || null,
136
+ id,
137
+ ).run();
138
+ }
139
+ });
140
+ return id;
141
+ }
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { applyRuntimeMigrations } from './migrations.js';
3
4
 
4
5
  async function loadSqlite() {
5
6
  try {
@@ -77,6 +78,7 @@ export async function initializeLocalSqlite({
77
78
  const db = await createLocalSqliteDatabase(resolvedDb);
78
79
  try {
79
80
  db.exec(schema);
81
+ await applyRuntimeMigrations(db);
80
82
  } finally {
81
83
  db.close();
82
84
  }
@@ -2,7 +2,10 @@
2
2
  * Agent Sam local PTY — localhost WebSocket shell, no tunnel, no IAM.
3
3
  * Compatible with iam-pty wire format (raw bytes + JSON resize/slash).
4
4
  */
5
+ import fs from 'node:fs';
5
6
  import http from 'node:http';
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
6
9
  import { WebSocketServer } from 'ws';
7
10
 
8
11
  const DEFAULT_PORT = 3099;
@@ -17,8 +20,45 @@ function shellForPlatform() {
17
20
  return process.env.SHELL || '/bin/zsh';
18
21
  }
19
22
 
20
- async function loadPty() {
23
+ export function ensureNodePtySpawnHelperExecutable(options = {}) {
24
+ const platform = options.platform || process.platform;
25
+ const arch = options.arch || process.arch;
26
+ if (platform !== 'darwin') return Object.freeze({ checked: false, changed: false, path: null });
27
+
28
+ const resolveModule = options.resolveModule || ((specifier) => import.meta.resolve(specifier));
29
+ const fsImpl = options.fs || fs;
30
+ const entryUrl = resolveModule('node-pty');
31
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(entryUrl)), '..');
32
+ const helperPath = path.join(packageRoot, 'prebuilds', `darwin-${arch}`, 'spawn-helper');
33
+
34
+ if (!fsImpl.existsSync(helperPath)) {
35
+ return Object.freeze({ checked: true, changed: false, path: helperPath, missing: true });
36
+ }
37
+
38
+ const stat = fsImpl.statSync(helperPath);
39
+ if ((stat.mode & 0o111) !== 0) {
40
+ return Object.freeze({ checked: true, changed: false, path: helperPath });
41
+ }
42
+
21
43
  try {
44
+ fsImpl.chmodSync(helperPath, stat.mode | 0o111);
45
+ } catch (error) {
46
+ const wrapped = new Error(
47
+ `node-pty spawn-helper is not executable and Agent Sam could not repair it at ${helperPath}. ` +
48
+ `Reinstall node-pty with install scripts enabled or make that helper executable. ${error?.message || error}`,
49
+ );
50
+ wrapped.code = 'node_pty_spawn_helper_not_executable';
51
+ wrapped.cause = error;
52
+ throw wrapped;
53
+ }
54
+
55
+ return Object.freeze({ checked: true, changed: true, path: helperPath });
56
+ }
57
+
58
+ async function loadPty(override) {
59
+ if (override?.spawn) return override;
60
+ try {
61
+ ensureNodePtySpawnHelperExecutable();
22
62
  const mod = await import('node-pty');
23
63
  return mod.default || mod;
24
64
  } catch (e) {
@@ -29,12 +69,69 @@ async function loadPty() {
29
69
  }
30
70
 
31
71
  /**
32
- * @param {{ cwd?: string, port?: number, host?: string }} [opts]
72
+ * Attach the portable PTY wire protocol to an already-created WebSocket-like transport.
73
+ * Exported so the release gate can test terminal semantics against an in-memory mock transport.
74
+ */
75
+ export function attachLocalPtySession({ ws, pty, shell, cwd, cols = 80, rows = 24, env = process.env, sessionId } = {}) {
76
+ if (!ws?.on || !ws?.send) throw new TypeError('ws transport with on/send is required');
77
+ if (!pty?.spawn) throw new TypeError('pty transport with spawn is required');
78
+ const term = pty.spawn(shell, [], {
79
+ name: 'xterm-256color',
80
+ cols,
81
+ rows,
82
+ cwd,
83
+ env: { ...env, TERM: 'xterm-256color', AGENTSAM_LOCAL_PTY: '1' },
84
+ });
85
+ const id = sessionId || `local_${Date.now().toString(36)}`;
86
+ const openState = ws.OPEN ?? 1;
87
+ const isOpen = () => ws.readyState == null || ws.readyState === openState;
88
+
89
+ ws.send(JSON.stringify({ type: 'session_id', session_id: id }));
90
+
91
+ term.onData((data) => {
92
+ if (isOpen()) ws.send(data);
93
+ });
94
+
95
+ ws.on('message', (raw) => {
96
+ const text = raw.toString();
97
+ try {
98
+ const msg = JSON.parse(text);
99
+ if (msg.type === 'resize' && msg.cols && msg.rows) {
100
+ term.resize(msg.cols, msg.rows);
101
+ return;
102
+ }
103
+ if (msg.type === 'slash' && msg.line) {
104
+ term.write(`${msg.line}\r`);
105
+ return;
106
+ }
107
+ } catch {
108
+ /* raw PTY input */
109
+ }
110
+ term.write(text);
111
+ });
112
+
113
+ let cleaned = false;
114
+ const cleanup = () => {
115
+ if (cleaned) return;
116
+ cleaned = true;
117
+ try { term.kill(); } catch { /* ignore */ }
118
+ };
119
+ term.onExit(() => {
120
+ if (isOpen() && ws.close) ws.close();
121
+ });
122
+ ws.on('close', cleanup);
123
+ ws.on('error', cleanup);
124
+
125
+ return Object.freeze({ session_id: id, term, cleanup });
126
+ }
127
+
128
+ /**
129
+ * @param {{ cwd?: string, port?: number, host?: string, pty?: { spawn: Function } }} [opts]
33
130
  */
34
131
  export async function startLocalPtyServer(opts = {}) {
35
- const pty = await loadPty();
132
+ const pty = await loadPty(opts.pty);
36
133
  const cwd = opts.cwd || process.cwd();
37
- const port = parsePort(opts.port ?? process.env.PTY_PORT, DEFAULT_PORT);
134
+ const requestedPort = opts.port === 0 ? 0 : parsePort(opts.port ?? process.env.PTY_PORT, DEFAULT_PORT);
38
135
  const host = opts.host || '127.0.0.1';
39
136
  const shell = shellForPlatform();
40
137
 
@@ -47,7 +144,7 @@ export async function startLocalPtyServer(opts = {}) {
47
144
  ok: true,
48
145
  service: 'agentsam-local-pty',
49
146
  cwd,
50
- port,
147
+ port: Number(httpServer.address()?.port || requestedPort),
51
148
  shell,
52
149
  }),
53
150
  );
@@ -65,64 +162,29 @@ export async function startLocalPtyServer(opts = {}) {
65
162
  const cols = parsePort(url.searchParams.get('cols'), 80);
66
163
  const rows = parsePort(url.searchParams.get('rows'), 24);
67
164
 
68
- const term = pty.spawn(shell, [], {
69
- name: 'xterm-256color',
165
+ attachLocalPtySession({
166
+ ws,
167
+ pty,
168
+ shell,
169
+ cwd: sessionCwd,
70
170
  cols,
71
171
  rows,
72
- cwd: sessionCwd,
73
- env: { ...process.env, TERM: 'xterm-256color', AGENTSAM_LOCAL_PTY: '1' },
74
- });
75
-
76
- const sessionId = `local_${Date.now().toString(36)}`;
77
- ws.send(JSON.stringify({ type: 'session_id', session_id: sessionId }));
78
-
79
- term.onData((data) => {
80
- if (ws.readyState === ws.OPEN) ws.send(data);
81
- });
82
-
83
- ws.on('message', (raw) => {
84
- const text = raw.toString();
85
- try {
86
- const msg = JSON.parse(text);
87
- if (msg.type === 'resize' && msg.cols && msg.rows) {
88
- term.resize(msg.cols, msg.rows);
89
- return;
90
- }
91
- if (msg.type === 'slash' && msg.line) {
92
- term.write(`${msg.line}\r`);
93
- return;
94
- }
95
- } catch {
96
- /* raw PTY input */
97
- }
98
- term.write(text);
99
- });
100
-
101
- const cleanup = () => {
102
- try {
103
- term.kill();
104
- } catch {
105
- /* ignore */
106
- }
107
- };
108
- term.onExit(() => {
109
- if (ws.readyState === ws.OPEN) ws.close();
172
+ env: process.env,
110
173
  });
111
- ws.on('close', cleanup);
112
- ws.on('error', cleanup);
113
174
  });
114
175
 
115
176
  await new Promise((resolve) => {
116
- httpServer.listen(port, host, resolve);
177
+ httpServer.listen(requestedPort, host, resolve);
117
178
  });
179
+ const boundPort = Number(httpServer.address()?.port || requestedPort);
118
180
 
119
181
  return {
120
- port,
182
+ port: boundPort,
121
183
  host,
122
184
  cwd,
123
185
  shell,
124
- url: `ws://${host}:${port}`,
125
- healthUrl: `http://${host}:${port}/health`,
186
+ url: `ws://${host}:${boundPort}`,
187
+ healthUrl: `http://${host}:${boundPort}/health`,
126
188
  close: () =>
127
189
  new Promise((resolve, reject) => {
128
190
  wss.close(() => {