earcon 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
earcon/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Earcon: a self-evolving memory proxy for OpenAI-compatible clients.
2
+
3
+ Any LLM application gets experience-driven learning by changing one
4
+ baseURL. Model weights stay frozen; experience is accumulated,
5
+ adjudicated, and injected as context. See docs/how-it-works.md.
6
+
7
+ Based on the mechanisms of JitRL (arXiv:2601.18510).
8
+ """
9
+
10
+ __version__ = "0.1.0"
earcon/cli.py ADDED
@@ -0,0 +1,72 @@
1
+ # -*- coding: utf-8 -*-
2
+ """CLI: `earcon serve` starts the learning proxy.
3
+
4
+ Examples:
5
+ earcon serve --upstream https://api.openai.com/v1 --api-key $KEY \
6
+ --judge-model gpt-4o-mini --port 8800
7
+
8
+ # pure observation (no injection) while you assess judge quality:
9
+ earcon serve --upstream ... --no-inject
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import os
15
+
16
+
17
+ def build_parser():
18
+ p = argparse.ArgumentParser(prog="earcon", description=__doc__)
19
+ sub = p.add_subparsers(dest="cmd")
20
+ serve = sub.add_parser("serve", help="run the learning proxy gateway")
21
+ serve.add_argument("--upstream", required=True,
22
+ help="OpenAI-compatible upstream base URL, e.g. "
23
+ "https://api.openai.com/v1 "
24
+ "(env: EARCON_UPSTREAM)")
25
+ serve.add_argument("--api-key", default=os.environ.get("EARCON_API_KEY", ""),
26
+ help="key used for upstream calls; clients' own keys "
27
+ "are ignored (env: EARCON_API_KEY)")
28
+ serve.add_argument("--port", type=int, default=8800)
29
+ serve.add_argument("--db", default="earcon_memory.db")
30
+ serve.add_argument("--judge-model", required=True,
31
+ help="model used for credit assignment")
32
+ serve.add_argument("--no-inject", action="store_true",
33
+ help="record-only mode: judge sessions, never inject")
34
+ serve.add_argument("--judge-extra-body", default=None,
35
+ help="JSON object merged into judge requests, for "
36
+ "vendor-private params (e.g. disabling a "
37
+ "reasoning mode). Never sent to the main path.")
38
+ serve.add_argument("--session-timeout", type=float, default=1800,
39
+ help="seconds of inactivity before a session is "
40
+ "closed and judged (default 1800)")
41
+ serve.add_argument("--inject-top-k", type=int, default=5)
42
+ return p
43
+
44
+
45
+ def main(argv=None):
46
+ p = build_parser()
47
+ args = p.parse_args(argv)
48
+ if args.cmd != "serve":
49
+ p.print_help()
50
+ return 2
51
+
52
+ extra = json.loads(args.judge_extra_body) if args.judge_extra_body else None
53
+
54
+ # local imports so the core library never requires fastapi
55
+ from earcon.gateway import Gateway, create_app
56
+ gw = Gateway(upstream=args.upstream, api_key=args.api_key,
57
+ db_path=args.db, judge_model=args.judge_model,
58
+ inject=not args.no_inject, extra_body=extra,
59
+ config={"session_timeout": args.session_timeout,
60
+ "inject_top_k": args.inject_top_k})
61
+ app = create_app(gw)
62
+
63
+ import uvicorn
64
+ print("earcon gateway: http://127.0.0.1:%d -> %s" % (args.port, args.upstream))
65
+ print("memory: %s | mode: %s" % (args.db,
66
+ "record+inject" if gw.inject else "record-only"))
67
+ uvicorn.run(app, host="127.0.0.1", port=args.port, log_level="warning")
68
+ return 0
69
+
70
+
71
+ if __name__ == "__main__":
72
+ raise SystemExit(main())
@@ -0,0 +1,5 @@
1
+ """Core library: memory, advantage estimation, policies, judges, backends.
2
+
3
+ Pure logic, zero third-party dependencies (the OpenAI-compatible backend
4
+ lazily imports `openai` only when used).
5
+ """
@@ -0,0 +1,51 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Advantage estimation: V(s), Q(s,a), A = Q - V, UCB exploration, shrinkage.
3
+
4
+ Corresponds to step 3 of JitRL:
5
+ V = mean return over the neighborhood ("how good is this situation")
6
+ Q = mean return of the cards that took action a
7
+ A = Q - V ("how much better than average")
8
+ unseen actions: UCB-style optimism with probability lam, else 0
9
+
10
+ Two engineering corrections the paper leaves implicit:
11
+
12
+ - small-sample shrinkage: A = (Q - V) * n / (n + m). An action with 1-2
13
+ cards has a noisy Q; max-normalization amplified that noise into a
14
+ full-scale advantage (we observed "bump into a wall" being learned as
15
+ the best action). Shrinkage lets thin evidence speak softly.
16
+ - clip to [-1, 1] instead of max-normalizing: normalization re-amplifies
17
+ relative noise when all advantages are small, cancelling shrinkage.
18
+ """
19
+
20
+ import random
21
+
22
+
23
+ class AdvantageEstimator:
24
+ def __init__(self, lam=0.05, alpha=2.0, min_neighbors=3, shrink=4.0, seed=0):
25
+ self.lam = lam # exploration probability
26
+ self.alpha = alpha # UCB bonus strength
27
+ self.min_neighbors = min_neighbors
28
+ self.shrink = shrink
29
+ self.rng = random.Random(seed)
30
+
31
+ def estimate(self, neighbors, actions):
32
+ """neighbors: [(action, G, sim), ...]; actions: full action list.
33
+ Returns {action: A} clipped to [-1, 1]."""
34
+ n = len(neighbors)
35
+ if n < self.min_neighbors:
36
+ return {a: 0.0 for a in actions}
37
+
38
+ V = sum(G for _, G, _ in neighbors) / n
39
+ adv = {}
40
+ for a in actions:
41
+ Gs = [G for act, G, _ in neighbors if act == a]
42
+ if Gs:
43
+ Q = sum(Gs) / len(Gs)
44
+ adv[a] = (Q - V) * len(Gs) / (len(Gs) + self.shrink)
45
+ else:
46
+ if self.rng.random() < self.lam:
47
+ adv[a] = self.alpha / n
48
+ else:
49
+ adv[a] = 0.0
50
+
51
+ return {a: max(-1.0, min(1.0, v)) for a, v in adv.items()}
@@ -0,0 +1,148 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Model backends: produce per-option "impulse values" (logit or pseudo-logit).
3
+
4
+ - MockBackend: zero-dependency stand-in with human-like biases, for demos
5
+ and tests. It has direction preferences, reacts to objects in sight
6
+ (including distractions), and has no cross-episode memory - exactly the
7
+ flaws a frozen base model exhibits in a new environment.
8
+ - OpenAICompatBackend: real logits via logprobs (the paper's token-level
9
+ path; requires an OpenAI-compatible endpoint that supports logprobs,
10
+ e.g. a self-hosted vLLM). Needs the `openai` package.
11
+ - VerbalConfidenceBackend: black-box fallback for restricted gateways
12
+ (no logprobs): one call asking the model to rate each option 0-100,
13
+ ln(p) as a pseudo-logit. The paper's black-box path. Any vendor-
14
+ private parameters (e.g. disabling a reasoning mode) go through
15
+ `extra_body` and are never sent by default.
16
+ """
17
+
18
+ import json
19
+ import math
20
+ import re
21
+
22
+
23
+ class MockBackend:
24
+ PREFS = {
25
+ "north": 1.2, "east": 1.0, "south": 0.2, "west": 0.0,
26
+ "pick key": -0.5, "take treasure": -0.5, "smash jar": -0.5,
27
+ }
28
+ REFLEX = {
29
+ "a key on the ground": {"pick key": 2.2},
30
+ "you have the key": {"take treasure": 2.2},
31
+ "a chest stands here": {"take treasure": 0.3},
32
+ "a jar sits in the corner": {"smash jar": 0.8},
33
+ }
34
+
35
+ def __init__(self, seed=0, noise=1.0):
36
+ import random
37
+ self.rng = random.Random(seed)
38
+ self.noise = noise
39
+
40
+ def choice_logits(self, prompt, options):
41
+ """options: [(letter, text), ...] -> {letter: logit}"""
42
+ reflex = {}
43
+ low = prompt.lower()
44
+ for marker, boosts in self.REFLEX.items():
45
+ if marker in low:
46
+ for k, v in boosts.items():
47
+ reflex[k] = reflex.get(k, 0.0) + v
48
+ return {
49
+ letter: (self.PREFS.get(text, 0.0) + reflex.get(text, 0.0)
50
+ + self.rng.gauss(0, self.noise))
51
+ for letter, text in options
52
+ }
53
+
54
+
55
+ class OpenAICompatBackend:
56
+ def __init__(self, base_url, api_key, model, timeout=60, retries=2):
57
+ from openai import OpenAI # lazy: core lib stays zero-dependency
58
+ self.client = OpenAI(base_url=base_url, api_key=api_key or "EMPTY",
59
+ timeout=timeout, max_retries=retries)
60
+ self.model = model
61
+
62
+ def choice_logits(self, prompt, options):
63
+ lines = [prompt, "", "Options:"]
64
+ for letter, text in options:
65
+ lines.append("%s. %s" % (letter, text))
66
+ lines.append("Answer with a single letter, nothing else.")
67
+ resp = self.client.chat.completions.create(
68
+ model=self.model,
69
+ messages=[{"role": "user", "content": "\n".join(lines)}],
70
+ max_tokens=1, temperature=0.0,
71
+ logprobs=True, top_logprobs=20)
72
+ top = resp.choices[0].logprobs.content[0].top_logprobs
73
+ logits = {}
74
+ for letter, _ in options:
75
+ hit = [t.logprob for t in top if t.token.strip().upper() == letter]
76
+ if hit:
77
+ logits[letter] = max(hit)
78
+ if not logits:
79
+ return {letter: 0.0 for letter, _ in options}
80
+ floor = min(logits.values()) - 5.0
81
+ return {letter: logits.get(letter, floor) for letter, _ in options}
82
+
83
+ def chat(self, messages, max_tokens=1024):
84
+ resp = self.client.chat.completions.create(
85
+ model=self.model, messages=messages, max_tokens=max_tokens)
86
+ return resp.choices[0].message.content
87
+
88
+
89
+ class VerbalConfidenceBackend:
90
+ """Black-box path: one scoring call, JSON output, ln(p) pseudo-logits."""
91
+
92
+ def __init__(self, base_url, api_key, model, timeout=60, retries=2,
93
+ extra_body=None):
94
+ self.base_url = base_url.rstrip("/")
95
+ self.api_key = api_key
96
+ self.model = model
97
+ self.timeout = timeout
98
+ self.retries = retries
99
+ self.extra_body = dict(extra_body or {})
100
+
101
+ def _post(self, payload):
102
+ import urllib.request
103
+ req = urllib.request.Request(
104
+ self.base_url + "/chat/completions",
105
+ data=json.dumps(payload).encode("utf-8"),
106
+ headers={"Content-Type": "application/json",
107
+ "Authorization": "Bearer " + (self.api_key or "")})
108
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
109
+ return json.loads(r.read().decode("utf-8"))
110
+
111
+ def _chat(self, text, max_tokens):
112
+ payload = {"model": self.model,
113
+ "messages": [{"role": "user", "content": text}],
114
+ "max_tokens": max_tokens, "stream": False}
115
+ payload.update(self.extra_body)
116
+ d = self._post(payload)
117
+ return d["choices"][0]["message"].get("content") or ""
118
+
119
+ def choice_logits(self, prompt, options):
120
+ lines = [prompt, "", "Options:"]
121
+ for letter, text in options:
122
+ lines.append("%s. %s" % (letter, text))
123
+ lines.append("Rate each option 0-100 (higher = more you want to do it)."
124
+ " Output one line of JSON only, e.g. %s"
125
+ % json.dumps({l: 50 for l, _ in options}))
126
+ scores = None
127
+ for _ in range(self.retries + 1):
128
+ try:
129
+ text = self._chat("\n".join(lines), max_tokens=3000)
130
+ m = re.search(r"\{[^{}]*\}", text, re.S)
131
+ scores = json.loads(m.group(0))
132
+ break
133
+ except Exception:
134
+ continue
135
+ if not isinstance(scores, dict):
136
+ return {letter: 0.0 for letter, _ in options}
137
+ logits = {}
138
+ for letter, _ in options:
139
+ try:
140
+ s = float(scores.get(letter, 1))
141
+ except (TypeError, ValueError):
142
+ s = 1.0
143
+ logits[letter] = math.log(max(s, 0.5) / 100.0)
144
+ return logits
145
+
146
+ def chat(self, messages, max_tokens=4096):
147
+ text = "\n\n".join(m["content"] for m in messages)
148
+ return self._chat(text, max_tokens=max_tokens)
earcon/core/judge.py ADDED
@@ -0,0 +1,67 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Judges: credit assignment at episode boundaries, then discounted returns.
3
+
4
+ - ReturnJudge: uses the environment's real per-step rewards (verifiable
5
+ rewards - tests passing, tickets resolved). Default and recommended.
6
+ - LLMJudge: the paper's approach - a model scores each step of the
7
+ trajectory. Quality of the judge bounds the whole system, so failures
8
+ fall back to the verifiable path.
9
+ """
10
+
11
+ import re
12
+
13
+ JUDGE_PROMPT = """You are scoring one episode of an agent's trajectory (outcome: {outcome}).
14
+ Rate each step's contribution to the final outcome on a scale of -3 to +3
15
+ (positive = helped, negative = hurt). Output exactly {n} integer scores,
16
+ one per line, nothing else.
17
+
18
+ {steps}"""
19
+
20
+
21
+ class ReturnJudge:
22
+ """G_t = sum_u gamma^(u-t) * r_u, but normalized by the remaining
23
+ horizon so that early steps in long episodes are not silently
24
+ discounted into irrelevance. A plain discounted return makes G at
25
+ t=0 of a 25-step failure ~-0.15 vs -1.0 at the end; the early
26
+ trap-fall card then looks fine and memory never learns to avoid it.
27
+ G_t = (raw discounted return) / (gamma^(T-t) scale), i.e. the
28
+ average-quality-of-remaining-future interpretation."""
29
+
30
+ def __init__(self, gamma=0.9):
31
+ self.gamma = gamma
32
+
33
+ def score(self, trajectory, success):
34
+ """trajectory: [(state, action, r), ...] -> [(state, action, G), ...]"""
35
+ T = len(trajectory)
36
+ raw = []
37
+ for t in range(T):
38
+ G = sum((self.gamma ** (u - t)) * trajectory[u][2]
39
+ for u in range(t, T))
40
+ raw.append(G / (1 - self.gamma) if self.gamma < 1.0 else G)
41
+ out = [(s, a, g) for (s, a, _), g in zip(trajectory, raw)]
42
+ return out
43
+
44
+
45
+ class LLMJudge:
46
+ def __init__(self, backend, gamma=0.9, scale=3.0):
47
+ self.backend = backend
48
+ self.fallback = ReturnJudge(gamma)
49
+ self.scale = scale
50
+
51
+ def score(self, trajectory, success):
52
+ steps = "\n".join(
53
+ "%d. [%s] -> %s" % (i + 1, s, a)
54
+ for i, (s, a, _) in enumerate(trajectory))
55
+ prompt = JUDGE_PROMPT.format(
56
+ outcome="success" if success else "failure",
57
+ n=len(trajectory), steps=steps)
58
+ try:
59
+ text = self.backend.chat([{"role": "user", "content": prompt}])
60
+ nums = [int(x) for x in re.findall(r"-?\d+", text)]
61
+ if len(nums) < len(trajectory):
62
+ raise ValueError("not enough scores")
63
+ shaped = [(s, a, n / float(self.scale))
64
+ for (s, a, _), n in zip(trajectory, nums)]
65
+ return self.fallback.score(shaped, success)
66
+ except Exception:
67
+ return self.fallback.score(trajectory, success)
earcon/core/memory.py ADDED
@@ -0,0 +1,94 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Experience memory: (state, action, return) cards in SQLite, Jaccard retrieval.
3
+
4
+ Non-parametric memory in the JitRL sense. Structured-text + Jaccard was
5
+ empirically better than embeddings in our experiments (and needs no
6
+ vector infra), so retrieval is deliberately simple. Two corrections the
7
+ paper leaves implicit are built in:
8
+
9
+ - recency pool: experience is non-stationary; recent cards must win ties
10
+ against early failures (otherwise learning curves can stall and even
11
+ regress as stale cards keep occupying the neighborhood);
12
+ - single-token coordinates: naive tokenization can treat "r0c1" and
13
+ "r1c0" as the same token set, silently conflating distinct states.
14
+ Callers should compose position-like attributes into one token.
15
+ """
16
+
17
+ import re
18
+ import sqlite3
19
+ import time
20
+
21
+ _TOKEN_RE = re.compile(r"[A-Za-z0-9]+|[一-鿿]")
22
+
23
+
24
+ def tokenize(text):
25
+ """Latin/digits by word, CJK by character; returns a set for Jaccard."""
26
+ return set(_TOKEN_RE.findall(text or ""))
27
+
28
+
29
+ def jaccard(a, b):
30
+ if not a or not b:
31
+ return 0.0
32
+ inter = len(a & b)
33
+ return inter / float(len(a) + len(b) - inter)
34
+
35
+
36
+ class MemoryStore:
37
+ def __init__(self, db_path="earcon_memory.db", max_cards=5000,
38
+ recency_pool=2000):
39
+ self.conn = sqlite3.connect(db_path, check_same_thread=False)
40
+ self.lock = __import__("threading").Lock()
41
+ self.max_cards = max_cards
42
+ self.recency_pool = recency_pool
43
+ self.conn.execute(
44
+ """CREATE TABLE IF NOT EXISTS cards(
45
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
46
+ namespace TEXT,
47
+ state TEXT,
48
+ action TEXT,
49
+ G REAL,
50
+ created REAL)""")
51
+ self.conn.commit()
52
+
53
+ def add(self, namespace, state, action, G):
54
+ with self.lock:
55
+ self.conn.execute(
56
+ "INSERT INTO cards(namespace, state, action, G, created) "
57
+ "VALUES(?,?,?,?,?)",
58
+ (namespace, state, action, G, time.time()))
59
+ self.conn.commit()
60
+ n = self.conn.execute("SELECT COUNT(*) FROM cards").fetchone()[0]
61
+ if n > self.max_cards:
62
+ self.conn.execute(
63
+ "DELETE FROM cards WHERE id IN "
64
+ "(SELECT id FROM cards ORDER BY id LIMIT ?)",
65
+ (n - self.max_cards,))
66
+ self.conn.commit()
67
+
68
+ def retrieve(self, namespace, state, k=10, min_sim=0.9):
69
+ """Most-similar k cards as [(action, G, sim), ...].
70
+
71
+ min_sim defaults high (near-exact match) for discrete-state tasks;
72
+ lower it for fuzzier domains. Ties prefer newer cards.
73
+ """
74
+ rows = self.conn.execute(
75
+ "SELECT state, action, G FROM cards WHERE namespace=? "
76
+ "ORDER BY id DESC LIMIT ?",
77
+ (namespace, self.recency_pool)).fetchall()
78
+ if not rows:
79
+ return []
80
+ q = tokenize(state)
81
+ scored = [(action, G, jaccard(q, tokenize(s))) for s, action, G in rows]
82
+ scored = [x for x in scored if x[2] >= min_sim]
83
+ scored.sort(key=lambda x: -x[2])
84
+ return scored[:k]
85
+
86
+ def size(self, namespace=None):
87
+ if namespace is None:
88
+ return self.conn.execute("SELECT COUNT(*) FROM cards").fetchone()[0]
89
+ return self.conn.execute(
90
+ "SELECT COUNT(*) FROM cards WHERE namespace=?",
91
+ (namespace,)).fetchone()[0]
92
+
93
+ def close(self):
94
+ self.conn.close()
earcon/core/policy.py ADDED
@@ -0,0 +1,62 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Policy: z' = z + beta * A, the closed-form update of KL-constrained
3
+ policy improvement. Works over any backend that produces per-option
4
+ "impulse values" (logits or pseudo-logits).
5
+
6
+ use_memory=False degrades to the pure base policy (the control arm).
7
+ """
8
+
9
+ import math
10
+ import random
11
+
12
+
13
+ class JitRLPolicy:
14
+ def __init__(self, backend, memory, estimator, beta=3.0,
15
+ use_memory=True, greedy=False, seed=0):
16
+ self.backend = backend
17
+ self.memory = memory
18
+ self.estimator = estimator
19
+ self.beta = beta
20
+ self.use_memory = use_memory
21
+ self.greedy = greedy
22
+ self.rng = random.Random(seed)
23
+
24
+ def act(self, prompt, state, namespace, actions):
25
+ """Returns (chosen action, debug info). actions: list of texts."""
26
+ options = [(chr(ord("A") + i), a) for i, a in enumerate(actions)]
27
+ z = self.backend.choice_logits(prompt, options)
28
+
29
+ adv = {a: 0.0 for a in actions}
30
+ n_neighbors = 0
31
+ if self.use_memory:
32
+ neighbors = self.memory.retrieve(namespace, state)
33
+ n_neighbors = len(neighbors)
34
+ adv = self.estimator.estimate(neighbors, actions)
35
+
36
+ adjusted = {
37
+ letter: z[letter] + self.beta * adv[text]
38
+ for letter, text in options
39
+ }
40
+
41
+ best = (max(adjusted, key=adjusted.get) if self.greedy
42
+ else self._softmax_sample(adjusted))
43
+
44
+ debug = {
45
+ "neighbors": n_neighbors,
46
+ "logits": {t: round(z[l], 2) for l, t in options},
47
+ "advantage": {t: round(adv[t], 2) for _, t in options},
48
+ "chosen": options[ord(best) - ord("A")][1],
49
+ }
50
+ return debug["chosen"], debug
51
+
52
+ def _softmax_sample(self, logits):
53
+ m = max(logits.values())
54
+ exps = {k: math.exp(v - m) for k, v in logits.items()}
55
+ total = sum(exps.values())
56
+ r = self.rng.random() * total
57
+ acc = 0.0
58
+ for k, v in exps.items():
59
+ acc += v
60
+ if r <= acc:
61
+ return k
62
+ return list(logits)[-1]
@@ -0,0 +1,316 @@
1
+ # -*- coding: utf-8 -*-
2
+ """The earcon gateway: a transparent OpenAI-compatible proxy that learns.
3
+
4
+ Request path (every turn):
5
+ client -> [experience injection] -> transparent forward -> upstream
6
+ response streams back while the turn is recorded into a session buffer.
7
+
8
+ Learning path (session close, background thread):
9
+ an LLM judge distills the trajectory into experience cards ->
10
+ SQLite memory -> retrieved for future sessions' injections.
11
+
12
+ For free-text coding/chat sessions (no enumerable action space) the
13
+ JitRL logit adjustment is realized as context injection instead: it is
14
+ the same loop (experience -> behavior change) at the fidelity the
15
+ protocol allows. The core library (earcon.core) implements the discrete
16
+ logit path used by examples/treasure_maze.
17
+ """
18
+
19
+ import json
20
+ import re
21
+ import sqlite3
22
+ import threading
23
+ import time
24
+ import urllib.request
25
+
26
+ from fastapi import FastAPI, Request
27
+ from fastapi.responses import JSONResponse, StreamingResponse
28
+
29
+ DEFAULTS = {
30
+ "session_timeout": 1800.0, # seconds of inactivity -> session close
31
+ "sweep_interval": 60.0, # how often the reaper checks for timeouts
32
+ "max_turns_judged": 40,
33
+ "min_turns_to_judge": 3,
34
+ "task_sig_chars": 120, # task signature length for retrieval
35
+ "inject_top_k": 5, # cards per injection
36
+ "inject_threshold": 0.15, # |G| beyond which a card is useful/a lesson
37
+ "retrieve_scan_limit": 3000, # recent-card scan window
38
+ "retrieve_min_overlap": 2, # keyword overlap to count as related
39
+ "turn_user_chars": 2000,
40
+ "turn_assistant_chars": 4000,
41
+ }
42
+
43
+ JUDGE_PROMPT = """Below is the full trajectory of a coding-assistant session
44
+ (user request -> assistant key response). Distill 1-5 reusable experience
45
+ cards from the assistant's performance. One card per line, format:
46
+ decision=<a key decision the assistant got right or wrong, max 30 words> ; score=<integer -3..3, positive if right, negative if wrong>
47
+ Output only those lines.
48
+
49
+ {steps}"""
50
+
51
+
52
+ class GatewayMemory:
53
+ def __init__(self, db_path):
54
+ self.conn = sqlite3.connect(db_path, check_same_thread=False)
55
+ self.lock = threading.Lock()
56
+ self.conn.execute(
57
+ """CREATE TABLE IF NOT EXISTS cards(
58
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
59
+ task TEXT,
60
+ action TEXT,
61
+ G REAL,
62
+ created REAL)""")
63
+ self.conn.commit()
64
+
65
+ def add(self, task, action, G):
66
+ with self.lock:
67
+ self.conn.execute(
68
+ "INSERT INTO cards(task, action, G, created) VALUES(?,?,?,?)",
69
+ (task, action, G, time.time()))
70
+ self.conn.commit()
71
+
72
+ def size(self):
73
+ return self.conn.execute("SELECT COUNT(*) FROM cards").fetchone()[0]
74
+
75
+ def retrieve_top(self, task_sig, scan_limit, min_overlap, k):
76
+ rows = self.conn.execute(
77
+ "SELECT task, action, G FROM cards ORDER BY id DESC LIMIT ?",
78
+ (scan_limit,)).fetchall()
79
+ if not rows:
80
+ return []
81
+ q = set(re.findall(r"[\w一-鿿]+", (task_sig or "").lower()))
82
+ scored = []
83
+ for task, action, G in rows:
84
+ t = set(re.findall(r"[\w一-鿿]+", (task or "").lower()))
85
+ inter = len(q & t)
86
+ if inter >= min_overlap:
87
+ scored.append((inter, G, action))
88
+ scored.sort(key=lambda x: (-x[0], -x[1]))
89
+ return scored[:k]
90
+
91
+
92
+ class Gateway:
93
+ def __init__(self, upstream, api_key, db_path, judge_model,
94
+ inject=True, extra_body=None, config=None):
95
+ self.upstream = upstream.rstrip("/")
96
+ self.api_key = api_key
97
+ self.judge_model = judge_model
98
+ self.inject = inject
99
+ self.extra_body = dict(extra_body or {})
100
+ self.conf = dict(DEFAULTS)
101
+ self.conf.update(config or {})
102
+ self.mem = GatewayMemory(db_path)
103
+
104
+ self.sessions = {} # sid -> {"turns": [...], "last": ts}
105
+ self.session_lock = threading.Lock()
106
+ self._stop = threading.Event()
107
+ self.reaper = threading.Thread(target=self._reap_loop, daemon=True)
108
+ self.reaper.start()
109
+
110
+ # ---------------- session bookkeeping ----------------
111
+
112
+ def record_turn(self, sid, user_text, assistant_text):
113
+ c = self.conf
114
+ with self.session_lock:
115
+ s = self.sessions.setdefault(sid, {"turns": [], "last": time.time()})
116
+ s["turns"].append((user_text[:c["turn_user_chars"]],
117
+ (assistant_text or "")[:c["turn_assistant_chars"]]))
118
+ s["last"] = time.time()
119
+
120
+ def close_session(self, sid):
121
+ with self.session_lock:
122
+ s = self.sessions.pop(sid, None)
123
+ if s and len(s["turns"]) >= self.conf["min_turns_to_judge"]:
124
+ threading.Thread(target=self._judge_and_write,
125
+ args=(s["turns"],), daemon=True).start()
126
+ return len((s or {}).get("turns", []))
127
+
128
+ def _reap_loop(self):
129
+ while not self._stop.wait(self.conf["sweep_interval"]):
130
+ now = time.time()
131
+ stale = []
132
+ with self.session_lock:
133
+ for sid, s in list(self.sessions.items()):
134
+ if now - s["last"] > self.conf["session_timeout"]:
135
+ stale.append(sid)
136
+ for sid in stale:
137
+ self.close_session(sid)
138
+
139
+ # ---------------- judging ----------------
140
+
141
+ def _judge_and_write(self, turns):
142
+ try:
143
+ sig = self._task_signature(turns)
144
+ if not sig:
145
+ return
146
+ c = self.conf
147
+ lines = ["%d. user: %s" % (i + 1, u[:600])
148
+ for i, (u, a) in enumerate(turns[:c["max_turns_judged"]])]
149
+ steps = "\n".join(
150
+ "%d. user: %s\n assistant: %s"
151
+ % (i + 1, u[:600], a[:600])
152
+ for i, (u, a) in enumerate(turns[:c["max_turns_judged"]]))
153
+ text = self._llm_chat(JUDGE_PROMPT.format(steps=steps))
154
+ for line in text.splitlines():
155
+ m = re.search(r"decision=(.+?)\s*;\s*score=(-?\d+)", line)
156
+ if m:
157
+ self.mem.add(sig, m.group(1).strip(),
158
+ int(m.group(2)) / 3.0)
159
+ except Exception as e:
160
+ print("[earcon] judge error:", e)
161
+
162
+ def _task_signature(self, turns):
163
+ for u, _ in turns:
164
+ if u.strip():
165
+ return u[:self.conf["task_sig_chars"]]
166
+ return ""
167
+
168
+ def _llm_chat(self, prompt, max_tokens=2000):
169
+ payload = {"model": self.judge_model,
170
+ "messages": [{"role": "user", "content": prompt}],
171
+ "max_tokens": max_tokens, "stream": False,
172
+ "temperature": 0.0}
173
+ payload.update(self.extra_body)
174
+ req = urllib.request.Request(
175
+ self.upstream + "/chat/completions",
176
+ data=json.dumps(payload).encode("utf-8"),
177
+ headers={"Content-Type": "application/json",
178
+ "Authorization": "Bearer " + (self.api_key or "")})
179
+ with urllib.request.urlopen(req, timeout=120) as r:
180
+ d = json.loads(r.read().decode("utf-8"))
181
+ return d["choices"][0]["message"].get("content") or ""
182
+
183
+ # ---------------- injection ----------------
184
+
185
+ def experience_prefix(self, task_sig):
186
+ c = self.conf
187
+ top = self.mem.retrieve_top(task_sig, c["retrieve_scan_limit"],
188
+ c["retrieve_min_overlap"], c["inject_top_k"])
189
+ if not top:
190
+ return None
191
+ lines = ["[earcon experience] lessons from past similar sessions:"]
192
+ for _, G, action in top:
193
+ tag = ("worked" if G > c["inject_threshold"]
194
+ else "failed" if G < -c["inject_threshold"] else "mixed")
195
+ lines.append("- (%s) %s" % (tag, action))
196
+ lines.append("Treat these as historical summaries; use your own "
197
+ "judgment for the current task.")
198
+ return "\n".join(lines)
199
+
200
+ # ---------------- HTTP ----------------
201
+
202
+ def _forward(self, body):
203
+ req = urllib.request.Request(
204
+ self.upstream + "/chat/completions",
205
+ data=json.dumps(body).encode("utf-8"),
206
+ headers={"Content-Type": "application/json",
207
+ "Authorization": "Bearer " + (self.api_key or "")})
208
+ return urllib.request.urlopen(req, timeout=300)
209
+
210
+ def handle_chat(self, body, auth_key):
211
+ messages = body.get("messages", [])
212
+
213
+ # session id: honor explicit metadata, else one request per session
214
+ # is naturally grouped by close_session/timeout sweeps
215
+ sid = (body.get("metadata") or {}).get("session_id") or "default"
216
+
217
+ if self.inject and messages:
218
+ sig = (_first_user_text(messages) or "")[:self.conf["task_sig_chars"]]
219
+ if sig.strip():
220
+ prefix = self.experience_prefix(sig)
221
+ if prefix:
222
+ new_msgs, inserted = [], False
223
+ for m in messages:
224
+ new_msgs.append(m)
225
+ if not inserted and m.get("role") == "system":
226
+ new_msgs.append({"role": "system", "content": prefix})
227
+ inserted = True
228
+ if not inserted:
229
+ new_msgs.insert(0, {"role": "system", "content": prefix})
230
+ body = dict(body)
231
+ body["messages"] = new_msgs
232
+
233
+ upstream_key = self.api_key or auth_key
234
+ stream = body.get("stream", False)
235
+ body_json = json.dumps(body).encode("utf-8")
236
+ headers = {"Content-Type": "application/json",
237
+ "Authorization": "Bearer " + upstream_key}
238
+ req = urllib.request.Request(self.upstream + "/chat/completions",
239
+ data=body_json, headers=headers)
240
+ up_resp = urllib.request.urlopen(req, timeout=300)
241
+
242
+ if stream:
243
+ def gen():
244
+ collected = []
245
+ try:
246
+ for chunk in up_resp:
247
+ yield chunk
248
+ try:
249
+ line = chunk.decode("utf-8").strip()
250
+ if line.startswith("data: ") and line != "data: [DONE]":
251
+ j = json.loads(line[6:])
252
+ delta = (j.get("choices") or [{}])[0].get("delta", {})
253
+ if delta.get("content"):
254
+ collected.append(delta["content"])
255
+ except Exception:
256
+ pass
257
+ finally:
258
+ if collected:
259
+ self.record_turn(sid, _first_user_text(messages) or "",
260
+ "".join(collected))
261
+
262
+ return StreamingResponse(gen(), media_type="text/event-stream")
263
+ else:
264
+ d = json.loads(up_resp.read().decode("utf-8"))
265
+ content = (d["choices"][0]["message"].get("content") or "")
266
+ self.record_turn(sid, _first_user_text(messages) or "", content)
267
+ return d
268
+
269
+
270
+ def _first_user_text(messages):
271
+ for m in messages:
272
+ if m.get("role") == "user":
273
+ c = m.get("content")
274
+ if isinstance(c, str):
275
+ return c
276
+ if isinstance(c, list):
277
+ for part in c:
278
+ if isinstance(part, dict) and part.get("type") == "text":
279
+ return part.get("text", "")
280
+ return ""
281
+
282
+
283
+ def create_app(gateway):
284
+ app = FastAPI()
285
+
286
+ @app.post("/v1/chat/completions")
287
+ @app.post("/chat/completions")
288
+ async def proxy_chat(request: Request):
289
+ body = await request.json()
290
+ auth_key = request.headers.get("Authorization", "").replace("Bearer ", "")
291
+ result = gateway.handle_chat(body, auth_key)
292
+ if isinstance(result, StreamingResponse):
293
+ return result
294
+ return JSONResponse(result)
295
+
296
+ @app.get("/v1/models")
297
+ @app.get("/models")
298
+ async def models():
299
+ req = urllib.request.Request(
300
+ gateway.upstream + "/models",
301
+ headers={"Authorization": "Bearer " + (gateway.api_key or "")})
302
+ with urllib.request.urlopen(req, timeout=30) as r:
303
+ return JSONResponse(json.loads(r.read().decode("utf-8")))
304
+
305
+ @app.get("/v1/earcon/stats")
306
+ async def stats():
307
+ return JSONResponse({"cards": gateway.mem.size(),
308
+ "sessions_open": len(gateway.sessions),
309
+ "inject": gateway.inject})
310
+
311
+ @app.post("/v1/earcon/session/{sid}/close")
312
+ async def close_session(sid: str):
313
+ n = gateway.close_session(sid)
314
+ return JSONResponse({"closed": sid, "turns": n})
315
+
316
+ return app
@@ -0,0 +1,182 @@
1
+ Metadata-Version: 2.4
2
+ Name: earcon
3
+ Version: 0.1.0
4
+ Summary: A self-evolving memory proxy for OpenAI-compatible clients: any LLM app gets experience-driven learning by changing one baseURL.
5
+ License: Apache-2.0
6
+ Keywords: llm,agents,memory,self-improvement,jitrl,proxy,reinforcement-learning
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: gateway
20
+ Requires-Dist: fastapi>=0.100; extra == "gateway"
21
+ Requires-Dist: uvicorn>=0.23; extra == "gateway"
22
+ Provides-Extra: openai
23
+ Requires-Dist: openai>=1.0; extra == "openai"
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=7.0; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # earcon
29
+
30
+ **A self-evolving memory proxy for OpenAI-compatible clients.**
31
+ Point your app's `base_url` at earcon, keep working normally - the model
32
+ starts learning from every session, with **zero weight updates** and
33
+ **zero client changes beyond one URL**.
34
+
35
+ - **What it is**: a local proxy that records your LLM sessions, has a
36
+ judge distill them into experience cards (a decision + a score), and
37
+ injects the relevant experience into future similar sessions.
38
+ - **What it is not**: not fine-tuning, not another RAG memory of user
39
+ facts. It stores *behavioral* experience with returns - "this approach
40
+ worked, that one failed" - and changes decisions, not just knowledge.
41
+ - **Lineage**: mechanisms from [JitRL: Just-In-Time Reinforcement
42
+ Learning](https://arxiv.org/abs/2601.18510) (ICML 2026 Spotlight):
43
+ non-parametric experience memory, advantage estimation, and
44
+ experience-driven action reweighting - realized for free-text agents.
45
+
46
+ ```
47
+ your app (any OpenAI SDK / LangGraph / coding client ...)
48
+ │ change one base_url
49
+
50
+ earcon gateway ──① inject experience──▶ upstream LLM (frozen weights)
51
+ │ ② record every turn
52
+
53
+ ③ judge on session close ──▶ ④ SQLite experience cards ──▶ back to ①
54
+ ```
55
+
56
+ ![architecture](docs/architecture.png)
57
+
58
+ ## Why not just mem0 / Letta / Zep?
59
+
60
+ Those store *facts* ("the user prefers concise answers") and retrieve
61
+ them into context. earcon stores **scored behavior** and follows the
62
+ JitRL loop:
63
+
64
+ | | fact memories (mem0 et al.) | earcon |
65
+ |---|---|---|
66
+ | Stored unit | "user likes X" | "decision D on task T scored -3" |
67
+ | Signal | none (storage only) | return / judge credit assignment |
68
+ | Changes decisions? | indirectly, via recall | directly - experience is *retrieved by task similarity and weighted by outcome* |
69
+ | Auditable | depends | one SQLite file, every card inspectable |
70
+ | Intrusive | SDK / API changes | one `base_url` swap |
71
+
72
+ ## Quickstart
73
+
74
+ ```bash
75
+ # legacy pip (<22) mishandles pyproject-only git installs (UNKNOWN-0.0.0):
76
+ python3 -m pip install --upgrade pip
77
+
78
+ # from GitHub (PyPI coming soon):
79
+ python3 -m pip install "git+https://github.com/370540009gg-cmd/earcon.git"
80
+ # extras: "earcon[gateway,openai]" via pip, or install fastapi/uvicorn yourself
81
+
82
+ # terminal 1: run the gateway against any OpenAI-compatible upstream
83
+ earcon serve --upstream https://api.openai.com/v1 \
84
+ --api-key $OPENAI_API_KEY --judge-model gpt-4o-mini
85
+
86
+ # terminal 2: any OpenAI app, one line changed
87
+ # OpenAI(base_url="http://127.0.0.1:8800/v1", ...)
88
+ python examples/quickstart_client.py
89
+ ```
90
+
91
+ Work normally. Sessions close (30 min idle, or explicit
92
+ `POST /v1/earcon/session/default/close`), the judge distills cards,
93
+ and future similar requests arrive pre-loaded with your own track
94
+ record:
95
+
96
+ ```bash
97
+ curl http://127.0.0.1:8800/v1/earcon/stats
98
+ # {"cards": 14, "sessions_open": 1, "inject": true}
99
+
100
+ sqlite3 earcon_memory.db "SELECT task, action, G FROM cards LIMIT 5"
101
+ ```
102
+
103
+ **Start in observation mode** while you assess your judge's card
104
+ quality: `earcon serve ... --no-inject`. The judge is the quality
105
+ ceiling of the whole system.
106
+
107
+ ## Does it actually work?
108
+
109
+ The discrete-action path is verified in `examples/treasure_maze/` - a
110
+ toy environment where traps sit on the intuitive routes, so avoiding
111
+ them is *only* knowable through experience:
112
+
113
+ ```bash
114
+ # control arm (frozen behavior): ~2% win, 4.0 trap falls / episode
115
+ python examples/treasure_maze/run.py --episodes 150 --seed 2 --no-memory
116
+
117
+ # earcon learning arm: ~43% win (up to 100% in late windows),
118
+ python examples/treasure_maze/run.py --episodes 150 --seed 2
119
+ # 1.0 falls/episode, 10.5 steps vs 6 optimal
120
+ ```
121
+
122
+ The learned advantage at the trap-adjacent cells comes out correctly
123
+ signed - memory, not luck. See `docs/how-it-works.md` for the full
124
+ loop, and the honest list of conditions under which it *won't* work.
125
+
126
+ ## How it works
127
+
128
+ 1. **Record** - every turn flows through the gateway transparently
129
+ (streaming included) into a session buffer.
130
+ 2. **Judge** - on session close, a background judge call distills 1-5
131
+ experience cards ("decision=...; score -3..+3").
132
+ 3. **Retrieve & inject** - the next session's first user message is
133
+ matched against past cards; the top matches join the system prompt.
134
+
135
+ For **enumerable action spaces** (agents, tools), `earcon.core`
136
+ implements the paper's full path: per-option logits from `logprobs`,
137
+ advantage `A = Q - V` with small-sample shrinkage, and the closed-form
138
+ update `z' = z + βA`. The maze example runs it end to end.
139
+
140
+ Details and design corrections: `docs/how-it-works.md` · client
141
+ integration guide: `docs/client-integration.md`.
142
+
143
+ ## Configuration
144
+
145
+ `earcon serve --upstream URL --judge-model M [--api-key K]
146
+ [--db FILE] [--port 8800] [--no-inject] [--session-timeout 1800]
147
+ [--inject-top-k 5] [--judge-extra-body '{"thinking":{"type":"off"}}']`
148
+
149
+ - Credentials: `EARCON_API_KEY` env var or `--api-key`. The gateway
150
+ rewrites client keys with its own, so clients need no real key.
151
+ - Vendor-private judge parameters (e.g. disabling a reasoning mode for
152
+ the scoring call) go through `--judge-extra-body`; nothing
153
+ non-standard is sent by default.
154
+
155
+ ## Honest limitations
156
+
157
+ - **The judge is the ceiling.** A shallow judge produces noisy cards;
158
+ start with `--no-inject` and audit them.
159
+ - **Injection, not logits, on the main path** - most hosted gateways
160
+ don't expose `logprobs`, so free-text learning happens through
161
+ context. The full logit path needs a `logprobs`-capable upstream
162
+ (vLLM etc.) and lives in `earcon.core`.
163
+ - **Cold start requires a working base.** If the model never succeeds,
164
+ there are no positive cards to reinforce (JitRL has the same
165
+ constraint). Rough sweet spot: base success in the 20-60% band.
166
+ - **Single-user, single-process.** No multi-tenant isolation; memory is
167
+ one SQLite file. The session reaper is a background thread, not a
168
+ distributed system.
169
+ - **Task matching is keyword-based.** Deliberately (it beat embeddings
170
+ in our maze experiments and needs no infra), but it's simple.
171
+
172
+ ## Roadmap
173
+
174
+ - [ ] Hermes agent `MemoryProvider` adapter
175
+ - [ ] Server-side logit bias via vLLM `logit_bias` (true step-level steering)
176
+ - [ ] Card editor / curation CLI
177
+ - [ ] Multi-namespace memory (per-project, per-tenant)
178
+
179
+ ## License
180
+
181
+ Apache-2.0. Built on the mechanisms of [JitRL](https://arxiv.org/abs/2601.18510)
182
+ (Barrett et al.) - if you use earcon in research, please cite the paper.
@@ -0,0 +1,15 @@
1
+ earcon/__init__.py,sha256=6FZ4KvyfOneLXshTWONLo6I00_bCe8795tobL9bplBw,348
2
+ earcon/cli.py,sha256=HUCXlIrL7qRFl3rp15_WKOWrkCuTYGEC2TMQuK1j6No,3029
3
+ earcon/core/__init__.py,sha256=69wlQJzcIsuYfoXg1ZuRH4Q6fvWX52G09KSsOugpnSI,194
4
+ earcon/core/advantage.py,sha256=uJGzRHClnqO4x7vZ85XVkye2tisnvTOVFLMCOrurMP4,2031
5
+ earcon/core/backends.py,sha256=1kYi2PycBJkhX-GDFLjuYsMJKiUYcZIkj9pidh5tcB0,5997
6
+ earcon/core/judge.py,sha256=VgrQIfQGujS4AXAvMRKXTnoujOpcb4QG6kw9ISIVq4M,2721
7
+ earcon/core/memory.py,sha256=GZ89jz0ex9_rWkYdYWmqw3Tf-ISd8Z3oxvuJ7phVcCg,3507
8
+ earcon/core/policy.py,sha256=xkfoK6J3AOHw4e0DuigVTpixTsdBWg8kTJbLgOwLOhY,2090
9
+ earcon/gateway/__init__.py,sha256=2-laMa--kdi8X4g0EM8PDQ1N1JJaf_m1LKJ3VhmW5fA,12809
10
+ earcon-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
11
+ earcon-0.1.0.dist-info/METADATA,sha256=FvZqL5TwATGlXjdKTqDYTCU_2pPy9A7kFCNvViyioWI,7615
12
+ earcon-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
13
+ earcon-0.1.0.dist-info/entry_points.txt,sha256=WEDXC35pHLWkZEVy50_SS3i-b6AaaPMvbwCdJbqcc7o,43
14
+ earcon-0.1.0.dist-info/top_level.txt,sha256=HmdG_LkVgOhEbCm2Uh5K6TIrDn1606aWRxDfGz4YVAo,7
15
+ earcon-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ earcon = earcon.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ earcon