Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/secure-release-paths.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@bradygaster/squad-cli": patch
"@bradygaster/squad-sdk": patch
---

Harden generated configuration, remote detection, input parsing, and self-upgrade commands against unsafe or pathological inputs.

Avoid probing retired profile squads while resolving legacy team roots.
2 changes: 1 addition & 1 deletion packages/squad-cli/src/cli/commands/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ function detectMode(cwd: string): ModeInfo {
export function teamRootIsThisProject(cwd: string, teamRoot: string): boolean {
const resolved = path.resolve(cwd, teamRoot);
const normalize = (p: string) => {
const n = path.resolve(p).replace(/[\\/]+$/, '');
const n = path.resolve(p).replace(/[\\/]$/, '');
return process.platform === 'win32' ? n.toLowerCase() : n;
};
const target = normalize(resolved);
Expand Down
19 changes: 12 additions & 7 deletions packages/squad-cli/src/cli/commands/migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,15 +320,15 @@ function generateSquadConfig(
});
}
}
lines.push(` members: [${team.members.map(m => `'${m}'`).join(', ')}],`);
lines.push(` members: [${team.members.map(m => `'${escapeString(m)}'`).join(', ')}],`);
lines.push(" }),");
lines.push("");

// Agents section
lines.push(" agents: [");
agents.forEach((agent, idx) => {
const isLast = idx === agents.length - 1;
lines.push(` defineAgent({ name: '${agent.name}', role: '${escapeString(agent.role)}', charter: '${agent.charter}', status: '${agent.status}' })${isLast ? '' : ','}`);
lines.push(` defineAgent({ name: '${escapeString(agent.name)}', role: '${escapeString(agent.role)}', charter: '${escapeString(agent.charter)}', status: '${agent.status}' })${isLast ? '' : ','}`);
});
lines.push(" ],");
lines.push("");
Expand All @@ -339,12 +339,12 @@ function generateSquadConfig(
lines.push(" rules: [");
routing.rules.forEach((rule, idx) => {
const isLast = idx === routing.rules.length - 1;
const agentsStr = `[${rule.agents.map(a => `'${a}'`).join(', ')}]`;
const agentsStr = `[${rule.agents.map(a => `'${escapeString(a)}'`).join(', ')}]`;
const desc = rule.description ? `, description: '${escapeString(rule.description)}'` : '';
lines.push(` { pattern: '${rule.pattern}', agents: ${agentsStr}${desc} }${isLast ? '' : ','}`);
lines.push(` { pattern: '${escapeString(rule.pattern)}', agents: ${agentsStr}${desc} }${isLast ? '' : ','}`);
});
lines.push(" ],");
lines.push(` defaultAgent: '${routing.defaultAgent}',`);
lines.push(` defaultAgent: '${escapeString(routing.defaultAgent)}',`);
lines.push(" fallback: 'coordinator',");
lines.push(" }),");
lines.push("");
Expand All @@ -359,6 +359,9 @@ function generateSquadConfig(
lines.push(" capacity: {");
Object.entries(casting.capacity).forEach(([universe, count], idx, arr) => {
const isLast = idx === arr.length - 1;
if (!Number.isFinite(count)) {
throw new Error(`Casting capacity for '${universe}' must be a finite number`);
}
lines.push(` '${escapeString(universe)}': ${count}${isLast ? '' : ','}`);
});
lines.push(" },");
Expand All @@ -373,10 +376,12 @@ function generateSquadConfig(
}

/**
* Escape single quotes in string literals
* Escape content for a single-quoted JavaScript string literal.
*/
function escapeString(str: string): string {
return str.replace(/'/g, "\\'").replace(/\n/g, '\\n');
return str.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
Comment thread
tamirdresher marked this conversation as resolved.
Resolved
.replace(/\r/g, '\\r').replace(/\n/g, '\\n')
.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}

/**
Expand Down
9 changes: 8 additions & 1 deletion packages/squad-cli/src/cli/core/team-md.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,14 @@ export function insertCopilotSection(content: string, autoAssign: boolean = fals
* Remove @copilot section from team.md
*/
export function removeCopilotSection(content: string): string {
return content.replace(/\n## Coding Agent\n[\s\S]*?(?=\n## |\n*$)/, '');
const heading = '\n## Coding Agent\n';
const start = content.indexOf(heading);
if (start === -1) return content;
const nextSection = content.indexOf('\n## ', start + heading.length);
if (nextSection !== -1) return content.slice(0, start) + content.slice(nextSection);
let end = content.length;
while (end > start + heading.length && content[end - 1] === '\n') end--;
return content.slice(0, start) + content.slice(end);
}

/**
Expand Down
15 changes: 8 additions & 7 deletions packages/squad-cli/src/cli/core/upgrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
import { FSStorageProvider, stripTeamCapabilitiesBlock, syncTeamCapabilities } from '@bradygaster/squad-sdk';
import { clearResolveSquadCache, isRetiredProfileTeamRoot } from '@bradygaster/squad-sdk/resolution';
import { squadRepoLauncherScript } from '@bradygaster/squad-sdk/client';
import { detectPlatformFromUrl } from '@bradygaster/squad-sdk/platform';
import {
backfillCastingRegistryFromTeam,
detectHistoricalCastingSchema,
Expand Down Expand Up @@ -271,8 +272,7 @@ function detectIsGitHubForMcp(dest: string, config: Record<string, unknown>): bo

try {
const remoteUrl = execFileSync('git', ['remote', 'get-url', 'origin'], { cwd: dest, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
const remoteUrlLower = remoteUrl.toLowerCase();
if (remoteUrlLower.includes('dev.azure.com') || remoteUrlLower.includes('visualstudio.com') || remoteUrlLower.includes('ssh.dev.azure.com')) {
if (detectPlatformFromUrl(remoteUrl) === 'azure-devops') {
return false;
}
} catch {
Expand Down Expand Up @@ -332,7 +332,7 @@ function stripRetiredProfileTeamRoot(squadDir: string, dest: string, dryRun: boo
*/
export function stripAgentStamps(s: string): string {
return s
.replace(/<!-- squad-cli v[\d.]+[-\w.]* -->\n?/g, '')
.replace(/<!-- squad-cli v[\d.][-\w.]* -->\n?/g, '')
.replace(/<!-- version: [^>]+ -->/g, '<!-- version: X -->')
.replace(/- \*\*Version:\*\* \S+/g, '- **Version:** X')
.replace(/`Squad v[^`]+`/g, '`Squad vX`')
Expand Down Expand Up @@ -1893,11 +1893,12 @@ export function detectSelfUpgradeTag(currentVersion: string): SelfUpgradeTag {
/** The exact command `selfUpgradeCli` runs for a package manager and dist-tag. */
export function selfUpgradeCommand(packageManager: SelfUpgradePackageManager, insiderOrTag: boolean | SelfUpgradeTag): string {
const tag: SelfUpgradeTag = typeof insiderOrTag === 'boolean' ? (insiderOrTag ? 'insider' : 'latest') : insiderOrTag;
const pkg = `@bradygaster/squad-cli@${tag}`;
if (tag !== 'latest' && tag !== 'insider') throw new Error('Invalid self-upgrade tag');
switch (packageManager) {
case 'pnpm': return `pnpm add -g ${pkg}`;
case 'yarn': return `yarn global add ${pkg}`;
default: return `npm install -g ${pkg}`;
case 'pnpm': return tag === 'insider' ? 'pnpm add -g @bradygaster/squad-cli@insider' : 'pnpm add -g @bradygaster/squad-cli@latest';
case 'yarn': return tag === 'insider' ? 'yarn global add @bradygaster/squad-cli@insider' : 'yarn global add @bradygaster/squad-cli@latest';
case 'npm': return tag === 'insider' ? 'npm install -g @bradygaster/squad-cli@insider' : 'npm install -g @bradygaster/squad-cli@latest';
default: throw new Error('Invalid self-upgrade package manager');
}
}

Expand Down
7 changes: 6 additions & 1 deletion packages/squad-cli/src/cli/shell/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1275,9 +1275,14 @@ export async function runShell(): Promise<void> {
recordShellError('dispatch', err instanceof Error ? err.constructor.name : 'unknown');
const errorMsg = err instanceof Error ? err.message : String(err);
if (shellApi) {
const quotaExceeded = errorMsg.toLowerCase().split(/[\r\n\u2028\u2029]/).some((line) => {
const quota = line.indexOf('quota');
return quota !== -1 && line.indexOf('exceed', quota + 5) !== -1;
});
const isRateLimit =
err instanceof RateLimitError ||
/rate.?limit|quota.*exceed|429/i.test(errorMsg);
/rate.?limit|429/i.test(errorMsg) ||
quotaExceeded;
let guidance;
if (isRateLimit) {
const retryAfter =
Expand Down
29 changes: 22 additions & 7 deletions packages/squad-sdk/src/agents/onboarding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,24 @@ export async function onboardAgent(
* @param role - Agent role
* @returns True if config was updated, false if not found or JSON format
*/
function findRulesArray(content: string): { start: number; end: number; entries: string } | undefined {
const start = /rules:\s*\[/.exec(content);
if (!start) return undefined;
const entriesStart = start.index + start[0].length;
let cursor = entriesStart;
while (cursor < content.length) {
const close = content.indexOf(']', cursor);
if (close === -1) return undefined;
let after = close + 1;
while (after < content.length && /\s/.test(content[after]!)) after++;
if (after < content.length && ',})'.includes(content[after]!)) {
return { start: start.index, end: close + 1, entries: content.slice(entriesStart, close) };
}
cursor = close + 1;
}
return undefined;
}

export async function addAgentToConfig(
teamRoot: string,
agentName: string,
Expand Down Expand Up @@ -527,21 +545,18 @@ export async function addAgentToConfig(
if (workType) {
const workTypePattern = new RegExp(`workType:\\s*['"]${workType}['"]`);
if (!workTypePattern.test(updatedContent)) {
const rulesPattern = /rules:\s*\[([\s\S]*?)\](?=\s*[,}\)])/;
const rulesMatch = updatedContent.match(rulesPattern);
const rulesMatch = findRulesArray(updatedContent);
if (rulesMatch) {
const newRule = ` {
workType: '${workType}',
agents: ['@${agentName}'],
confidence: 'high'
}`;
const existingRules = rulesMatch[1]!.trimEnd();
const existingRules = rulesMatch.entries.trimEnd();
const separator = existingRules.trim() ? ',\n' : '\n';
const updatedRules = existingRules + separator + newRule;
updatedContent = updatedContent.replace(
rulesPattern,
`rules: [${updatedRules}\n ]`
);
updatedContent = updatedContent.slice(0, rulesMatch.start) +
`rules: [${updatedRules}\n ]` + updatedContent.slice(rulesMatch.end);
modified = true;
}
}
Expand Down
4 changes: 3 additions & 1 deletion packages/squad-sdk/src/backend/durable-http-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,9 @@ export function validateBaseUrl(baseUrl: string | undefined): string {
`baseUrl must use https:// (plain http:// is allowed only for localhost / 127.0.0.1 / ::1); got '${url.protocol}//${url.host}'`, 400);
}
if (url.username || url.password) throw new BackendError('invalid-request', 'baseUrl must not embed credentials', 400);
return baseUrl.replace(/\/+$/, '');
let end = baseUrl.length;
while (end > 0 && baseUrl[end - 1] === '/') end--;
return baseUrl.slice(0, end);
}

function toError(res: Response, text: string): BackendError {
Expand Down
19 changes: 15 additions & 4 deletions packages/squad-sdk/src/casting/handwritten-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export function toAgentId(value: string): string {
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
.replace(/^-|-$/g, '');
}

export interface DroppedRecord { name: string; reason: string }
Expand Down Expand Up @@ -757,13 +757,24 @@ export interface TeamRosterMember {
charterId?: string;
}

const UNIVERSE_LINE = /^\s*(?:[-*]\s+)?\*{0,2}universe\*{0,2}\s*:\s*\*{0,2}\s*([^\n|*]+?)\s*$/im;
const UNIVERSE_CELL = /^\s*\|\s*\*{0,2}universe\*{0,2}\s*\|\s*([^|\n]+?)\s*\|/im;
const UNIVERSE_LINE = /^(?:[-*]\s+)?\*{0,2}universe\*{0,2}\s*:(.*)$/i;
const UNIVERSE_CELL = /^\|\s*\*{0,2}universe\*{0,2}\s*\|([^|]+)\|/i;

/** Parse specialist rows from `team.md` (`## Members` table, else the first Name/Role table). */
export function parseTeamRoster(teamMd: string): { members: TeamRosterMember[]; universe?: string } {
const universe = (UNIVERSE_LINE.exec(teamMd)?.[1] ?? UNIVERSE_CELL.exec(teamMd)?.[1])?.replace(/[*_`]/g, '').trim();
const lines = teamMd.split(/\r?\n/);
let universeLine: string | undefined;
let universeCell: string | undefined;
for (const line of lines) {
const text = line.trim();
const lineMatch = UNIVERSE_LINE.exec(text);
if (universeLine === undefined && lineMatch) {
const candidate = lineMatch[1]!.trimStart().replace(/^\*{0,2}/, '').trimStart();
if (candidate && !/[*|]/.test(candidate)) universeLine = candidate;
}
if (universeCell === undefined) universeCell = UNIVERSE_CELL.exec(text)?.[1];
}
const universe = (universeLine ?? universeCell)?.replace(/[*_`]/g, '').trim();
const membersHeading = lines.findIndex((l) => /^##\s+members\b/i.test(l.trim()));
const scope = membersHeading === -1
? lines
Expand Down
15 changes: 12 additions & 3 deletions packages/squad-sdk/src/client/adapters/apply.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,16 @@ export function removeLines(existing: string, lines: readonly string[], id: stri
return rows.join('\n');
}

const SECTION_RE = /^\s*(\[\[?)\s*([^\]\r\n]+?)\s*(\]\]?)\s*(?:#.*)?$/;
const SECTION_RE = /^\s*(\[\[?)([^\]\r\n]+)(\]\]?)\s*(?:#.*)?$/;

function withoutTrailingLineBreaks(value: string): string {
let end = value.length;
while (end > 0 && value[end - 1] === '\n') {
end--;
if (end > 0 && value[end - 1] === '\r') end--;
}
return value.slice(0, end);
}

function segmentsEqual(a: readonly string[], b: readonly string[]): boolean {
return a.length === b.length && a.every((s, idx) => s === b[idx]);
Expand Down Expand Up @@ -471,7 +480,7 @@ export function upsertTomlTable(
if (!(k in merged)) merged[k] = v;
}
const body = Object.entries(merged).map(([k, v]) => `${k} = ${v}`);
const cleanedExisting = lines.join(nl).replace(/(\r?\n)*$/, '');
const cleanedExisting = withoutTrailingLineBreaks(lines.join(nl));
const prefix = cleanedExisting === '' ? '' : cleanedExisting + nl + nl;
return `${prefix}${[header, ...body].join(nl)}${nl}`;
}
Expand Down Expand Up @@ -798,7 +807,7 @@ export function removeTomlTable(existing: string, table: string): string {
}
if (!changed) return existing;
const joined = lines.join(nl);
return joined.trim() === '' ? '' : joined.replace(/(\r?\n)*$/, nl);
return joined.trim() === '' ? '' : withoutTrailingLineBreaks(joined) + nl;
}

const MCP_CONTAINERS = ['mcpServers', 'mcp', 'servers'];
Expand Down
7 changes: 5 additions & 2 deletions packages/squad-sdk/src/client/adapters/coordinator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,11 @@ export const CANONICAL_COORDINATOR_HEADINGS = [
export function extractCanonicalCoordinatorHeadings(markdown: string): string[] {
const headings: string[] = [];
for (const line of markdown.split(/\r?\n/)) {
const m = /^#{2,3}\s+(.+?)\s*$/.exec(line);
if (m) headings.push(m[1]!);
const count = line.startsWith('###') ? 3 : line.startsWith('##') ? 2 : 0;
if (count && /\s/.test(line.charAt(count))) {
const heading = line.slice(count).trim();
if (heading) headings.push(heading);
}
}
return headings;
}
Expand Down
Loading
Loading