offsite 0.0.2 → 0.0.4

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 (114) hide show
  1. package/README.md +18 -7
  2. package/apps/server/dist/main.mjs +5767 -0
  3. package/apps/server/dist/main.mjs.map +1 -0
  4. package/apps/web/dist/assets/{angular-html-Oa9dnZbT.js → angular-html-prQpjz7s.js} +1 -1
  5. package/apps/web/dist/assets/{angular-ts-F_BIbY2H.js → angular-ts-BE4HJ5Uh.js} +1 -1
  6. package/apps/web/dist/assets/{apl-D7AuiKiV.js → apl-CJ-NIQ-7.js} +1 -1
  7. package/apps/web/dist/assets/{astro-DnpymQyW.js → astro-CVkyXRVY.js} +1 -1
  8. package/apps/web/dist/assets/{blade-CZZrW0iI.js → blade-CQFMHse_.js} +1 -1
  9. package/apps/web/dist/assets/{c-V_Rix0w2.js → c-gqNWYRL8.js} +1 -1
  10. package/apps/web/dist/assets/{chapel-fGtLLMYq.js → chapel-CQ9_BV4j.js} +1 -1
  11. package/apps/web/dist/assets/{cobol-BFOTnbFa.js → cobol-D-9v184m.js} +1 -1
  12. package/apps/web/dist/assets/{coffee-BdvfipEg.js → coffee-BE0tIOLL.js} +1 -1
  13. package/apps/web/dist/assets/{cpp-D_NFR3H2.js → cpp-CzOLC-NF.js} +1 -1
  14. package/apps/web/dist/assets/{crystal-BM2vkBPa.js → crystal-f1GcBNi_.js} +1 -1
  15. package/apps/web/dist/assets/{css-Byur6C5q.js → css-DlqRAumc.js} +1 -1
  16. package/apps/web/dist/assets/{edge-CP-KL2DQ.js → edge-DQkkPJaW.js} +1 -1
  17. package/apps/web/dist/assets/{elixir-CiO075Fh.js → elixir-ClG78o74.js} +1 -1
  18. package/apps/web/dist/assets/{elm-DIyG-d95.js → elm-DZDmCmuw.js} +1 -1
  19. package/apps/web/dist/assets/{erb-DHZK6WKc.js → erb-B1mu0-DN.js} +1 -1
  20. package/apps/web/dist/assets/{git-rebase-CxXKbwiy.js → git-rebase-x1gs-rK2.js} +1 -1
  21. package/apps/web/dist/assets/{glimmer-js-BUhQC_gD.js → glimmer-js-Cjos1igW.js} +1 -1
  22. package/apps/web/dist/assets/{glimmer-ts-D2lLByyw.js → glimmer-ts-CrR-PFvn.js} +1 -1
  23. package/apps/web/dist/assets/{glsl-BMvlWqE_.js → glsl-DR0G8e99.js} +1 -1
  24. package/apps/web/dist/assets/{graphql-D9UFk_fJ.js → graphql-DKmrBZt7.js} +1 -1
  25. package/apps/web/dist/assets/{hack-BZAO0Jc2.js → hack-Brs_j9Xv.js} +1 -1
  26. package/apps/web/dist/assets/{haml-Dm5wroII.js → haml-8Lc-lF96.js} +1 -1
  27. package/apps/web/dist/assets/{handlebars-C9L1Bn7f.js → handlebars-Ds8WdPdv.js} +1 -1
  28. package/apps/web/dist/assets/{html-Bz91Luf0.js → html-C0gvYDho.js} +1 -1
  29. package/apps/web/dist/assets/{html-derivative-hIdjVrpA.js → html-derivative-CU9dkErg.js} +1 -1
  30. package/apps/web/dist/assets/{http-AWG6aeFM.js → http-BE0w0Fty.js} +1 -1
  31. package/apps/web/dist/assets/{hurl-pSGcpqgh.js → hurl-DqZk6YcW.js} +1 -1
  32. package/apps/web/dist/assets/index-0B-Gdd7b.css +2 -0
  33. package/apps/web/dist/assets/index-rgKS_aMw.js +1148 -0
  34. package/apps/web/dist/assets/{java-D_CyC-X4.js → java-PSSQ0YmM.js} +1 -1
  35. package/apps/web/dist/assets/{javascript-PK4jkG9t.js → javascript-Ci3r4rzs.js} +1 -1
  36. package/apps/web/dist/assets/{jinja-Cu3wzgkz.js → jinja-lLTko9Wl.js} +1 -1
  37. package/apps/web/dist/assets/{jison-CHevE1W8.js → jison-1BpHD5UK.js} +1 -1
  38. package/apps/web/dist/assets/{json-DPTkd0bP.js → json-BAUn76M4.js} +1 -1
  39. package/apps/web/dist/assets/{jsx-DcsDzCOA.js → jsx-B8sFp1vz.js} +1 -1
  40. package/apps/web/dist/assets/{julia-B9tMVOL0.js → julia-C4TZ4EL9.js} +1 -1
  41. package/apps/web/dist/assets/{just-BHIhrE9N.js → just-D5qIrqkp.js} +1 -1
  42. package/apps/web/dist/assets/{latex-CY05HK-G.js → latex-BL7XYxFg.js} +1 -1
  43. package/apps/web/dist/assets/{liquid-DJaL8XK2.js → liquid-DBx9Hq7B.js} +1 -1
  44. package/apps/web/dist/assets/{lua-BfaWUinJ.js → lua-BqjicQyd.js} +1 -1
  45. package/apps/web/dist/assets/{marko-0Lc0z7w6.js → marko-CHgy7yaY.js} +1 -1
  46. package/apps/web/dist/assets/{mdc-DEhXNYDZ.js → mdc-DOloBwb8.js} +1 -1
  47. package/apps/web/dist/assets/{nginx-DLuBebI5.js → nginx-g7I1HPwV.js} +1 -1
  48. package/apps/web/dist/assets/{nim-BIJh7lZB.js → nim-O6zJV1LD.js} +1 -1
  49. package/apps/web/dist/assets/{org-BFpxb2WJ.js → org-HLg4-757.js} +1 -1
  50. package/apps/web/dist/assets/{perl-DHbDMq2q.js → perl-B3cDKTai.js} +1 -1
  51. package/apps/web/dist/assets/{php-BcVbiJpZ.js → php-2eDApoU3.js} +1 -1
  52. package/apps/web/dist/assets/{pug-bdfyK-rS.js → pug-itzGn-nK.js} +1 -1
  53. package/apps/web/dist/assets/{qml-BC2D8eWk.js → qml-sU0VtUmf.js} +1 -1
  54. package/apps/web/dist/assets/{r-O3zbZ-YT.js → r-C6mhPqgr.js} +1 -1
  55. package/apps/web/dist/assets/{razor-Ffnu5_vD.js → razor-CSzRtbW7.js} +1 -1
  56. package/apps/web/dist/assets/{regexp-dnbUAgjx.js → regexp-BmdBJRV9.js} +1 -1
  57. package/apps/web/dist/assets/{rst-DJfy2dSm.js → rst-BRxUd6sp.js} +1 -1
  58. package/apps/web/dist/assets/{ruby-DGEpA0mD.js → ruby-CQHHOfmX.js} +1 -1
  59. package/apps/web/dist/assets/{sas-CZvL8X8k.js → sas-DlaL8b25.js} +1 -1
  60. package/apps/web/dist/assets/{scss-BtNSCzZB.js → scss-Cc71ABWp.js} +1 -1
  61. package/apps/web/dist/assets/{shellscript-uR-sOZlr.js → shellscript-CzA_LIIm.js} +1 -1
  62. package/apps/web/dist/assets/{shellsession-BT-Jl4S5.js → shellsession-DESJlgp3.js} +1 -1
  63. package/apps/web/dist/assets/{soy-BjfL_vrj.js → soy-Nkvq88YN.js} +1 -1
  64. package/apps/web/dist/assets/{sql-fa1gAeRF.js → sql-CtPxrO7T.js} +1 -1
  65. package/apps/web/dist/assets/{stata-DgTOpGhg.js → stata-BacEfVTr.js} +1 -1
  66. package/apps/web/dist/assets/{surrealql-DVqEkJeu.js → surrealql-CYW10JNe.js} +1 -1
  67. package/apps/web/dist/assets/{svelte-CyQ5sU9I.js → svelte-D3_tCKGs.js} +1 -1
  68. package/apps/web/dist/assets/{templ-DrztMbAf.js → templ-BGKIfY_b.js} +1 -1
  69. package/apps/web/dist/assets/{tex-NAwM8Kkh.js → tex-BkkYOaXX.js} +1 -1
  70. package/apps/web/dist/assets/{ts-tags-DX96dDxh.js → ts-tags-B02tnbpZ.js} +1 -1
  71. package/apps/web/dist/assets/{tsx-D3PnhDHK.js → tsx-D3MB1IUf.js} +1 -1
  72. package/apps/web/dist/assets/{twig-FG0P9evf.js → twig-CPhw2wGK.js} +1 -1
  73. package/apps/web/dist/assets/{typescript-Crqeuw0P.js → typescript-B7U4faGm.js} +1 -1
  74. package/apps/web/dist/assets/{typst-CO_2MFRr.js → typst-CN9EZswy.js} +1 -1
  75. package/apps/web/dist/assets/{vue-fTNrS0Q3.js → vue-YH8dfjo_.js} +1 -1
  76. package/apps/web/dist/assets/{vue-html-E0ptmXwc.js → vue-html-NwX2xzgp.js} +1 -1
  77. package/apps/web/dist/assets/{vue-vine-C34_rJIu.js → vue-vine-DoRmnjLj.js} +1 -1
  78. package/apps/web/dist/assets/{xml-BB9WbMMU.js → xml-DgfgLpPc.js} +1 -1
  79. package/apps/web/dist/assets/{xsl-B3w2P7LL.js → xsl-CEwQRUK_.js} +1 -1
  80. package/apps/web/dist/assets/{yaml-BKGRKqBA.js → yaml-CEFOzF95.js} +1 -1
  81. package/apps/web/dist/icon.svg +5 -0
  82. package/apps/web/dist/index.html +2 -2
  83. package/apps/web/dist/sw.js +19 -8
  84. package/bin/offsite.js +1 -1
  85. package/package.json +6 -1
  86. package/apps/server/dist/args.js +0 -11
  87. package/apps/server/dist/claude.js +0 -207
  88. package/apps/server/dist/config.js +0 -185
  89. package/apps/server/dist/content.js +0 -172
  90. package/apps/server/dist/db.js +0 -13
  91. package/apps/server/dist/files.js +0 -50
  92. package/apps/server/dist/git.js +0 -133
  93. package/apps/server/dist/history.js +0 -137
  94. package/apps/server/dist/hub.js +0 -10
  95. package/apps/server/dist/main.js +0 -64
  96. package/apps/server/dist/projects.js +0 -92
  97. package/apps/server/dist/protocol.js +0 -20
  98. package/apps/server/dist/push.js +0 -152
  99. package/apps/server/dist/run.js +0 -375
  100. package/apps/server/dist/runs.js +0 -102
  101. package/apps/server/dist/schemes.js +0 -262
  102. package/apps/server/dist/sessions.js +0 -65
  103. package/apps/server/dist/socket.js +0 -149
  104. package/apps/server/dist/storage.js +0 -22
  105. package/apps/server/dist/terminal/alerts.js +0 -145
  106. package/apps/server/dist/terminal/process.js +0 -207
  107. package/apps/server/dist/terminal/shell-check.js +0 -91
  108. package/apps/server/dist/terminal/shell-integration.js +0 -112
  109. package/apps/server/dist/terminal/terminal.js +0 -402
  110. package/apps/web/dist/assets/index-BiLbXfDN.js +0 -899
  111. package/apps/web/dist/assets/index-DQIK-TpZ.css +0 -2
  112. /package/apps/server/src/{terminal → services/terminal}/shell-integration/bash/offsite.bash +0 -0
  113. /package/apps/server/src/{terminal → services/terminal}/shell-integration/fish/offsite.fish +0 -0
  114. /package/apps/server/src/{terminal → services/terminal}/shell-integration/zsh/.zshenv +0 -0
@@ -1,172 +0,0 @@
1
- export function toMessage(type, item, time) {
2
- return {
3
- type,
4
- uuid: item.uuid,
5
- time,
6
- content: isRecord(item.message) ? toBlocks(item.message.content) : [],
7
- parent: item.parent_tool_use_id,
8
- };
9
- }
10
- export function contextTokens(message) {
11
- if (!isRecord(message) || !isRecord(message.usage))
12
- return null;
13
- const usage = message.usage;
14
- return [
15
- usage.input_tokens,
16
- usage.cache_creation_input_tokens,
17
- usage.cache_read_input_tokens,
18
- usage.output_tokens,
19
- ].reduce((total, value) => total + (typeof value === 'number' ? value : 0), 0);
20
- }
21
- export function toContext(usage) {
22
- const messages = usage.messageBreakdown;
23
- const sections = [
24
- {
25
- title: 'Messages',
26
- items: messages === undefined
27
- ? []
28
- : [
29
- { name: 'User messages', tokens: messages.userMessageTokens },
30
- {
31
- name: 'Assistant messages',
32
- tokens: messages.assistantMessageTokens,
33
- },
34
- { name: 'Tool calls', tokens: messages.toolCallTokens },
35
- { name: 'Tool results', tokens: messages.toolResultTokens },
36
- { name: 'Attachments', tokens: messages.attachmentTokens },
37
- ],
38
- },
39
- {
40
- title: 'Tools used',
41
- items: (messages?.toolCallsByType ?? []).map((tool) => ({
42
- name: tool.name,
43
- tokens: tool.callTokens + tool.resultTokens,
44
- })),
45
- },
46
- {
47
- title: 'Memory files',
48
- items: usage.memoryFiles.map((file) => ({
49
- name: file.path,
50
- tokens: file.tokens,
51
- })),
52
- },
53
- {
54
- title: 'MCP tools',
55
- items: usage.mcpTools.map((tool) => ({
56
- name: `${tool.serverName} · ${tool.name}`,
57
- tokens: tool.tokens,
58
- })),
59
- },
60
- {
61
- title: 'Agents',
62
- items: usage.agents.map((agent) => ({
63
- name: agent.agentType,
64
- tokens: agent.tokens,
65
- })),
66
- },
67
- {
68
- title: 'Skills',
69
- items: (usage.skills?.skillFrontmatter ?? []).map((skill) => ({
70
- name: skill.name,
71
- tokens: skill.tokens,
72
- })),
73
- },
74
- {
75
- title: 'Last response',
76
- items: usage.apiUsage === null
77
- ? []
78
- : [
79
- { name: 'Input', tokens: usage.apiUsage.input_tokens },
80
- {
81
- name: 'Cache read',
82
- tokens: usage.apiUsage.cache_read_input_tokens,
83
- },
84
- {
85
- name: 'Cache write',
86
- tokens: usage.apiUsage.cache_creation_input_tokens,
87
- },
88
- { name: 'Output', tokens: usage.apiUsage.output_tokens },
89
- ],
90
- },
91
- ];
92
- return {
93
- tokens: usage.totalTokens,
94
- window: usage.maxTokens,
95
- model: usage.model,
96
- categories: usage.categories.flatMap((category) => category.kind === 'deferred'
97
- ? []
98
- : [
99
- {
100
- name: category.name,
101
- tokens: category.tokens,
102
- kind: category.kind,
103
- },
104
- ]),
105
- sections: sections
106
- .map((section) => ({
107
- title: section.title,
108
- items: section.items.filter((item) => item.tokens > 0),
109
- }))
110
- .filter((section) => section.items.length > 0),
111
- };
112
- }
113
- function toBlocks(content) {
114
- if (typeof content === 'string')
115
- return [{ type: 'text', text: content }];
116
- if (!Array.isArray(content))
117
- return [];
118
- return content.flatMap((block) => {
119
- if (!isRecord(block))
120
- return [];
121
- switch (block.type) {
122
- case 'text':
123
- return typeof block.text === 'string' &&
124
- !block.text.startsWith('<system-reminder>') &&
125
- !block.text.startsWith('<local-command-caveat>')
126
- ? [{ type: 'text', text: block.text }]
127
- : [];
128
- case 'thinking':
129
- return typeof block.thinking === 'string' && block.thinking !== ''
130
- ? [{ type: 'thinking', thinking: block.thinking }]
131
- : [];
132
- case 'image': {
133
- const source = block.source;
134
- return isRecord(source) &&
135
- source.type === 'base64' &&
136
- typeof source.media_type === 'string' &&
137
- typeof source.data === 'string'
138
- ? [{ type: 'image', mediaType: source.media_type, data: source.data }]
139
- : [];
140
- }
141
- case 'tool_use':
142
- return typeof block.id === 'string' &&
143
- typeof block.name === 'string' &&
144
- isRecord(block.input)
145
- ? [
146
- {
147
- type: 'tool_use',
148
- id: block.id,
149
- name: block.name,
150
- input: block.input,
151
- },
152
- ]
153
- : [];
154
- case 'tool_result':
155
- return typeof block.tool_use_id === 'string'
156
- ? [
157
- {
158
- type: 'tool_result',
159
- toolUseId: block.tool_use_id,
160
- content: toBlocks(block.content),
161
- isError: block.is_error === true,
162
- },
163
- ]
164
- : [];
165
- default:
166
- return [];
167
- }
168
- });
169
- }
170
- function isRecord(value) {
171
- return typeof value === 'object' && value !== null && !Array.isArray(value);
172
- }
@@ -1,13 +0,0 @@
1
- import { mkdirSync } from 'node:fs';
2
- import path from 'node:path';
3
- import { DatabaseSync } from 'node:sqlite';
4
- import { home } from './storage.js';
5
- mkdirSync(home, { recursive: true });
6
- export const db = new DatabaseSync(path.join(home, 'offsite.db'));
7
- db.exec(`
8
- CREATE TABLE IF NOT EXISTS projects (
9
- path TEXT PRIMARY KEY,
10
- name TEXT NOT NULL,
11
- logo TEXT
12
- )
13
- `);
@@ -1,50 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { mkdirSync, readdirSync, writeFileSync } from 'node:fs';
3
- import path from 'node:path';
4
- import { git } from './git.js';
5
- import { home } from './storage.js';
6
- const FILE_LIMIT = 20_000;
7
- const skipped = new Set(['node_modules', '.git', 'dist', 'target', '.next']);
8
- export async function listFiles(cwd) {
9
- try {
10
- const { stdout } = await git(cwd, [
11
- 'ls-files',
12
- '--cached',
13
- '--others',
14
- '--exclude-standard',
15
- ]);
16
- return stdout.split('\n').filter(Boolean).slice(0, FILE_LIMIT);
17
- }
18
- catch {
19
- return walk(cwd);
20
- }
21
- }
22
- export function saveUpload(name, data) {
23
- const dir = path.join(home, 'uploads', randomUUID());
24
- mkdirSync(dir, { recursive: true });
25
- const file = path.join(dir, path.basename(name));
26
- writeFileSync(file, data);
27
- return file;
28
- }
29
- function walk(root) {
30
- const files = [];
31
- const pending = [''];
32
- while (pending.length > 0 && files.length < FILE_LIMIT) {
33
- const dir = pending.pop() ?? '';
34
- let entries;
35
- try {
36
- entries = readdirSync(path.join(root, dir), { withFileTypes: true });
37
- }
38
- catch {
39
- continue;
40
- }
41
- for (const entry of entries) {
42
- const relative = dir === '' ? entry.name : `${dir}/${entry.name}`;
43
- if (entry.isDirectory() && !skipped.has(entry.name))
44
- pending.push(relative);
45
- if (entry.isFile())
46
- files.push(relative);
47
- }
48
- }
49
- return files;
50
- }
@@ -1,133 +0,0 @@
1
- import { execFile } from 'node:child_process';
2
- import { readFileSync, statSync } from 'node:fs';
3
- import path from 'node:path';
4
- import { promisify } from 'node:util';
5
- import { query } from '@anthropic-ai/claude-agent-sdk';
6
- import { claudeOptions } from './claude.js';
7
- const DIFF_LIMIT = 80_000;
8
- const UNTRACKED_LIMIT = 100;
9
- const NEW_FILE_LIMIT = 256 * 1024;
10
- export async function gitStatus(cwd) {
11
- let output;
12
- try {
13
- output = await git(cwd, ['status', '--porcelain=v2', '--branch']);
14
- }
15
- catch {
16
- return null;
17
- }
18
- const status = {
19
- branch: null,
20
- upstream: null,
21
- ahead: 0,
22
- behind: 0,
23
- changed: 0,
24
- };
25
- for (const line of output.stdout.split('\n').filter(Boolean)) {
26
- const [marker, key, ...rest] = line.split(' ');
27
- if (marker !== '#')
28
- status.changed++;
29
- else if (key === 'branch.head')
30
- status.branch = rest[0] === '(detached)' ? null : rest[0];
31
- else if (key === 'branch.upstream')
32
- status.upstream = rest[0];
33
- else if (key === 'branch.ab') {
34
- status.ahead = Number(rest[0]);
35
- status.behind = -Number(rest[1]);
36
- }
37
- }
38
- return status;
39
- }
40
- export async function commit(cwd, message) {
41
- if (message.trim() === '')
42
- throw new Error('Write a commit message first');
43
- await git(cwd, ['add', '--all']);
44
- await git(cwd, ['commit', '--message', message]);
45
- return gitStatus(cwd);
46
- }
47
- export async function push(cwd) {
48
- const status = await gitStatus(cwd);
49
- if (status === null)
50
- throw new Error(`${cwd} is not a git repository`);
51
- if (status.upstream === null)
52
- await git(cwd, ['push', '--set-upstream', 'origin', 'HEAD']);
53
- else
54
- await git(cwd, ['push']);
55
- return gitStatus(cwd);
56
- }
57
- export async function createPullRequest(cwd) {
58
- const { stdout } = await promisify(execFile)('gh', ['pr', 'create', '--fill'], { cwd });
59
- const url = stdout.trim().split('\n').at(-1);
60
- if (url === undefined)
61
- throw new Error('gh did not return a pull request URL');
62
- return { url };
63
- }
64
- export async function suggestCommitMessage(accountId, cwd) {
65
- const diff = (await workingDiff(cwd)).slice(0, DIFF_LIMIT);
66
- if (diff === '')
67
- throw new Error('There is nothing to commit');
68
- const conversation = query({
69
- prompt: `Write a git commit message for this diff. Reply with only the message: a short summary line, optionally followed by a blank line and a brief body.\n\n${diff}`,
70
- options: {
71
- ...claudeOptions(accountId, cwd),
72
- systemPrompt: 'You write concise git commit messages.',
73
- tools: [],
74
- model: 'haiku',
75
- maxTurns: 1,
76
- persistSession: false,
77
- },
78
- });
79
- for await (const message of conversation) {
80
- if (message.type !== 'result')
81
- continue;
82
- if (message.subtype !== 'success')
83
- throw new Error(message.errors.join('\n'));
84
- if (message.is_error)
85
- throw new Error(message.result);
86
- return { message: message.result.trim() };
87
- }
88
- throw new Error('Claude did not reply');
89
- }
90
- export async function workingDiff(cwd) {
91
- try {
92
- await git(cwd, ['rev-parse', '--is-inside-work-tree']);
93
- }
94
- catch {
95
- throw new Error(`${cwd} is not a git repository`);
96
- }
97
- const tracked = await git(cwd, [
98
- 'diff',
99
- 'HEAD',
100
- '--no-color',
101
- '--no-ext-diff',
102
- ]);
103
- const untracked = await git(cwd, [
104
- 'ls-files',
105
- '--others',
106
- '--exclude-standard',
107
- ]);
108
- const added = untracked.stdout
109
- .split('\n')
110
- .filter(Boolean)
111
- .slice(0, UNTRACKED_LIMIT)
112
- .map((file) => newFilePatch(cwd, file));
113
- return [tracked.stdout, ...added].join('');
114
- }
115
- export function git(cwd, args) {
116
- return promisify(execFile)('git', args, {
117
- cwd,
118
- maxBuffer: 64 * 1024 * 1024,
119
- });
120
- }
121
- function newFilePatch(cwd, file) {
122
- const header = `diff --git a/${file} b/${file}\nnew file\n--- /dev/null\n+++ b/${file}\n`;
123
- const full = path.join(cwd, file);
124
- if (statSync(full).size > NEW_FILE_LIMIT)
125
- return `${header}Binary or large file\n`;
126
- const content = readFileSync(full, 'utf8');
127
- if (content.includes('\0'))
128
- return `${header}Binary or large file\n`;
129
- const lines = content.split('\n');
130
- if (lines.at(-1) === '')
131
- lines.pop();
132
- return `${header}@@ -0,0 +1,${lines.length} @@\n${lines.map((line) => `+${line}\n`).join('')}`;
133
- }
@@ -1,137 +0,0 @@
1
- import { readdir, readFile } from 'node:fs/promises';
2
- import os from 'node:os';
3
- import path from 'node:path';
4
- import { getSessionMessages, getSubagentMessages, } from '@anthropic-ai/claude-agent-sdk';
5
- import { contextTokens, toMessage } from './content.js';
6
- import { runs } from './run.js';
7
- const projectsDir = path.join(os.homedir(), '.claude', 'projects');
8
- async function sessionEntries(sessionId) {
9
- for (const dir of await readdir(projectsDir)) {
10
- let text;
11
- try {
12
- text = await readFile(path.join(projectsDir, dir, `${sessionId}.jsonl`), 'utf8');
13
- }
14
- catch (error) {
15
- if (error.code === 'ENOENT')
16
- continue;
17
- throw error;
18
- }
19
- return text.split('\n').flatMap((line) => {
20
- const entry = parseLine(line);
21
- return entry !== null && typeof entry.type === 'string'
22
- ? [{ ...entry, type: entry.type }]
23
- : [];
24
- });
25
- }
26
- return [];
27
- }
28
- function messageTimes(entries) {
29
- const times = new Map();
30
- for (const entry of entries)
31
- if (typeof entry.uuid === 'string' && typeof entry.timestamp === 'string')
32
- times.set(entry.uuid, Date.parse(entry.timestamp));
33
- return times;
34
- }
35
- function compactedBefore(entries, uuid) {
36
- if (uuid === undefined)
37
- return null;
38
- const start = entries.findIndex((entry) => entry.uuid === uuid);
39
- const index = entries.findLastIndex((entry, position) => position < start &&
40
- entry.type === 'system' &&
41
- entry.subtype === 'compact_boundary');
42
- return index < 0 ? null : index;
43
- }
44
- function parseLine(line) {
45
- try {
46
- return JSON.parse(line);
47
- }
48
- catch {
49
- return null;
50
- }
51
- }
52
- function mainMessages(disk, times) {
53
- return disk.flatMap((item) => item.type === 'system' || item.parent_tool_use_id !== null
54
- ? []
55
- : [toMessage(item.type, item, times.get(item.uuid) ?? null)]);
56
- }
57
- export async function history(sessionId, cwd) {
58
- const run = runs.get(sessionId);
59
- const [disk, entries] = await Promise.all([
60
- getSessionMessages(sessionId, { dir: cwd }),
61
- sessionEntries(sessionId),
62
- ]);
63
- const resumeAt = run?.resumeAt ?? null;
64
- const kept = resumeAt === null
65
- ? disk
66
- : disk.slice(0, disk.findIndex((item) => item.uuid === resumeAt) + 1);
67
- const messages = mainMessages(kept, messageTimes(entries));
68
- messages.push(...(await subagentMessages(sessionId, cwd, messages)));
69
- const seen = new Set(messages.map((item) => item.uuid));
70
- const last = kept.findLast((item) => item.type === 'assistant' && item.parent_tool_use_id === null);
71
- const tokens = last === undefined ? null : contextTokens(last.message);
72
- return {
73
- type: 'history',
74
- sessionId,
75
- messages: [
76
- ...messages,
77
- ...(run?.messages.filter((item) => !seen.has(item.uuid)) ?? []),
78
- ],
79
- requests: [...(run?.pending.values() ?? [])].map((item) => item.request),
80
- queue: run?.queue ?? [],
81
- settings: run?.settings ?? null,
82
- context: run?.context ??
83
- (tokens === null
84
- ? null
85
- : { tokens, window: null, model: null, categories: [], sections: [] }),
86
- before: compactedBefore(entries, disk[0]?.uuid),
87
- };
88
- }
89
- export async function earlier(sessionId, cwd, before) {
90
- const entries = await sessionEntries(sessionId);
91
- const kept = entries.slice(0, before);
92
- const disk = await getSessionMessages(sessionId, {
93
- sessionStore: { append: () => Promise.resolve(), load: async () => kept },
94
- });
95
- const messages = mainMessages(disk, messageTimes(entries));
96
- messages.push(...(await subagentMessages(sessionId, cwd, messages)));
97
- messages.push({
98
- type: 'notice',
99
- uuid: `compacted:${before}`,
100
- time: null,
101
- text: 'Conversation compacted',
102
- isError: false,
103
- });
104
- return { messages, before: compactedBefore(entries, disk[0]?.uuid) };
105
- }
106
- async function subagentMessages(sessionId, cwd, messages) {
107
- const agents = new Set(messages.flatMap((message) => message.type === 'assistant'
108
- ? message.content.flatMap((block) => block.type === 'tool_use' &&
109
- (block.name === 'Agent' || block.name === 'Task')
110
- ? [block.id]
111
- : [])
112
- : []));
113
- const launches = messages.flatMap((message) => message.type === 'user'
114
- ? message.content.flatMap((block) => {
115
- if (block.type !== 'tool_result' || !agents.has(block.toolUseId))
116
- return [];
117
- const agentId = /agentId: (\w+)/.exec(block.content
118
- .map((item) => (item.type === 'text' ? item.text : ''))
119
- .join('\n'))?.[1];
120
- return agentId === undefined
121
- ? []
122
- : [{ agentId, parent: block.toolUseId }];
123
- })
124
- : []);
125
- const loaded = await Promise.all(launches.map(async (launch) => {
126
- const disk = await getSubagentMessages(sessionId, launch.agentId, {
127
- dir: cwd,
128
- });
129
- const items = disk.flatMap((item) => item.type === 'system'
130
- ? []
131
- : [
132
- toMessage(item.type, { ...item, parent_tool_use_id: launch.parent }, null),
133
- ]);
134
- return [...items, ...(await subagentMessages(sessionId, cwd, items))];
135
- }));
136
- return loaded.flat();
137
- }
@@ -1,10 +0,0 @@
1
- export const clients = new Set();
2
- export function publish(sessionId, event) {
3
- for (const client of clients)
4
- if (client.sessionId === sessionId)
5
- client.send(event);
6
- }
7
- export function broadcast(event) {
8
- for (const client of clients)
9
- client.send(event);
10
- }
@@ -1,64 +0,0 @@
1
- import { createReadStream, existsSync, statSync } from 'node:fs';
2
- import { createServer } from 'node:http';
3
- import path from 'node:path';
4
- import { WebSocketServer } from 'ws';
5
- import { args } from './args.js';
6
- import { findClaude } from './claude.js';
7
- import { startPush } from './push.js';
8
- import { stopAll } from './runs.js';
9
- import { connectClient } from './socket.js';
10
- const contentTypes = {
11
- '.html': 'text/html; charset=utf-8',
12
- '.js': 'text/javascript; charset=utf-8',
13
- '.css': 'text/css; charset=utf-8',
14
- '.svg': 'image/svg+xml',
15
- '.png': 'image/png',
16
- '.ico': 'image/x-icon',
17
- '.json': 'application/json',
18
- '.webmanifest': 'application/manifest+json',
19
- '.woff2': 'font/woff2',
20
- };
21
- const port = Number(args.port);
22
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
23
- console.error(`invalid port ${args.port}`);
24
- process.exit(1);
25
- }
26
- if (findClaude() === null) {
27
- console.error('could not find claude on PATH; install Claude Code first');
28
- process.exit(1);
29
- }
30
- const publicDir = path.join(import.meta.dirname, '..', '..', 'web', 'dist');
31
- const server = createServer((request, response) => {
32
- const url = new URL(request.url ?? '/', 'http://localhost');
33
- serveFile(url.pathname, response);
34
- });
35
- const sockets = new WebSocketServer({ noServer: true });
36
- server.on('upgrade', (request, socket, head) => {
37
- const url = new URL(request.url ?? '/', 'http://localhost');
38
- if (url.pathname === '/ws')
39
- sockets.handleUpgrade(request, socket, head, connectClient);
40
- else
41
- socket.destroy();
42
- });
43
- server.listen(port, args.host, () => {
44
- startPush(`${args.host}:${port}`);
45
- console.log(`offsite is running at http://${args.host}:${port}`);
46
- });
47
- process.on('SIGINT', () => {
48
- stopAll();
49
- process.exit(0);
50
- });
51
- function serveFile(pathname, response) {
52
- const requested = path.join(publicDir, path.normalize(pathname));
53
- const file = requested.startsWith(publicDir + path.sep) &&
54
- statSync(requested, { throwIfNoEntry: false })?.isFile()
55
- ? requested
56
- : path.join(publicDir, 'index.html');
57
- if (!existsSync(file)) {
58
- response.statusCode = 404;
59
- response.end('web app not built; run pnpm build');
60
- return;
61
- }
62
- response.setHeader('content-type', contentTypes[path.extname(file)] ?? 'application/octet-stream');
63
- createReadStream(file).pipe(response);
64
- }
@@ -1,92 +0,0 @@
1
- import { readdir, stat } from 'node:fs/promises';
2
- import os from 'node:os';
3
- import path from 'node:path';
4
- import { db } from './db.js';
5
- import { broadcast } from './hub.js';
6
- const LOGO_TYPES = [
7
- 'image/png',
8
- 'image/jpeg',
9
- 'image/gif',
10
- 'image/webp',
11
- 'image/svg+xml',
12
- 'image/x-icon',
13
- 'image/vnd.microsoft.icon',
14
- ];
15
- const LOGO_LIMIT = 512 * 1024;
16
- export function projects() {
17
- return db
18
- .prepare('SELECT path, name, logo FROM projects')
19
- .all()
20
- .map(toProject);
21
- }
22
- export async function addProject(input) {
23
- const folder = path.resolve(expandHome(input.trim()));
24
- if (!(await stat(folder)).isDirectory())
25
- throw new Error(`${folder} is not a folder`);
26
- db.prepare('INSERT OR IGNORE INTO projects (path, name, logo) VALUES (?, ?, NULL)').run(folder, path.basename(folder) || folder);
27
- publish();
28
- const project = projects().find((item) => item.path === folder);
29
- if (project === undefined)
30
- throw new Error(`Could not add ${folder}`);
31
- return project;
32
- }
33
- export function updateProject(folder, patch) {
34
- if (patch.name !== undefined) {
35
- const name = patch.name.trim();
36
- if (name === '')
37
- throw new Error('Project name cannot be empty');
38
- db.prepare('UPDATE projects SET name = ? WHERE path = ?').run(name, folder);
39
- }
40
- if (patch.logo !== undefined) {
41
- if (patch.logo !== null)
42
- checkLogo(patch.logo);
43
- db.prepare('UPDATE projects SET logo = ? WHERE path = ?').run(patch.logo, folder);
44
- }
45
- publish();
46
- return null;
47
- }
48
- export function removeProject(folder) {
49
- db.prepare('DELETE FROM projects WHERE path = ?').run(folder);
50
- publish();
51
- return null;
52
- }
53
- export async function directories(input) {
54
- const folder = path.resolve(expandHome(input.trim()));
55
- const entries = await readdir(folder, { withFileTypes: true });
56
- const parent = path.dirname(folder);
57
- return {
58
- path: folder,
59
- parent: parent === folder ? null : parent,
60
- directories: entries
61
- .filter((entry) => entry.isDirectory())
62
- .map((entry) => ({
63
- name: entry.name,
64
- path: path.join(folder, entry.name),
65
- }))
66
- .sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase())),
67
- };
68
- }
69
- function publish() {
70
- broadcast({ type: 'projects', projects: projects() });
71
- }
72
- function toProject(row) {
73
- if (typeof row.path !== 'string' ||
74
- typeof row.name !== 'string' ||
75
- (typeof row.logo !== 'string' && row.logo !== null))
76
- throw new Error('The projects table has an unexpected row');
77
- return { path: row.path, name: row.name, logo: row.logo };
78
- }
79
- function checkLogo(logo) {
80
- const type = /^data:([^;,]+);base64,/.exec(logo)?.[1];
81
- if (type === undefined || !LOGO_TYPES.includes(type))
82
- throw new Error('Use a PNG, JPEG, GIF, WebP, SVG or ICO image');
83
- if (logo.length > LOGO_LIMIT)
84
- throw new Error('Use an image smaller than 384 KB');
85
- }
86
- function expandHome(input) {
87
- if (input === '~')
88
- return os.homedir();
89
- if (input.startsWith('~/'))
90
- return path.join(os.homedir(), input.slice(2));
91
- return input;
92
- }