kira-glasses-bridge 2.2.0 → 2.4.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kira-glasses-bridge",
3
- "version": "2.2.0",
3
+ "version": "2.4.0",
4
4
  "description": "Connects your Mac to Kira, the assistant for Even G2 glasses: Claude Code sessions, files, folders and apps, by voice.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/index.mjs CHANGED
@@ -9,6 +9,7 @@ import { agentById, AGENTS } from './agents/index.mjs'
9
9
  import { normalizeAnswer } from './agents/protocol.mjs'
10
10
  import { openApp, installedApps } from './apps.mjs'
11
11
  import { listFiles, readUserFile, createFolder, writeUserFile, trashPath, resolveUserPath } from './files.mjs'
12
+ import { prepareWorktree, worktreeStatus, pushWorktree, removeWorktree, repoOfFolder } from './worktrees.mjs'
12
13
 
13
14
  import { createRequire } from 'node:module'
14
15
  const { version: BRIDGE_VERSION } = createRequire(import.meta.url)('../package.json')
@@ -124,6 +125,37 @@ const tools = {
124
125
  return setupProjectFolder({ dir, name: args.name, description: args.description, sshUrl: args.ssh_url, httpsUrl: args.https_url })
125
126
  },
126
127
 
128
+ /** Open Terminal on this Mac in a folder and run a command there (used to hand a Claude session to the person). */
129
+ async open_terminal(args) {
130
+ const dir = resolveUserPath(String(args.cwd ?? ''))
131
+ const command = String(args.command ?? '').replace(/[^\w\s./:@=-]/g, '')
132
+ if (process.platform !== 'darwin') return { error: 'opening a terminal is only supported on macOS' }
133
+ const { execFile } = await import('node:child_process')
134
+ const script = `tell application "Terminal"
135
+ activate
136
+ do script "cd ${JSON.stringify(dir)} && ${command}"
137
+ end tell`
138
+ return new Promise(resolve => execFile('osascript', ['-e', script], err => resolve(err ? { error: err.message } : { opened: true, cwd: display(dir), command })))
139
+ },
140
+
141
+ /** A worktree for one task attempt, off the project's checkout of the repo. */
142
+ prepare_worktree(args) {
143
+ return prepareWorktree(args)
144
+ },
145
+ worktree_status(args) {
146
+ return worktreeStatus(args)
147
+ },
148
+ push_worktree(args) {
149
+ return pushWorktree(args)
150
+ },
151
+ remove_worktree(args) {
152
+ return removeWorktree(args)
153
+ },
154
+ /** Which GitHub repo a folder's origin points at (project link enrichment). */
155
+ async repo_of_folder(args) {
156
+ return { repo: await repoOfFolder(args.path) }
157
+ },
158
+
127
159
  /** Read-only git facts for a folder: repo, branch, head, dirty files. */
128
160
  async git_status(args) {
129
161
  const s = await snapshot(resolveCwd(args.path ?? args.cwd))
@@ -0,0 +1,164 @@
1
+ // A git worktree per task attempt, so agents working on different tasks never
2
+ // share a directory and the main checkout is never touched. Worktrees live
3
+ // under ~/.kira/worktrees/<owner>/<repo>/<branch>; the project's linked folder
4
+ // is only read (fetch, worktree add) and its working tree is left alone.
5
+ import { execFile } from 'node:child_process'
6
+ import { homedir } from 'node:os'
7
+ import { isAbsolute, join, resolve } from 'node:path'
8
+ import { mkdir, stat } from 'node:fs/promises'
9
+ import { display } from './git.mjs'
10
+ import { resolveUserPath } from './files.mjs'
11
+
12
+ const ROOT = join(homedir(), '.kira', 'worktrees')
13
+ const SETUP_TIMEOUT_MS = 5 * 60_000
14
+ const OUTPUT_CAP = 4000
15
+
16
+ function git(cwd, args, { timeout = 60_000 } = {}) {
17
+ return new Promise(resolve => {
18
+ execFile('git', args, { cwd, maxBuffer: 16 * 1024 * 1024, timeout, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' } }, (err, stdout, stderr) => {
19
+ resolve({ ok: !err, out: String(stdout ?? '').trim(), err: String(stderr ?? err?.message ?? '').trim() })
20
+ })
21
+ })
22
+ }
23
+
24
+ function remoteToRepo(url) {
25
+ const m = /github\.com[:/]([^/\s]+\/[^/\s]+?)(?:\.git)?$/.exec(url ?? '')
26
+ return m ? m[1] : null
27
+ }
28
+
29
+ const sameRepo = (a, b) => !!a && !!b && a.toLowerCase() === b.toLowerCase()
30
+
31
+ /** The GitHub repo a folder's origin points at, or null. */
32
+ export async function repoOfFolder(folder) {
33
+ const dir = resolveUserPath(String(folder ?? ''))
34
+ const r = await git(dir, ['remote', 'get-url', 'origin'])
35
+ return r.ok ? remoteToRepo(r.out) : null
36
+ }
37
+
38
+ /** Among the project's folders, the checkout of this repo. */
39
+ async function findCheckout(folders, repo) {
40
+ for (const f of folders ?? []) {
41
+ let dir
42
+ try {
43
+ dir = resolveUserPath(String(f))
44
+ } catch {
45
+ continue
46
+ }
47
+ const top = await git(dir, ['rev-parse', '--show-toplevel'])
48
+ if (!top.ok) continue
49
+ const origin = await git(top.out, ['remote', 'get-url', 'origin'])
50
+ const found = origin.ok ? remoteToRepo(origin.out) : null
51
+ if (sameRepo(found, repo)) return { checkout: top.out, repo: found }
52
+ }
53
+ return null
54
+ }
55
+
56
+ const exists = p => stat(p).then(() => true).catch(() => false)
57
+
58
+ /**
59
+ * Make (or find) the worktree for a branch of a repo, based on `base`
60
+ * (default: the remote's default branch, else the checkout's current branch).
61
+ * Runs `setup_command` inside it when given (e.g. `pnpm install`), once, on
62
+ * creation. Idempotent: an existing worktree for the branch is returned as is.
63
+ */
64
+ export async function prepareWorktree({ folders, repo, branch, base, setup_command: setupCommand }) {
65
+ if (!repo || !branch) return { error: 'repo and branch are required' }
66
+ const found = await findCheckout(folders, repo)
67
+ if (!found) return { error: `none of the project's folders is a checkout of ${repo}${folders?.length ? ` (looked in ${folders.map(String).join(', ')})` : ''}. Link the folder that has it.` }
68
+ const { checkout } = found
69
+ repo = found.repo // the origin's casing, so the path is the same however the repo was spelled
70
+
71
+ const path = join(ROOT, ...repo.split('/'), branch.replace(/[^\w.-]+/g, '-'))
72
+ if (await exists(join(path, '.git'))) {
73
+ const head = await git(path, ['rev-parse', 'HEAD'])
74
+ const mb = await git(path, ['merge-base', 'HEAD', `origin/${base || 'HEAD'}`])
75
+ return { path: display(path), abs: path, checkout: display(checkout), branch, existing: true, head: head.out || null, base_sha: mb.ok ? mb.out : null }
76
+ }
77
+
78
+ // Fresh remote refs when we can get them; offline, the local refs will do.
79
+ const fetched = await git(checkout, ['fetch', 'origin', '--prune', '--quiet'], { timeout: 90_000 })
80
+ let baseName = base
81
+ if (!baseName) {
82
+ const head = await git(checkout, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'])
83
+ baseName = head.ok ? head.out.replace(/^origin\//, '') : (await git(checkout, ['rev-parse', '--abbrev-ref', 'HEAD'])).out || 'main'
84
+ }
85
+ const candidates = [`refs/remotes/origin/${baseName}`, `refs/heads/${baseName}`]
86
+ let baseRef = null
87
+ for (const c of candidates) if ((await git(checkout, ['rev-parse', '--verify', '--quiet', c])).ok) { baseRef = c; break }
88
+ if (!baseRef) return { error: `base branch ${baseName} not found in ${display(checkout)}${fetched.ok ? '' : ' (fetch failed: ' + fetched.err.split('\n').pop() + ')'}` }
89
+ const baseSha = (await git(checkout, ['rev-parse', baseRef])).out
90
+
91
+ await mkdir(join(path, '..'), { recursive: true })
92
+ const branchExists = (await git(checkout, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`])).ok
93
+ const add = branchExists ? await git(checkout, ['worktree', 'add', path, branch]) : await git(checkout, ['worktree', 'add', '-b', branch, path, baseRef])
94
+ if (!add.ok) {
95
+ // A stale registration (folder deleted by hand) blocks re-adding; prune once and retry.
96
+ await git(checkout, ['worktree', 'prune'])
97
+ const retry = branchExists ? await git(checkout, ['worktree', 'add', path, branch]) : await git(checkout, ['worktree', 'add', '-b', branch, path, baseRef])
98
+ if (!retry.ok) return { error: `git worktree add failed: ${retry.err.split('\n').pop()}` }
99
+ }
100
+ // Starting from origin/<base> makes git track it; the branch is ours, and "pushed" must mean our branch is on origin.
101
+ if (!branchExists) await git(path, ['branch', '--unset-upstream'])
102
+
103
+ let setup = null
104
+ if (setupCommand && String(setupCommand).trim()) {
105
+ setup = await new Promise(resolve => {
106
+ execFile('sh', ['-lc', String(setupCommand)], { cwd: path, timeout: SETUP_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, CI: '1' } }, (err, stdout, stderr) => {
107
+ const out = `${stdout ?? ''}${stderr ?? ''}`.trim()
108
+ resolve({ ok: !err, command: String(setupCommand), output: out.length > OUTPUT_CAP ? `…${out.slice(-OUTPUT_CAP)}` : out })
109
+ })
110
+ })
111
+ }
112
+ return { path: display(path), abs: path, checkout: display(checkout), branch, base: baseName, base_sha: baseSha, existing: false, fetched: fetched.ok, setup }
113
+ }
114
+
115
+ /** Where a worktree stands: branch, commits and files changed against its base, and whether it has been pushed. */
116
+ export async function worktreeStatus({ path: p, base }) {
117
+ const path = resolveUserPath(String(p ?? ''))
118
+ if (!(await exists(join(path, '.git')))) return { error: 'no worktree at that path', path: display(path) }
119
+ const [branch, head, status] = await Promise.all([git(path, ['rev-parse', '--abbrev-ref', 'HEAD']), git(path, ['rev-parse', 'HEAD']), git(path, ['status', '--porcelain=v1'])])
120
+ const baseRef = base ? `origin/${base}` : 'origin/HEAD'
121
+ const mb = await git(path, ['merge-base', 'HEAD', baseRef])
122
+ const ahead = mb.ok ? await git(path, ['rev-list', '--count', `${mb.out}..HEAD`]) : { ok: false, out: '0' }
123
+ const diff = mb.ok ? await git(path, ['diff', '--shortstat', mb.out, 'HEAD']) : { out: '' }
124
+ const remoteRef = `refs/remotes/origin/${branch.out}`
125
+ const onOrigin = (await git(path, ['rev-parse', '--verify', '--quiet', remoteRef])).ok
126
+ const unpushed = onOrigin ? await git(path, ['rev-list', '--count', `${remoteRef}..HEAD`]) : null
127
+ const commits = mb.ok ? (await git(path, ['log', '--format=%h %s', `${mb.out}..HEAD`, '--max-count=20'])).out.split('\n').filter(Boolean) : []
128
+ return {
129
+ path: display(path),
130
+ branch: branch.out,
131
+ head: head.out.slice(0, 7),
132
+ dirty: status.out.split('\n').filter(Boolean).length,
133
+ commits_ahead: Number(ahead.out || 0),
134
+ commits,
135
+ diffstat: diff.out,
136
+ pushed: onOrigin && Number(unpushed?.out || 0) === 0,
137
+ on_origin: onOrigin,
138
+ }
139
+ }
140
+
141
+ /** Push the worktree's branch to origin, setting upstream. */
142
+ export async function pushWorktree({ path: p }) {
143
+ const path = resolveUserPath(String(p ?? ''))
144
+ const branch = (await git(path, ['rev-parse', '--abbrev-ref', 'HEAD'])).out
145
+ if (!branch || branch === 'HEAD') return { error: 'worktree is not on a branch' }
146
+ const r = await git(path, ['push', '--set-upstream', 'origin', branch], { timeout: 120_000 })
147
+ if (!r.ok) return { error: `push failed: ${r.err.split('\n').filter(Boolean).pop()}` }
148
+ return { pushed: true, branch, head: (await git(path, ['rev-parse', 'HEAD'])).out.slice(0, 7) }
149
+ }
150
+
151
+ /** Remove a worktree (and optionally its branch) once its work is merged or abandoned. */
152
+ export async function removeWorktree({ path: p, delete_branch: deleteBranch }) {
153
+ const path = resolveUserPath(String(p ?? ''))
154
+ if (!path.startsWith(ROOT + '/')) return { error: 'refusing to remove a folder outside ~/.kira/worktrees' }
155
+ if (!(await exists(path))) return { removed: false, note: 'already gone' }
156
+ const common = await git(path, ['rev-parse', '--git-common-dir'])
157
+ const branch = (await git(path, ['rev-parse', '--abbrev-ref', 'HEAD'])).out
158
+ const main = common.ok ? (isAbsolute(common.out) ? common.out : resolve(path, common.out)).replace(/\/\.git$/, '') : null
159
+ const r = await git(main ?? path, ['worktree', 'remove', '--force', path])
160
+ if (!r.ok) return { error: `worktree remove failed: ${r.err.split('\n').pop()}` }
161
+ let branchDeleted = false
162
+ if (deleteBranch && main && branch && branch !== 'HEAD') branchDeleted = (await git(main, ['branch', '-D', branch])).ok
163
+ return { removed: true, branch, branch_deleted: branchDeleted }
164
+ }