-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathsession.ts
More file actions
159 lines (137 loc) · 4.63 KB
/
session.ts
File metadata and controls
159 lines (137 loc) · 4.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import { execFileSync } from "child_process";
import { existsSync, mkdirSync, writeFileSync } from "fs";
import { resolve } from "path";
import { randomBytes } from "crypto";
// ── Types ─────────────────────────────────────────────────────────────
export interface LocalRepoOptions {
url: string;
token: string;
dir: string;
session?: string;
}
export interface LocalSession {
dir: string;
branch: string;
sessionId: string;
commitChanges(msg?: string): void;
push(): void;
finalize(): void;
}
// ── Helpers ───────────────────────────────────────────────────────────
function authedUrl(url: string, token: string): string {
// https://github.com/org/repo → https://<token>@github.com/org/repo
return url.replace(/^https:\/\//, `https://${token}@`);
}
function cleanUrl(url: string): string {
return url.replace(/^https:\/\/[^@]+@/, "https://");
}
/**
* Safe git execution using argument arrays to prevent command injection.
* Inputs are passed as separate arguments and never interpreted by a shell.
*/
function git(args: string[], cwd: string): string {
return execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf-8" }).trim();
}
function getDefaultBranch(cwd: string): string {
try {
// e.g. "origin/main" → "main"
const ref = git(["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
return ref.replace("refs/remotes/origin/", "");
} catch {
// Fallback: try main, then master
try {
git(["rev-parse", "--verify", "origin/main"], cwd);
return "main";
} catch {
return "master";
}
}
}
// ── initLocalSession ──────────────────────────────────────────────────
export function initLocalSession(opts: LocalRepoOptions): LocalSession {
const { url, token, session } = opts;
const dir = resolve(opts.dir);
const aUrl = authedUrl(url, token);
// Clone or update
if (!existsSync(dir)) {
execFileSync("git", ["clone", "--depth", "1", "--no-single-branch", aUrl, dir], { stdio: "pipe" });
} else {
git(["remote", "set-url", "origin", aUrl], dir);
git(["fetch", "origin"], dir);
// Reset local default branch to latest remote
const defaultBranch = getDefaultBranch(dir);
git(["checkout", defaultBranch], dir);
git(["reset", "--hard", `origin/${defaultBranch}`], dir);
}
// Determine branch
let branch: string;
let sessionId: string;
if (session) {
// Resume existing session
branch = session;
sessionId = branch.replace(/^gitclaw\/session-/, "") || branch;
// Try local checkout first, fall back to remote tracking
try {
git(["checkout", branch], dir);
} catch {
git(["checkout", "-b", branch, `origin/${branch}`], dir);
}
// Pull latest for existing session branch
try { git(["pull", "origin", branch], dir); } catch { /* branch may not exist on remote yet */ }
} else {
// New session — branch off latest default branch
sessionId = randomBytes(4).toString("hex"); // 8-char hex
branch = `gitclaw/session-${sessionId}`;
git(["checkout", "-b", branch], dir);
}
// Scaffold agent.yaml + memory if missing (on session branch only)
const agentYamlPath = `${dir}/agent.yaml`;
if (!existsSync(agentYamlPath)) {
const name = url.split("/").pop()?.replace(/\.git$/, "") || "agent";
writeFileSync(agentYamlPath, [
'spec_version: "0.1.0"',
`name: ${name}`,
"version: 0.1.0",
`description: Gitclaw agent for ${name}`,
"model:",
' preferred: "openai:gpt-4o-mini"',
" fallback: []",
"tools: [cli, read, write, memory]",
"runtime:",
" max_turns: 50",
"",
].join("\n"), "utf-8");
}
const memoryFile = `${dir}/memory/MEMORY.md`;
if (!existsSync(memoryFile)) {
mkdirSync(`${dir}/memory`, { recursive: true });
writeFileSync(memoryFile, "# Memory\n", "utf-8");
}
// Build session object
const localSession: LocalSession = {
dir,
branch,
sessionId,
commitChanges(msg?: string) {
git(["add", "-A"], dir);
try {
git(["diff", "--cached", "--quiet"], dir);
// Nothing staged — skip
} catch {
// There are staged changes
const commitMsg = msg || `gitclaw: auto-commit (${branch})`;
git(["commit", "-m", commitMsg], dir);
}
},
push() {
git(["push", "origin", branch], dir);
},
finalize() {
localSession.commitChanges();
localSession.push();
// Strip PAT from remote URL
git(["remote", "set-url", "origin", cleanUrl(url)], dir);
},
};
return localSession;
}