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
10 changes: 8 additions & 2 deletions Sources/AgentTermHost/AgentHooks.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,22 @@ public enum AgentHooks {
return " --settings " + Handoff.shellQuote(String(decoding: settings, as: UTF8.self))
}

static func copilotInstructionsFolder(in directory: URL) -> URL {
directory.appendingPathComponent("copilot-instructions", isDirectory: true)
}

static let copilotInstructionsVariable = "COPILOT_CUSTOM_INSTRUCTIONS_DIRS"

/// What an agent's environment is given besides: for Copilot CLI, the
/// folder of instructions it is told to run its commands in shells the
/// user sees, next to any its own environment names (MCP-13).
public static func instructionsEnvironment(agent: String, directory: URL?, prompt: String?, current: [String: String]) throws -> [String: String] {
guard agent == "copilot", let prompt, let directory else { return [:] }
let folder = directory.appendingPathComponent("copilot-instructions", isDirectory: true)
let folder = copilotInstructionsFolder(in: directory)
let file = folder.appendingPathComponent("instructions/agentterm.instructions.md")
try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
try writeText("---\napplyTo: \"**\"\n---\n" + prompt + "\n", to: file)
let name = "COPILOT_CUSTOM_INSTRUCTIONS_DIRS"
let name = copilotInstructionsVariable
let theirs = current[name].flatMap { $0.isEmpty ? nil : $0 }
return [name: [theirs, folder.path].compactMap { $0 }.joined(separator: ",")]
}
Expand Down
40 changes: 40 additions & 0 deletions Sources/AgentTermHost/FirstPromptInput.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import Foundation

/// Recognizes text followed by Return in the terminal input stream, without
/// retaining the user's message. Frames may split a paste or a key sequence.
struct FirstPromptInput {
private var characters = 0
private var escaped = false
private var sequence: [UInt8]?
private var pasting = false

mutating func submitted(_ data: Data) -> Bool {
for byte in data {
if let parameters = sequence {
if (0x40...0x7e).contains(byte) {
if byte == 0x7e {
if parameters == Array("200".utf8) { pasting = true }
if parameters == Array("201".utf8) { pasting = false }
}
sequence = nil
} else if parameters.count < 16 {
sequence?.append(byte)
}
} else if escaped {
escaped = false
if byte == 0x5b || byte == 0x4f { sequence = [] }
} else {
switch byte {
case 0x1b: escaped = true
case 0x0d, 0x0a:
if !pasting && characters > 0 { return true }
case 0x03, 0x15: characters = 0 // Cancel or clear the line.
case 0x08, 0x7f: characters = max(0, characters - 1)
case 0x20...0x7e, 0xc2...0xf4: characters += 1
default: break
}
}
}
return false
}
}
51 changes: 43 additions & 8 deletions Sources/AgentTermHost/HostServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -287,9 +287,13 @@ public final class HostServer {
/// in it was found (#129). Its hooks and MCP server have until a
/// grace after it to be heard from.
var agentSince: Date?
var firstPromptInput = FirstPromptInput()
var firstPromptAt: Date?
/// Whether AgentTerm had instructions for its agent when it started
/// (#172): what the session was given, whatever is saved later.
var promptGiven = true
/// The Copilot instructions in the launched shell's environment. Nil when disabled.
var copilotInstructionsPrepared: Bool?
/// A call of one of AgentTerm's own tools that its agent said it is
/// about to make, and when: until the call comes to its server, or
/// the agent says anything else (#141).
Expand Down Expand Up @@ -317,6 +321,8 @@ public final class HostServer {
/// What Settings > Shell has run first in it, typed with Return
/// once it shows its prompt, as a person would.
var pendingStartup: String?
/// It was started as a shell, not with a command of its own.
var isShell = true

init(info: SessionInfo, process: PTYProcess, screenLines: Int) {
self.info = info
Expand Down Expand Up @@ -2885,7 +2891,7 @@ public final class HostServer {
case .success(let made):
if let problem = made.problem { server.send(.error(problem), to: client) }
let request = CreateRequest(command: made.prepared.command, cwd: made.prepared.directory, title: Handoff.name(of: target), size: size)
if let created = server.create(request, for: client), let branch = made.branch {
if let created = server.create(request, for: client, startsWithPrompt: true), let branch = made.branch {
server.sessions[created]?.info.branch = branch
server.broadcastSessions()
}
Expand Down Expand Up @@ -3481,6 +3487,11 @@ public final class HostServer {
// Typing takes control of the session's size.
if session.arbiter.activity(client.id) { applySize(of: session) }
used(by: client)
if session.info.link != nil, session.info.link?.hooks == nil, session.firstPromptAt == nil,
session.firstPromptInput.submitted(frame.payload)
{
session.firstPromptAt = configuration.now()
}
session.process.write(frame.payload)
// It may have stopped the turn, and not every agent says so: nor
// does Antigravity when its question for leave is cancelled (#141).
Expand Down Expand Up @@ -3521,7 +3532,7 @@ public final class HostServer {
@discardableResult
private func create(
_ request: CreateRequest, for client: Client?, conversationID: String? = nil, openedBy: SessionID? = nil, run: Schedule? = nil,
environment more: [String: String] = [:]
environment more: [String: String] = [:], startsWithPrompt: Bool = false
) -> SessionID? {
// The host's home: the user's, or a test's own, never the home of
// the person running the tests.
Expand Down Expand Up @@ -3551,10 +3562,14 @@ public final class HostServer {
}
// Copilot CLI does not take an MCP server's instructions: it reads
// what it is told from a folder its environment names.
let copilotPrompt = agentPrompt(for: "copilot")
let instructionsVariable = AgentHooks.copilotInstructionsVariable
var copilotDirectory: URL?
if let told = try? AgentHooks.instructionsEnvironment(
agent: "copilot", directory: configuration.hooksDirectory, prompt: agentPrompt(for: "copilot"), current: environment)
agent: "copilot", directory: configuration.hooksDirectory, prompt: copilotPrompt, current: environment)
{
environment.merge(told) { _, new in new }
if told[instructionsVariable] != nil { copilotDirectory = configuration.hooksDirectory.map(AgentHooks.copilotInstructionsFolder) }
}
// A schedule's run of Antigravity trusts the schedule's folder, as
// the user asked by scheduling it there; for that run only.
Expand Down Expand Up @@ -3624,13 +3639,20 @@ public final class HostServer {
)
let session = Session(info: info, process: process, screenLines: configuration.screenLines)
session.agentKey = agentKey
if copilotPrompt != nil {
let directories = environment[instructionsVariable]?.components(separatedBy: ",") ?? []
session.copilotInstructionsPrepared = copilotDirectory.map { directories.contains($0.path) } ?? false
}
if let agentID = info.agent {
session.info.link = AgentLink()
session.agentSince = configuration.now()
if run != nil || startsWithPrompt { session.firstPromptAt = session.agentSince }
session.promptGiven = agentPrompt(for: agentID) != nil
refreshPrompt(session)
}
session.marksPrepared = marksPrepared
session.isShell = isShell
if info.agent == nil { session.info.running = !isShell }
session.info.openedBy = openedBy
session.pendingTyped = request.typed.flatMap { $0.isEmpty ? nil : $0 }
session.pendingStartup = startup
Expand Down Expand Up @@ -3817,18 +3839,20 @@ public final class HostServer {
/// while it runs, what was heard before it included.
private func typedAgentFound(_ agent: String, in session: Session) {
session.info.typedAgent = agent
session.firstPromptAt = nil
session.firstPromptInput = FirstPromptInput()
session.agentSince = configuration.now()
let early = heardEarly.removeValue(forKey: session.info.id) ?? []
session.info.link = AgentLink(hooks: early.contains(.hooks) ? true : nil, mcp: early.contains(.mcp) ? true : nil)
session.promptGiven = agentPrompt(for: agent) != nil
session.promptGiven = agent == "copilot" ? session.copilotInstructionsPrepared != nil : agentPrompt(for: agent) != nil
refreshPrompt(session)
}

/// What AgentTerm's instructions came to in a session (#172), from how
/// they reach its agent and what its MCP server did.
private func refreshPrompt(_ session: Session) {
guard let agent = session.info.agent ?? session.info.typedAgent, var link = session.info.link else { return }
link.prompt = AgentLink.prompt(agent: agent, given: session.promptGiven, mcp: link.mcp)
link.prompt = AgentLink.prompt(agent: agent, given: session.promptGiven, mcp: link.mcp, copilotPrepared: session.copilotInstructionsPrepared)
session.info.link = link
}

Expand All @@ -3840,6 +3864,14 @@ public final class HostServer {
var changed = false
let now = configuration.now()
for session in sessions.values {
// Whether closing it stops a program at work, asked first then.
if session.info.agent == nil {
let running = !session.isShell || session.process.runsAnotherProgram
if running != session.info.running {
session.info.running = running
changed = true
}
}
if session.info.agent == nil, let front = session.process.foregroundCommand {
let typed = SessionSummaries.agent(forCommand: front)
if let typed, typed != session.info.typedAgent {
Expand All @@ -3858,10 +3890,13 @@ public final class HostServer {
}
}
guard var link = session.info.link, let since = session.agentSince, now.timeIntervalSince(since) >= configuration.linkGrace else { continue }
if link.hooks == nil { link.hooks = false }
let agent = session.info.agent ?? session.info.typedAgent
if link.hooks == nil, let submitted = session.firstPromptAt, now.timeIntervalSince(submitted) >= configuration.linkGrace {
link.hooks = false
}
if link.mcp == nil { link.mcp = false }
if let agent = session.info.agent ?? session.info.typedAgent {
link.prompt = AgentLink.prompt(agent: agent, given: session.promptGiven, mcp: link.mcp)
if let agent {
link.prompt = AgentLink.prompt(agent: agent, given: session.promptGiven, mcp: link.mcp, copilotPrepared: session.copilotInstructionsPrepared)
}
if link != session.info.link {
session.info.link = link
Expand Down
9 changes: 9 additions & 0 deletions Sources/AgentTermHost/PTYProcess.swift
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,15 @@ public final class PTYProcess {
return ProcessNames.command(of: group)
}

/// Whether a program other than the one it started is in front of the
/// terminal: a command run at the shell's prompt. False at the prompt,
/// and once the program has ended.
public var runsAnotherProgram: Bool {
guard !finished else { return false }
let group = tcgetpgrp(master)
return group > 0 && group != pid
}

public func resize(_ size: TermSize) {
guard !finished else { return }
Self.setSize(size, on: master)
Expand Down
4 changes: 2 additions & 2 deletions Sources/AgentTermMac/AgentTermApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -813,9 +813,9 @@ private struct TabCommands: View {
Button("Close All Files") { model.closeFileTabs(pane: pane) }
.keyboardShortcut("w", modifiers: [.command, .shift])
.disabled(files.documents.isEmpty && model.diffTabFile == nil)
Button("Close Other Tabs…") { model.closeTabs(.init(keepGroup: model.frontStripTab, pane: pane)) }
Button(model.asksToClose(.init(keepGroup: model.frontStripTab, pane: pane)) ? "Close Other Tabs…" : "Close Other Tabs") { model.closeTabs(.init(keepGroup: model.frontStripTab, pane: pane)) }
.disabled(model.tabCount < 2)
Button(model.sessions.isEmpty ? "Close All Tabs" : "Close All Tabs…") { model.closeTabs(.init(pane: pane)) }
Button(model.asksToClose(.init(pane: pane)) ? "Close All Tabs…" : "Close All Tabs") { model.closeTabs(.init(pane: pane)) }
.disabled(model.tabCount == 0)
}
}
Expand Down
23 changes: 15 additions & 8 deletions Sources/AgentTermMac/AppModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2347,14 +2347,15 @@ final class AppModel: ObservableObject {
connection?.send(.kill(session: session))
}

/// A session the user asked to end, until that is confirmed. Ending
/// one stops what runs in it, an agent in the middle of its work for
/// one, and ⌘W is pressed out of habit: it asks first, as closing many
/// tabs does and as the iPhone does.
/// A session the user asked to end, until that is confirmed. Only one
/// at work is asked about (`SessionInfo.isBusy`): ending it stops an
/// agent in the middle of its turn, or a command; a shell at its prompt
/// or a done agent ends at once.
@Published var pendingEnd: SessionInfo?

func requestEnd(_ session: SessionID) {
pendingEnd = sessions.first { $0.id == session }
guard let info = sessions.first(where: { $0.id == session }) else { return }
if info.isBusy { pendingEnd = info } else { close(session) }
}

func takeControl() {
Expand Down Expand Up @@ -2535,10 +2536,16 @@ final class AppModel: ObservableObject {
sessions.filter { closes(stripTab(of: TabID.session($0)), by: request) }
}

/// Closes every tab but the one the request keeps. Sessions are running
/// programs, so ending any is asked about first.
/// Closes every tab but the one the request keeps. Ending a session at
/// work is asked about first; shells at their prompt and done agents
/// end with the tabs.
func closeTabs(_ request: CloseRequest = CloseRequest()) {
if sessionsEnded(by: request).isEmpty { closeTabsConfirmed(request) } else { pendingCloseRequest = request }
if asksToClose(request) { pendingCloseRequest = request } else { closeTabsConfirmed(request) }
}

/// Whether a request is asked about first: a session it ends is at work.
func asksToClose(_ request: CloseRequest) -> Bool {
sessionsEnded(by: request).contains(where: \.isBusy)
}

func closeTabsConfirmed(_ request: CloseRequest) {
Expand Down
2 changes: 1 addition & 1 deletion Sources/AgentTermMac/PaneViews.swift
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ struct SessionUsageBar: View {
// Whether its hooks and AgentTerm's MCP server talk to the host.
if let link = session.link {
Rectangle().fill(Color.white.opacity(0.08)).frame(width: 1, height: 24)
AgentLinkMark(link: link, typed: session.agent == nil ? name : nil)
AgentLinkMark(link: link, agent: agent, typed: session.agent == nil ? name : nil)
}
}
.frame(height: 46)
Expand Down
22 changes: 16 additions & 6 deletions Sources/AgentTermMac/Panes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -274,18 +274,28 @@ extension AppModel {

// MARK: Closing a tab of the strip, all it holds (#145)

/// Closes a tab of the strip and everything in it. One of the user's
/// own is asked first as `CloseWords.asks` says; an agent's is ending
/// the agent, which is always asked, and the host ends its shells and
/// closes its pages with it.
/// Closes a tab of the strip and everything in it. Shells are asked
/// about first only when one of them runs a command; pages, diffs and
/// files close at once, a file with unsaved changes asking to be saved.
/// An agent's tab is ending the agent, asked while it is at work, and
/// the host ends its shells and closes its pages with it.
func requestCloseGroup(_ group: String) {
if let holder = TabID.holder(of: group) {
if CloseWords.asks(holder.kind, count: members(of: group).count) { pendingGroupClose = group } else { closeGroup(group) }
if TabID.holder(of: group) != nil {
if asksToClose(group) { pendingGroupClose = group } else { closeGroup(group) }
} else if let agent = session(forTab: group) {
requestEnd(agent.id)
}
}

/// Whether closing a tab of the strip is asked first: its agent, or
/// one of its shells, is at work (`SessionInfo.isBusy`).
func asksToClose(_ group: String) -> Bool {
if let holder = TabID.holder(of: group) {
return holder.kind == .shells && userShells(in: holder.project).contains(where: \.isBusy)
}
return session(forTab: group)?.isBusy ?? false
}

/// Closes a tab of the user's own, once asked. A file with unsaved
/// changes is asked about, and stays open until it is answered.
func closeGroup(_ group: String) {
Expand Down
12 changes: 6 additions & 6 deletions Sources/AgentTermMac/SessionTabs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,8 @@ private struct SessionTab: View {
/// The tab of one of a project's groups of the user's own (#127): its
/// shells, its pages, its diffs or its files, with how many it holds. The
/// row under the strip has them, each with its own ×. The tab's × closes
/// all it holds, asked first as `CloseWords.asks` says (#145), as Chrome's
/// window closes its tabs.
/// all it holds, as Chrome's window closes its tabs (#145): asked first
/// only when a shell in it runs a command (`AppModel.asksToClose`).
private struct HolderTabLabel: View {
/// What is in front, which it shows (#178).
@EnvironmentObject private var front: FrontState
Expand All @@ -189,7 +189,7 @@ private struct HolderTabLabel: View {
private func close() { model.requestCloseGroup(id) }

/// What its × and its menu say: "End Shells", "Close Browser…".
private func closing(_ count: Int) -> String { CloseWords.groupAction(kind) + (CloseWords.asks(kind, count: count) ? "…" : "") }
private func closing(_ count: Int) -> String { CloseWords.groupAction(kind) + (model.asksToClose(id) ? "…" : "") }

var body: some View {
let members = model.members(of: id)
Expand Down Expand Up @@ -254,7 +254,7 @@ struct TabStripMenu: View {
Button("Close All Files") { model.closeFileTabs(pane: paneID) }
.disabled(files.documents.isEmpty && model.diffTabFile == nil)
.help("Close every file and diff of this pane. The terminals stay.")
Button(model.sessionsEnded(by: .init(pane: paneID)).isEmpty ? "Close All Tabs" : "Close All Tabs…") { model.closeTabs(.init(pane: paneID)) }
Button(model.asksToClose(.init(pane: paneID)) ? "Close All Tabs…" : "Close All Tabs") { model.closeTabs(.init(pane: paneID)) }
.disabled(count == 0)
.help("Close every tab of this pane, ending its sessions. Pinned tabs stay.")
}
Expand All @@ -268,8 +268,8 @@ struct CloseOthersButton: View {
private var count: Int { request.pane.flatMap { model.paneLayout.pane($0)?.tabs.count } ?? model.tabCount }

var body: some View {
// The dots say a question follows, which it does when sessions would end.
Button(model.sessionsEnded(by: request).isEmpty ? "Close Other Tabs" : "Close Other Tabs…") { model.closeTabs(request) }
// The dots say a question follows, which it does when a session at work would end.
Button(model.asksToClose(request) ? "Close Other Tabs…" : "Close Other Tabs") { model.closeTabs(request) }
.disabled(count < 2)
.help("Close every other tab of this pane, ending the other sessions. Pinned tabs stay.")
}
Expand Down
Loading
Loading