mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 02:47:34 +00:00
Share the existing terminal model result observer
This commit is contained in:
+26
-179
@@ -3,82 +3,17 @@ import { isRemoteRuntimePtyId } from '../../../../../../../shared/remote-runtime
|
||||
import { sendRuntimePtyInput } from '@/runtime/hosted-terminals/input/runtime-terminal-input-send'
|
||||
import { subscribeToRuntimeTerminalData } from '@/runtime/hosted-terminals/streams/runtime-terminal-data-subscription'
|
||||
import { NATIVE_CHAT_SUBMIT } from '../../../../../../../shared/native-chat/input/native-chat-paste-bytes'
|
||||
import { stripScrollbackAnsi } from '../../terminal/assembly/native-chat-scrape-fallback'
|
||||
import type { ClaudeModelSwitchOutcome } from '../../../../../../../shared/native-chat/input/native-chat-session-option-dispatch'
|
||||
|
||||
const DETECTION_TIMEOUT_MS = 5_000
|
||||
const MAX_OBSERVED_BYTES = 64 * 1024
|
||||
import {
|
||||
createClaudeModelSwitchConfirmationObserver as createConfirmationObserver,
|
||||
type SubscribeToData,
|
||||
type ClaudeModelSwitchConfirmationObserver
|
||||
} from '../../../../../../../shared/native-chat/input/native-chat-claude-model-switch-confirmation'
|
||||
|
||||
type SubscribeToData = (watcher: (data: string) => void) => Promise<() => void> | (() => void)
|
||||
|
||||
export type ClaudeModelSwitchConfirmationObserver = {
|
||||
ready: Promise<void>
|
||||
result: Promise<ClaudeModelSwitchOutcome>
|
||||
arm(): void
|
||||
startDetection(): void
|
||||
dispose(): void
|
||||
}
|
||||
|
||||
export function hasClaudeModelSwitchConfirmation(buffer: string): boolean {
|
||||
const text = compactTerminalText(buffer)
|
||||
return (
|
||||
text.includes('switchmodel?') && text.includes('thisconversationiscachedforthecurrentmodel')
|
||||
)
|
||||
}
|
||||
|
||||
function compactTerminalText(buffer: string): string {
|
||||
// Cursor-column escapes replace literal TUI spaces, so match independently of rendered gaps.
|
||||
return stripScrollbackAnsi(buffer).replace(/\s+/g, '').toLowerCase()
|
||||
}
|
||||
|
||||
function hasClaudeModelSwitchSuccess(buffer: string, modelLabel: string): boolean {
|
||||
const text = compactTerminalText(buffer)
|
||||
// Claude echoes neither the vendor prefix nor Orca's picker-only `alias` suffix.
|
||||
const label = modelLabel.replace(/^claude[\s-]+/i, '').replace(/\s+alias$/i, '')
|
||||
const marker = `setmodelto${label.replace(/\s+/g, '').toLowerCase()}`
|
||||
if (text.includes(marker)) {
|
||||
return true
|
||||
}
|
||||
// Match every picker token so a versioned echo cannot confirm the wrong context variant.
|
||||
const labelTokens = label.toLowerCase().match(/[a-z]+|\d+[a-z]*/g) ?? []
|
||||
const successStart = text.lastIndexOf('setmodelto')
|
||||
if (successStart === -1 || labelTokens.length === 0) {
|
||||
return false
|
||||
}
|
||||
const successText = text.slice(successStart)
|
||||
let tokenEnd = 0
|
||||
for (const token of labelTokens) {
|
||||
const tokenStart = successText.indexOf(token, tokenEnd)
|
||||
if (tokenStart === -1) {
|
||||
return false
|
||||
}
|
||||
tokenEnd = tokenStart + token.length
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function hasClaudeModelSwitchRejection(buffer: string): boolean {
|
||||
return compactTerminalText(buffer).includes('keptmodelas')
|
||||
}
|
||||
|
||||
function subscribeToClaudeModelSwitchData(args: {
|
||||
ptyId: string
|
||||
subscribeToData?: SubscribeToData
|
||||
watcher: (data: string) => void
|
||||
}): Promise<() => void> | (() => void) {
|
||||
if (args.subscribeToData) {
|
||||
return args.subscribeToData(args.watcher)
|
||||
}
|
||||
if (isRemoteRuntimePtyId(args.ptyId)) {
|
||||
return subscribeToRuntimeTerminalData(
|
||||
args.ptyId,
|
||||
`desktop:native-chat-model-switch:${args.ptyId}`,
|
||||
args.watcher,
|
||||
{ startAtLiveTail: true }
|
||||
)
|
||||
}
|
||||
return subscribeToPtyData(args.ptyId, args.watcher)
|
||||
}
|
||||
export {
|
||||
hasClaudeModelSwitchConfirmation,
|
||||
type ClaudeModelSwitchConfirmationObserver
|
||||
} from '../../../../../../../shared/native-chat/input/native-chat-claude-model-switch-confirmation'
|
||||
|
||||
export function createClaudeModelSwitchConfirmationObserver(args: {
|
||||
ptyId: string
|
||||
@@ -87,110 +22,22 @@ export function createClaudeModelSwitchConfirmationObserver(args: {
|
||||
submitConfirmation?: () => boolean | void
|
||||
timeoutMs?: number
|
||||
}): ClaudeModelSwitchConfirmationObserver {
|
||||
let armed = false
|
||||
let settled = false
|
||||
let confirmationSubmitted = false
|
||||
let observed = ''
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null
|
||||
let unsubscribe: (() => void) | null = null
|
||||
let resolveResult!: (outcome: ClaudeModelSwitchOutcome) => void
|
||||
let resolveReady!: () => void
|
||||
const result = new Promise<ClaudeModelSwitchOutcome>((resolve) => {
|
||||
resolveResult = resolve
|
||||
return createConfirmationObserver({
|
||||
expectedModelLabel: args.expectedModelLabel,
|
||||
timeoutMs: args.timeoutMs,
|
||||
subscribeToData:
|
||||
args.subscribeToData ??
|
||||
((watcher) =>
|
||||
isRemoteRuntimePtyId(args.ptyId)
|
||||
? subscribeToRuntimeTerminalData(
|
||||
args.ptyId,
|
||||
`desktop:native-chat-model-switch:${args.ptyId}`,
|
||||
watcher,
|
||||
{ startAtLiveTail: true }
|
||||
)
|
||||
: subscribeToPtyData(args.ptyId, watcher)),
|
||||
submitConfirmation:
|
||||
args.submitConfirmation ??
|
||||
(() => sendRuntimePtyInput(args.ptyId, NATIVE_CHAT_SUBMIT, 'driving'))
|
||||
})
|
||||
const ready = new Promise<void>((resolve) => {
|
||||
resolveReady = resolve
|
||||
})
|
||||
|
||||
const finish = (outcome: ClaudeModelSwitchOutcome): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
if (timeout !== null) {
|
||||
clearTimeout(timeout)
|
||||
timeout = null
|
||||
}
|
||||
unsubscribe?.()
|
||||
unsubscribe = null
|
||||
resolveResult(outcome)
|
||||
}
|
||||
|
||||
const scheduleTimeout = (): void => {
|
||||
if (timeout !== null) {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
timeout = setTimeout(() => finish('unknown'), args.timeoutMs ?? DETECTION_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
const observeData = (data: string): void => {
|
||||
if (!armed || settled) {
|
||||
return
|
||||
}
|
||||
observed = `${observed}${data}`.slice(-MAX_OBSERVED_BYTES)
|
||||
if (args.expectedModelLabel && hasClaudeModelSwitchSuccess(observed, args.expectedModelLabel)) {
|
||||
finish('applied')
|
||||
return
|
||||
}
|
||||
if (hasClaudeModelSwitchRejection(observed)) {
|
||||
finish('rejected')
|
||||
return
|
||||
}
|
||||
if (!confirmationSubmitted && hasClaudeModelSwitchConfirmation(observed)) {
|
||||
confirmationSubmitted = true
|
||||
try {
|
||||
// The picker already authorizes switching; this exact warning defaults to Yes and needs one Enter.
|
||||
const accepted = args.submitConfirmation
|
||||
? args.submitConfirmation() !== false
|
||||
: sendRuntimePtyInput(args.ptyId, NATIVE_CHAT_SUBMIT, 'driving')
|
||||
if (!accepted) {
|
||||
finish('unknown')
|
||||
return
|
||||
}
|
||||
scheduleTimeout()
|
||||
} catch {
|
||||
finish('unknown')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const subscription = subscribeToClaudeModelSwitchData({
|
||||
ptyId: args.ptyId,
|
||||
subscribeToData: args.subscribeToData,
|
||||
watcher: observeData
|
||||
})
|
||||
void Promise.resolve(subscription)
|
||||
.then((dispose) => {
|
||||
if (settled) {
|
||||
dispose()
|
||||
} else {
|
||||
unsubscribe = dispose
|
||||
}
|
||||
})
|
||||
.catch(() => finish('unknown'))
|
||||
.finally(resolveReady)
|
||||
} catch {
|
||||
finish('unknown')
|
||||
resolveReady()
|
||||
}
|
||||
|
||||
return {
|
||||
ready,
|
||||
result,
|
||||
arm: () => {
|
||||
if (settled || armed) {
|
||||
return
|
||||
}
|
||||
armed = true
|
||||
},
|
||||
startDetection: () => {
|
||||
// Start timeout at command delivery; SSH body/Enter latency must not consume the response window.
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
scheduleTimeout()
|
||||
},
|
||||
dispose: () => finish('unknown')
|
||||
}
|
||||
}
|
||||
|
||||
+2
-27
@@ -2,34 +2,9 @@
|
||||
|
||||
import type { NativeChatMessage } from '../../../../../../../shared/native-chat/native-chat-types'
|
||||
|
||||
const ESC = String.fromCharCode(27)
|
||||
const ANSI_ESCAPE_PATTERN = new RegExp(`${ESC}\\[[0-?]*[ -/]*[@-~]`, 'g')
|
||||
const OSC_SEQUENCE_PATTERN = new RegExp(`${ESC}\\][^\\u0007]*(?:\\u0007|${ESC}\\\\)`, 'g')
|
||||
const SINGLE_ESCAPE_PATTERN = new RegExp(`${ESC}(?:[@-Z\\\\-_]|[()*+\\-./][0-~]|c)`, 'g')
|
||||
import { stripScrollbackAnsi } from '../../../../../../../shared/terminal/output/terminal-safe-text'
|
||||
|
||||
function stripUnsupportedControlCharacters(value: string): string {
|
||||
let result = ''
|
||||
for (const char of value) {
|
||||
const code = char.charCodeAt(0)
|
||||
// Drop C0 control chars except tab (9) and newline (10); keep DEL (127) out.
|
||||
if (code <= 8 || code === 11 || code === 12 || (code >= 14 && code <= 31) || code === 127) {
|
||||
continue
|
||||
}
|
||||
result += char
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export function stripScrollbackAnsi(value: string): string {
|
||||
return stripUnsupportedControlCharacters(
|
||||
value
|
||||
.replace(OSC_SEQUENCE_PATTERN, '')
|
||||
.replace(ANSI_ESCAPE_PATTERN, '')
|
||||
.replace(SINGLE_ESCAPE_PATTERN, '')
|
||||
)
|
||||
.replace(/\r\n/g, '\n')
|
||||
.replace(/\r/g, '\n')
|
||||
}
|
||||
export { stripScrollbackAnsi } from '../../../../../../../shared/terminal/output/terminal-safe-text'
|
||||
|
||||
// Without per-agent parsing, leading shell/prompt markers are only a best-effort user-role heuristic.
|
||||
const USER_PROMPT_MARKERS = ['$', '%', '>', '#', '❯', '➜', '»']
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import { stripScrollbackAnsi } from '../../terminal/output/terminal-safe-text'
|
||||
import type { ClaudeModelSwitchOutcome } from './native-chat-session-option-dispatch'
|
||||
|
||||
const DETECTION_TIMEOUT_MS = 5_000
|
||||
const MAX_OBSERVED_BYTES = 64 * 1024
|
||||
|
||||
export type SubscribeToData = (
|
||||
watcher: (data: string) => void
|
||||
) => Promise<() => void> | (() => void)
|
||||
|
||||
export type ClaudeModelSwitchConfirmationObserver = {
|
||||
ready: Promise<void>
|
||||
result: Promise<ClaudeModelSwitchOutcome>
|
||||
arm(): void
|
||||
startDetection(): void
|
||||
dispose(): void
|
||||
}
|
||||
|
||||
export function hasClaudeModelSwitchConfirmation(buffer: string): boolean {
|
||||
const text = compactTerminalText(buffer)
|
||||
return (
|
||||
text.includes('switchmodel?') && text.includes('thisconversationiscachedforthecurrentmodel')
|
||||
)
|
||||
}
|
||||
|
||||
function compactTerminalText(buffer: string): string {
|
||||
// Cursor-column escapes replace literal TUI spaces, so match independently of rendered gaps.
|
||||
return stripScrollbackAnsi(buffer).replace(/\s+/g, '').toLowerCase()
|
||||
}
|
||||
|
||||
function hasClaudeModelSwitchSuccess(buffer: string, modelLabel: string): boolean {
|
||||
const text = compactTerminalText(buffer)
|
||||
// Claude echoes neither the vendor prefix nor Orca's picker-only `alias` suffix.
|
||||
const label = modelLabel.replace(/^claude[\s-]+/i, '').replace(/\s+alias$/i, '')
|
||||
const marker = `setmodelto${label.replace(/\s+/g, '').toLowerCase()}`
|
||||
if (text.includes(marker)) {
|
||||
return true
|
||||
}
|
||||
// Match every picker token so a versioned echo cannot confirm the wrong context variant.
|
||||
const labelTokens = label.toLowerCase().match(/[a-z]+|\d+[a-z]*/g) ?? []
|
||||
const successStart = text.lastIndexOf('setmodelto')
|
||||
if (successStart === -1 || labelTokens.length === 0) {
|
||||
return false
|
||||
}
|
||||
const successText = text.slice(successStart)
|
||||
let tokenEnd = 0
|
||||
for (const token of labelTokens) {
|
||||
const tokenStart = successText.indexOf(token, tokenEnd)
|
||||
if (tokenStart === -1) {
|
||||
return false
|
||||
}
|
||||
tokenEnd = tokenStart + token.length
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function hasClaudeModelSwitchRejection(buffer: string): boolean {
|
||||
return compactTerminalText(buffer).includes('keptmodelas')
|
||||
}
|
||||
|
||||
export function createClaudeModelSwitchConfirmationObserver(args: {
|
||||
expectedModelLabel: string | null
|
||||
subscribeToData: SubscribeToData
|
||||
submitConfirmation: () => boolean | void
|
||||
timeoutMs?: number
|
||||
}): ClaudeModelSwitchConfirmationObserver {
|
||||
let armed = false
|
||||
let settled = false
|
||||
let confirmationSubmitted = false
|
||||
let observed = ''
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null
|
||||
let unsubscribe: (() => void) | null = null
|
||||
let resolveResult!: (outcome: ClaudeModelSwitchOutcome) => void
|
||||
let resolveReady!: () => void
|
||||
const result = new Promise<ClaudeModelSwitchOutcome>((resolve) => {
|
||||
resolveResult = resolve
|
||||
})
|
||||
const ready = new Promise<void>((resolve) => {
|
||||
resolveReady = resolve
|
||||
})
|
||||
|
||||
const finish = (outcome: ClaudeModelSwitchOutcome): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
if (timeout !== null) {
|
||||
clearTimeout(timeout)
|
||||
timeout = null
|
||||
}
|
||||
unsubscribe?.()
|
||||
unsubscribe = null
|
||||
resolveResult(outcome)
|
||||
}
|
||||
|
||||
const scheduleTimeout = (): void => {
|
||||
if (timeout !== null) {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
timeout = setTimeout(() => finish('unknown'), args.timeoutMs ?? DETECTION_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
const observeData = (data: string): void => {
|
||||
if (!armed || settled) {
|
||||
return
|
||||
}
|
||||
observed = `${observed}${data}`.slice(-MAX_OBSERVED_BYTES)
|
||||
if (args.expectedModelLabel && hasClaudeModelSwitchSuccess(observed, args.expectedModelLabel)) {
|
||||
finish('applied')
|
||||
return
|
||||
}
|
||||
if (hasClaudeModelSwitchRejection(observed)) {
|
||||
finish('rejected')
|
||||
return
|
||||
}
|
||||
if (!confirmationSubmitted && hasClaudeModelSwitchConfirmation(observed)) {
|
||||
confirmationSubmitted = true
|
||||
try {
|
||||
// The picker already authorizes switching; this exact warning defaults to Yes and needs one Enter.
|
||||
const accepted = args.submitConfirmation() !== false
|
||||
if (!accepted) {
|
||||
finish('unknown')
|
||||
return
|
||||
}
|
||||
scheduleTimeout()
|
||||
} catch {
|
||||
finish('unknown')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const subscription = args.subscribeToData(observeData)
|
||||
void Promise.resolve(subscription)
|
||||
.then((dispose) => {
|
||||
if (settled) {
|
||||
dispose()
|
||||
} else {
|
||||
unsubscribe = dispose
|
||||
}
|
||||
})
|
||||
.catch(() => finish('unknown'))
|
||||
.finally(resolveReady)
|
||||
} catch {
|
||||
finish('unknown')
|
||||
resolveReady()
|
||||
}
|
||||
|
||||
return {
|
||||
ready,
|
||||
result,
|
||||
arm: () => {
|
||||
if (settled || armed) {
|
||||
return
|
||||
}
|
||||
armed = true
|
||||
},
|
||||
startDetection: () => {
|
||||
// Start timeout at command delivery; SSH body/Enter latency must not consume the response window.
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
scheduleTimeout()
|
||||
},
|
||||
dispose: () => finish('unknown')
|
||||
}
|
||||
}
|
||||
@@ -12,3 +12,32 @@ export function terminalSafe(value: string): string {
|
||||
export function terminalSafeLine(value: string): string {
|
||||
return terminalSafe(value).replaceAll(/[\r\n]+/g, ' ')
|
||||
}
|
||||
|
||||
const ESC = String.fromCharCode(27)
|
||||
const ANSI_ESCAPE_PATTERN = new RegExp(`${ESC}\\[[0-?]*[ -/]*[@-~]`, 'g')
|
||||
const OSC_SEQUENCE_PATTERN = new RegExp(`${ESC}\\][^\\u0007]*(?:\\u0007|${ESC}\\\\)`, 'g')
|
||||
const SINGLE_ESCAPE_PATTERN = new RegExp(`${ESC}(?:[@-Z\\\\-_]|[()*+\\-./][0-~]|c)`, 'g')
|
||||
|
||||
function stripUnsupportedControlCharacters(value: string): string {
|
||||
let result = ''
|
||||
for (const char of value) {
|
||||
const code = char.charCodeAt(0)
|
||||
// Drop C0 control chars except tab (9) and newline (10); keep DEL (127) out.
|
||||
if (code <= 8 || code === 11 || code === 12 || (code >= 14 && code <= 31) || code === 127) {
|
||||
continue
|
||||
}
|
||||
result += char
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export function stripScrollbackAnsi(value: string): string {
|
||||
return stripUnsupportedControlCharacters(
|
||||
value
|
||||
.replace(OSC_SEQUENCE_PATTERN, '')
|
||||
.replace(ANSI_ESCAPE_PATTERN, '')
|
||||
.replace(SINGLE_ESCAPE_PATTERN, '')
|
||||
)
|
||||
.replace(/\r\n/g, '\n')
|
||||
.replace(/\r/g, '\n')
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user