From 41739d7cf9fc75a3957b1a37547bd079fccc66d3 Mon Sep 17 00:00:00 2001 From: hyperion Date: Mon, 23 Nov 2026 13:31:22 +0100 Subject: [PATCH] - Reworked internal signals - Separated input passing from signal calling - Exposed command registry to the broader codebase - Moved command execution call to internal shell logic - TTY is now expected to watch for stdout escape sequences to perform tasks --- src/core/command_io.ts | 5 +-- src/core/command_registry.ts | 4 ++ src/core/commands/clear.ts | 4 +- src/core/commands/help.ts | 27 +++++++++++++ src/core/commands/testasync.ts | 33 +++++++-------- src/core/history_state.ts | 10 ++--- src/core/shell_state.ts | 5 ++- src/core/signal.ts | 14 ------- src/core/util/errors.ts | 5 ++- src/core/util/parser.ts | 3 +- src/dev.ts | 37 +++++++++-------- src/shell/process.ts | 69 +++++++++++--------------------- src/shell/process_manager.ts | 17 ++++++-- src/shell/shell.ts | 73 ++++++++++++++++++++++++---------- src/test.ts | 18 +++++++++ 15 files changed, 191 insertions(+), 133 deletions(-) create mode 100644 src/core/commands/help.ts delete mode 100644 src/core/signal.ts create mode 100644 src/test.ts diff --git a/src/core/command_io.ts b/src/core/command_io.ts index 12627ae..fd529b3 100644 --- a/src/core/command_io.ts +++ b/src/core/command_io.ts @@ -1,8 +1,7 @@ -import type { Signal, SIGNAL_MAP } from "./signal"; +import type { Input } from "@shell/shell"; export interface CommandIO { writeStdout(data: Uint8Array): void; writeStderr(data: Uint8Array): void; - getSignal(): Promise; - sendSignal(sig: SIGNAL_MAP): void; + onInput(): Promise; } diff --git a/src/core/command_registry.ts b/src/core/command_registry.ts index 8279228..b9310b3 100644 --- a/src/core/command_registry.ts +++ b/src/core/command_registry.ts @@ -3,11 +3,14 @@ import { descriptor as cat } from "./commands/cat"; import { descriptor as cd } from "./commands/cd"; import { descriptor as clear } from "./commands/clear"; import { descriptor as echo } from "./commands/echo"; +import { descriptor as help } from "./commands/help"; import { descriptor as ls } from "./commands/ls"; import { descriptor as pwd } from "./commands/pwd"; import { descriptor as testasync } from "./commands/testasync"; import { descriptor as touch } from "./commands/touch"; +export type CommandRegistry = ReadonlyMap; + const reg = new Map(); //reg.set(descriptor.name, descriptor <- imported const from command implementation file); reg.set(echo.name, echo); @@ -18,6 +21,7 @@ reg.set(cat.name, cat); reg.set(pwd.name, pwd); reg.set(clear.name, clear); reg.set(touch.name, touch); +reg.set(help.name, help); Object.freeze(reg); export const COMMAND_REGISTRY: ReadonlyMap = reg; diff --git a/src/core/commands/clear.ts b/src/core/commands/clear.ts index 071e402..da58f50 100644 --- a/src/core/commands/clear.ts +++ b/src/core/commands/clear.ts @@ -2,13 +2,13 @@ import type { CommandDescriptor, CommandOutput } from "@core/command"; import type { CommandIO } from "@core/command_io"; import { createSuccessResult, type ResultSuccess } from "@core/result"; import type { ShellState } from "@core/shell_state"; -import { SIGNAL_MAP } from "@core/signal"; import type { ShellError } from "@core/util/errors"; export const COMMAND_NAME = "clear"; async function main(io: CommandIO, state: ShellState, __args: string[]): Promise> { - io.sendSignal(SIGNAL_MAP.CLR); + const encoded = new TextEncoder().encode("\x1b[2J\x1b[0;0H"); + io.writeStdout(encoded); const result: ResultSuccess = createSuccessResult(COMMAND_NAME); diff --git a/src/core/commands/help.ts b/src/core/commands/help.ts new file mode 100644 index 0000000..f4ee964 --- /dev/null +++ b/src/core/commands/help.ts @@ -0,0 +1,27 @@ +import type { CommandDescriptor, CommandOutput } from "@core/command"; +import type { CommandIO } from "@core/command_io"; +import { COMMAND_REGISTRY } from "@core/command_registry"; +import { createSuccessResult, type ResultSuccess } from "@core/result"; +import type { ShellState } from "@core/shell_state"; +import type { ShellError } from "@core/util/errors"; + +export const COMMAND_NAME = "help"; + +async function main(io: CommandIO, state: ShellState, args: string[]): Promise> { + const e = new TextEncoder(); + for (const entry of COMMAND_REGISTRY.keys()) { + io.writeStdout(e.encode(` ${entry}\n`)); + } + + const result: ResultSuccess = createSuccessResult(COMMAND_NAME); + + return { + state: state, + result, + }; +} + +export const descriptor: CommandDescriptor = { + fn: main, + name: COMMAND_NAME, +}; diff --git a/src/core/commands/testasync.ts b/src/core/commands/testasync.ts index 6c4af28..f68207e 100644 --- a/src/core/commands/testasync.ts +++ b/src/core/commands/testasync.ts @@ -2,7 +2,6 @@ import type { CommandDescriptor, CommandOutput } from "@core/command"; import type { CommandIO } from "@core/command_io"; import type { ResultSuccess } from "@core/result"; import type { ShellState } from "@core/shell_state"; -import { SIGNAL_MAP } from "@core/signal"; import type { ShellError } from "@core/util/errors"; import { createImmutableBuffer } from "@core/util/immutable_buffer"; @@ -10,26 +9,24 @@ const COMMAND_NAME = "async"; async function main(io: CommandIO, state: ShellState, __args: string[]): Promise> { while (true) { - const out = await io.getSignal(); + const sig = await io.onInput(); - if (out.type === SIGNAL_MAP.INPUT) { - const encoded = new TextEncoder().encode(("user pressed: " + out.payload + "\n") as string); - io.writeStdout(encoded); + const encoded = new TextEncoder().encode(("user pressed: " + sig.sequence + "\n") as string); + io.writeStdout(encoded); - if (out.payload === "x") { - const result: ResultSuccess = { - type: "success", - exitCode: 0, - stdout: createImmutableBuffer(new Uint8Array()), - stderr: createImmutableBuffer(new Uint8Array()), - commandName: COMMAND_NAME, - }; + if (sig.sequence === "\x03") { + const result: ResultSuccess = { + type: "success", + exitCode: 0, + stdout: createImmutableBuffer(new Uint8Array()), + stderr: createImmutableBuffer(new Uint8Array()), + commandName: COMMAND_NAME, + }; - return { - state: state, - result, - }; - } + return { + state: state, + result, + }; } } } diff --git a/src/core/history_state.ts b/src/core/history_state.ts index ce27b5a..e7bf994 100644 --- a/src/core/history_state.ts +++ b/src/core/history_state.ts @@ -1,9 +1,9 @@ const HISTORY_MAX_CAPACITY = 255; -export type HistoryState = readonly string[]; +export type HistoryState = readonly Uint8Array[]; -export function addHistoryEntry(state: HistoryState, input: string): HistoryState { - const entries: string[] = [...state]; +export function addHistoryEntry(state: HistoryState, input: Uint8Array): HistoryState { + const entries: Uint8Array[] = [...state]; if (entries.length === HISTORY_MAX_CAPACITY) { entries.shift(); @@ -12,11 +12,11 @@ export function addHistoryEntry(state: HistoryState, input: string): HistoryStat entries.push(input); } - const result: readonly string[] = entries; + const result: readonly Uint8Array[] = entries; return Object.freeze(result); } -export function getHistoryEntry(state: HistoryState, index: number): string { +export function getHistoryEntry(state: HistoryState, index: number): Uint8Array { const entry = state[index]; if (entry === undefined) { // Add a custom error object later diff --git a/src/core/shell_state.ts b/src/core/shell_state.ts index 2155412..538cd64 100644 --- a/src/core/shell_state.ts +++ b/src/core/shell_state.ts @@ -9,6 +9,7 @@ export interface ShellState { readonly users: ReadonlyMap; readonly groups: ReadonlyMap; readonly sessionStack: ReadonlyArray; + //readonly commmandRegistry: CommandRegistry; } export function createInitialShellState( @@ -16,12 +17,14 @@ export function createInitialShellState( users: ReadonlyMap, groups: ReadonlyMap, user: UserInfo, + //commandRegistry: CommandRegistry, ): ShellState { return Object.freeze({ filesystem, users, groups, sessionStack: Object.freeze([createInitialSessionState(user)]), + //commandRegistry, }); } @@ -63,7 +66,7 @@ export function withCwd(state: ShellState, ptr: NodePointer): ShellState { } satisfies ShellState); } -export function withHistory(state: ShellState, input: string): ShellState { +export function withHistory(state: ShellState, input: Uint8Array): ShellState { const session = getCurrentSession(state); const newSession = Object.freeze({ diff --git a/src/core/signal.ts b/src/core/signal.ts deleted file mode 100644 index cd61c32..0000000 --- a/src/core/signal.ts +++ /dev/null @@ -1,14 +0,0 @@ -//Payload optional because command that handles that signal -// is going to know what shape it is, therefore also able to cast it; -export type Signal = { - type: SIGNAL_MAP; - payload?: unknown; -}; - -export enum SIGNAL_MAP { - CLR = 0, - SIGINT = 2, - SIGTERM = 3, - SIGKILL = 9, - INPUT = 10, -} diff --git a/src/core/util/errors.ts b/src/core/util/errors.ts index 6033cff..9506a97 100644 --- a/src/core/util/errors.ts +++ b/src/core/util/errors.ts @@ -1,3 +1,5 @@ +import type { SIGNAL_MAP } from "@shell/shell"; + export interface ShellError { readonly errorType: string; readonly message: string; @@ -219,6 +221,5 @@ export interface ProtocolError extends ShellError { /** Process was killed by a signal (Exit = 128 + signalNumber) */ export interface SignalTerminationError extends ShellError { errorType: "SignalTermination"; - signalNumber: number; // e.g., 9 (SIGKILL), 15 (SIGTERM), 2 (SIGINT) - signalName: string; // e.g., "SIGTERM", "SIGKILL" + signal: SIGNAL_MAP; } diff --git a/src/core/util/parser.ts b/src/core/util/parser.ts index 5693071..17960a3 100644 --- a/src/core/util/parser.ts +++ b/src/core/util/parser.ts @@ -6,13 +6,14 @@ interface UnclosedQuoteError { timestamp: number; } -export function tokenize(input: string): string[] { +export function tokenize(buff: Uint8Array): string[] { enum State { Normal, SingleQuote, DoubleQuote, Escape, } + const input = new TextDecoder().decode(buff); const tokens: string[] = []; const buffer: string[] = []; diff --git a/src/dev.ts b/src/dev.ts index 1374c75..955af36 100644 --- a/src/dev.ts +++ b/src/dev.ts @@ -1,8 +1,13 @@ import { getCurrentSession } from "@core/session_manager"; -import { SIGNAL_MAP } from "@core/signal"; import { resolvePointerToHome } from "@core/util/path_resolver"; +import { stdin as input, stdout as output } from "node:process"; +import readline from "node:readline"; import { Termos } from "./entry"; +process.stdin.setRawMode(true); +readline.emitKeypressEvents(process.stdin); + +const rl = readline.createInterface({ input, output }); //import { deserializeFileSystem } from "@shell/serializer"; //import { Shell } from "@shell/shell"; @@ -35,25 +40,25 @@ shell.on("result", payload => { process.stdout.write("\n" + resolvePointerToHome(payload.state, getCurrentSession(payload.state).cwd) + "\n> "); }); -shell.on("signal", payload => { - if (payload.sig === SIGNAL_MAP.CLR) console.clear(); -}); - shell.on("stdout", payload => { const decoded = new TextDecoder().decode(payload.data); - process.stdout.write(decoded); -}); - -console.clear(); -process.stdout.write(resolvePointerToHome(shell.State, getCurrentSession(shell.State).cwd) + "\n> "); -process.stdin.on("data", async data => { - if (shell.BoundPID !== null) { - shell.sendInput(data.toString().trim()); + if (decoded === "\x1b[2J\x1b[0;0H") { + console.clear(); return; } - const input = data.toString().trim(); - await shell.execute(input); + process.stdout.write(decoded); }); -//export { Termos }; +let buff = ""; + +console.clear(); +process.stdout.write(resolvePointerToHome(shell.State, getCurrentSession(shell.State).cwd) + "\n> "); +process.stdin.on("keypress", async (str, key) => { + if (key.sequence === "\f") console.clear(); + + if (buff.length > 3) buff = ""; + buff = buff + key.name; + + await shell.input(key); +}); diff --git a/src/shell/process.ts b/src/shell/process.ts index e287aec..e3942d1 100644 --- a/src/shell/process.ts +++ b/src/shell/process.ts @@ -2,16 +2,15 @@ import type { CommandDescriptor } from "@core/command"; import type { CommandIO } from "@core/command_io"; import { createErrorResult, createSuccessResult, type ResultError, type ResultSuccess } from "@core/result"; import type { ShellState } from "@core/shell_state"; -import { SIGNAL_MAP, type Signal } from "@core/signal"; import type { ShellError, SignalTerminationError } from "@core/util/errors"; import { createImmutableBuffer } from "@core/util/immutable_buffer"; import { concatUint8Arrays, splitUint8Array } from "@termos/util/concat"; import { EventEmitter } from "./event_emitter"; -import type { ShellEventMap } from "./shell"; +import { ShellEventMap, SIGNAL_MAP, type Input } from "./shell"; export class Process { - private _SignalQueue: Signal[] = []; - private _SignalHandler: ((signal: Signal) => void) | null = null; + private _InputQueue: Input[] = []; + private _InputHandler: ((signal: Input) => void) | null = null; private _StdoutChunks: Uint8Array[] = []; private _StderrChunks: Uint8Array[] = []; private _Settled: boolean = false; @@ -52,21 +51,16 @@ export class Process { } } - private _sendSignal(sig: SIGNAL_MAP): void { - this._EventEmitter.emit("signal", { pid: this.PID, sig: sig }); - } - public execute(): void { const io: CommandIO = { - sendSignal: (sig: SIGNAL_MAP) => this._sendSignal(sig), writeStdout: (data: Uint8Array) => this.writeToOutput(this._StdoutChunks, "stdout", data), writeStderr: (data: Uint8Array) => this.writeToOutput(this._StderrChunks, "stderr", data), - getSignal: () => { - const signal: Signal | undefined = this._SignalQueue.shift(); + onInput: () => { + const signal: Input | undefined = this._InputQueue.shift(); if (signal !== undefined) return Promise.resolve(signal); - const promise = new Promise(resolve => { - this._SignalHandler = resolve; + const promise = new Promise(resolve => { + this._InputHandler = resolve; }); return promise; }, @@ -120,51 +114,34 @@ export class Process { }); } - public sendSignal(signal: Signal): void { + public sendInput(input: Input): void { + if (this._Settled) return; + + if (this._InputHandler !== null) { + this._InputHandler(input); + this._InputHandler = null; + } else { + this._InputQueue.push(input); + } + } + + public sendSignal(signal: SIGNAL_MAP): void { if (this._Settled) return; const result: ResultError = createErrorResult( "SignalTermination", - `Process ${this.Name}(${this.PID}) killed by a ${SIGNAL_MAP[signal.type]}(${signal.type})`, - { signalNumber: signal.type, signalName: SIGNAL_MAP[signal.type] }, + `Process ${this.Name} PID: ${this.PID} killed by a ${SIGNAL_MAP[signal]}`, + { signal }, this.CommandDescriptor.name, ); - switch (signal.type) { - case SIGNAL_MAP.SIGKILL: - this._SignalHandler = null; - this._Settled = true; - - this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State }); - return; - - case SIGNAL_MAP.SIGTERM: - if (this._SignalHandler !== null) { - this._SignalHandler(signal); - this._SignalHandler = null; - } - - this._Settled = true; - this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State }); - - return; + switch (signal) { case SIGNAL_MAP.SIGINT: - if (this._SignalHandler !== null) { - this._SignalHandler(signal); - this._SignalHandler = null; - } - this._Settled = true; - this._EventEmitter.emit("result", { pid: this.PID, result: result, state: this.State }); return; default: - if (this._SignalHandler !== null) { - this._SignalHandler(signal); - this._SignalHandler = null; - } else { - this._SignalQueue.push(signal); - } + break; } } diff --git a/src/shell/process_manager.ts b/src/shell/process_manager.ts index 4c83ac3..eed7472 100644 --- a/src/shell/process_manager.ts +++ b/src/shell/process_manager.ts @@ -1,9 +1,8 @@ import type { CommandDescriptor } from "@core/command"; import type { ShellState } from "@core/shell_state"; -import { SIGNAL_MAP, type Signal } from "@core/signal"; import { EventEmitter } from "./event_emitter"; import { Process } from "./process"; -import type { ShellEventMap } from "./shell"; +import { Input, ShellEventMap, SIGNAL_MAP } from "./shell"; export class ProcessManager { private _Processes: Map = new Map(); @@ -30,7 +29,7 @@ export class ProcessManager { return pid; } - public sendSignal(pid: number, signal: Signal): void { + public sendSignal(pid: number, signal: SIGNAL_MAP): void { const process = this._Processes.get(pid); if (!process) { @@ -42,6 +41,16 @@ export class ProcessManager { process.sendSignal(signal); } + public sendInput(pid: number, input: Input): void { + const process = this._Processes.get(pid); + if (!process) { + //Implement a proper error object later to return to shell + console.error("PID not found"); + return; + } + process.sendInput(input); + } + public kill(pid: number): void { const process = this._Processes.get(pid); @@ -52,7 +61,7 @@ export class ProcessManager { } //Make global signals an enum later - process.sendSignal({ type: SIGNAL_MAP.SIGKILL } satisfies Signal); + process.sendSignal(SIGNAL_MAP.SIGINT); } public on(type: K, handler: (payload: ShellEventMap[K]) => void): () => void { diff --git a/src/shell/shell.ts b/src/shell/shell.ts index e24e9db..a22c519 100644 --- a/src/shell/shell.ts +++ b/src/shell/shell.ts @@ -2,10 +2,10 @@ import { COMMAND_REGISTRY } from "@core/command_registry"; import { createErrorResult, type Result } from "@core/result"; import { getCurrentSession, type SessionState } from "@core/session_manager"; import { withExitCode, withHistory, type ShellState } from "@core/shell_state"; -import { SIGNAL_MAP } from "@core/signal"; import type { ShellError } from "@core/util/errors"; import { createImmutableBuffer } from "@core/util/immutable_buffer"; import { tokenize } from "@core/util/parser"; +import { concatUint8Arrays } from "@termos/util/concat"; import { EventEmitter } from "./event_emitter"; import { ProcessManager } from "./process_manager"; @@ -14,12 +14,32 @@ export interface TTYState { height: number; } +export enum SIGNAL_MAP { + CLR = 0, + SIGINT = 1, +} + +export interface Input { + sequence: string; + name: string; + ctrl: boolean; + meta: boolean; + shift: boolean; +} + export class Shell { private _State: Readonly; private _Session: SessionState; private _ProcessManager: ProcessManager = new ProcessManager(); private _EventEmitter: EventEmitter = new EventEmitter(); - private _GlobalKeyMap: ReadonlyMap; + private _SignalMap: ReadonlyMap = new Map([ + ["\f", SIGNAL_MAP.CLR], + ["\x03", SIGNAL_MAP.SIGINT], + ]); + private readonly E: TextEncoder = new TextEncoder(); + private readonly D: TextDecoder = new TextDecoder(); + + private _Stdin: Uint8Array = new Uint8Array(); public BoundPID: number | null = null; @@ -27,12 +47,6 @@ export class Shell { this._State = Object.freeze(state); this._Session = state.sessionStack[state.sessionStack.length - 1]!; - //Temporary solution for sigint keybind - const map = new Map(); - map.set("ctrl+c", SIGNAL_MAP.SIGINT); - - this._GlobalKeyMap = map; - this._ProcessManager.on("stdout", payload => this._EventEmitter.emit("stdout", payload)); this._ProcessManager.on("stderr", payload => this._EventEmitter.emit("stderr", payload)); this._ProcessManager.on("process", payload => this._EventEmitter.emit("process", payload)); @@ -50,7 +64,34 @@ export class Shell { this._ProcessManager.on("signal", payload => this._EventEmitter.emit("signal", payload)); } - public async execute(input: string): Promise { + public async input(key: { + sequence: string; + name: string; + ctrl: boolean; + meta: boolean; + shift: boolean; + }): Promise { + const stdin = Uint8Array.from(this._Stdin); + switch (key.sequence) { + case "\x03": + if (!this.BoundPID) break; + const sig = this._SignalMap.get(key.sequence)!; + this._ProcessManager.sendSignal(this.BoundPID, sig); + break; + case "\r": + if (this.BoundPID) this._ProcessManager.sendInput(this.BoundPID, key); + this._Stdin = new Uint8Array(); + this._execute(stdin); + break; + default: + if (this.BoundPID) this._ProcessManager.sendInput(this.BoundPID, key); + const buffer = this.E.encode(key.sequence); + this._Stdin = concatUint8Arrays([stdin, buffer]); + break; + } + } + + private async _execute(input: Uint8Array): Promise { const parsed = tokenize(input); if (!parsed[0]) return; @@ -96,18 +137,8 @@ export class Shell { this.BoundPID = pid; } - public sendInput(input: string): void { - const signal = this._GlobalKeyMap.get(input); - - if (signal !== undefined) { - if (this.BoundPID !== null) { - this._ProcessManager.sendSignal(this.BoundPID, { type: signal }); - } - } else { - if (this.BoundPID !== null) { - this._ProcessManager.sendSignal(this.BoundPID, { type: SIGNAL_MAP.INPUT, payload: input }); - } - } + public getHistoryIndex(i: number): Uint8Array | undefined { + return this._Session.history[i]; } public get State(): Readonly { diff --git a/src/test.ts b/src/test.ts new file mode 100644 index 0000000..82f855f --- /dev/null +++ b/src/test.ts @@ -0,0 +1,18 @@ +import { stdin as input, stdout as output } from "node:process"; +import readline from "node:readline"; + +process.stdin.setRawMode(true); +readline.emitKeypressEvents(process.stdin); + +const rl = readline.createInterface({ input, output }); + +const d = new TextDecoder(); + +//@ts-ignore +rl.on("line", input => { + console.log(`Received: ${input}`); +}); + +process.stdin.on("keypress", async (str, key) => { + console.log(str, key); +});